Closed15

Vagrant + Debian10 でWordPressの開発環境を構築する

sfuksfuk

1. 構築準備

■ 目的

WordPressの開発環境構築を目的としますが、
自分のLinux環境トレーニングを兼ねます。

debian環境は下記で構築予定
・nginx
・php-fpm
・MariaDB
・WordPress

■ 利用するソフトウェア

※verは現時点で最新
・virtualbox 6.1.16
・vagrant 2.2.14

virtualbox
vagrant

■ [ホストOS] vagrant boxの追加

https://app.vagrantup.com/generic/boxes/debian10

$ vagrant box add generic/debian10
==> box: Loading metadata for box 'generic/debian10'
    box: URL: https://vagrantcloud.com/generic/debian10
This box can work with multiple providers! The providers that it
can work with are listed below. Please review the list and choose
the provider you will be working with.

1) docker
2) hyperv
3) libvirt
4) parallels
5) virtualbox
6) vmware_desktop

Enter your choice: 5
==> box: Adding box 'generic/debian10' (v3.1.6) for provider: virtualbox
...
...

# [※確認] boxが追加された事を確認する 
$ vagrant box list
generic/debian10   (virtualbox, 3.1.6)

■ [ホストOS] vm用ファルダ・Vagrantfile作成

$ mkdir debian10-dev

$ mkdir -p debian10-dev/vagrant

$ mkdir -p debian10-dev/wordpress

$ touch debian10-dev/Vagrantfile  # 空ファイルを作成

$ tree debian10-dev/
debian10-dev/
├── vagrant/
├── Vagrantfile
└── wordpress/

■ [ホストOS] Vagrantfile編集

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  # Debian10
  config.vm.box = "generic/debian10"

  # network
  config.vm.network "private_network", ip: "192.168.100.10"  # 任意のipを設定する

  # macine
  config.vm.provider "virtualbox" do |vb|
    vb.name = "debian10-dev-wp"
    vb.memory = "1024"
	vb.cpus = "1"
  end

  # sync dir
  config.vm.synced_folder "./wordpress", '/var/www/wordpress', :mount_options => ['dmode=777', 'fmode=777']
  config.vm.synced_folder "./vagrant", '/vagrant', :mount_options => ['dmode=777', 'fmode=777']
end
sfuksfuk

2. 仮想マシンの起動と確認

■ [ホストOS] vagrant 起動(初回)

初回起動でコケました。。。
VirtualBoxのGuest Additions toolsに問題があるみたいですね
VirtualBoxのverとGuest Additionsのverが合わないと出るエラーみたいですねー

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'generic/debian10'...
...
...
==> default: Mounting shared folders...
default: /vagrant => C:/debian10/vagrant
Vagrant was unable to mount VirtualBox shared folders. This is usually
because the filesystem "vboxsf" is not available. This filesystem is
made available via the VirtualBox Guest Additions and kernel module.
Please verify that these guest additions are properly installed in the
guest. This is not a bug in Vagrant and is usually caused by a faulty
Vagrant box. For context, the command attempted was:

mount -t vboxsf -o dmode=777,fmode=777,uid=1000,gid=1000 vagrant /vagrant

The error output from the command was:

/sbin/mount.vboxsf: mounting failed with the error: No such device

# 仮想マシンを停止する
$ vagrant halt
==> default: Attempting graceful shutdown of VM...

■ [ホストOS] vagrant にプラグイン「vagrant-vbguest」をインストールする

※vagrant up時、自動でVirtualBoxのバージョンに合わせ、
 Guest Additionsのバージョンを更新するプラグイン

$ vagrant plugin install vagrant-vbguest
Installing the 'vagrant-vbguest' plugin. This can take a few minutes...
Fetching micromachine-3.0.0.gem
Fetching vagrant-vbguest-0.28.0.gem
Installed the plugin 'vagrant-vbguest (0.28.0)'!

■ [ホストOS] vagrant 起動(2回目)

起動できた!👏

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'generic/debian10' version '3.1.6' is up to date...
...
...
==> default: Mounting shared folders...
    default: /vagrant => C:/debian10/vagrant
    default: /var/www/wordpress => C:/debian10/wordpress
==> default: Detected mount owner ID within mount options. (uid: 1000 guestpath: /vagrant)
==> default: Detected mount group ID within mount options. (gid: 1000 guestpath: /vagrant)
==> default: Detected mount owner ID within mount options. (uid: 1000 guestpath: /var/www/wordpress)
==> default: Detected mount group ID within mount options. (gid: 1000 guestpath: /var/www/wordpress)

■ [ゲストOS] 状況確認

# ゲストOSにsshでログインする
$ vagrant ssh
Last login: Mon Nov 23 12:16:44 2020 from 10.0.2.2
vagrant@debian10:~$ 

# mountフォルダ確認「vagrant」
vagrant@debian10:/$ ls -la /vagrant/
total 4
drwxrwxrwx  1 vagrant vagrant    0 Nov 23 12:09 .
drwxr-xr-x 19 root    root    4096 Nov 23 12:12 ..

# mountフォルダ確認「wordpress」
vagrant@debian10:/$ ls -la /var/www/wordpress/
total 4
drwxrwxrwx 1 vagrant vagrant    0 Nov 23 12:10 .
drwxr-xr-x 3 root    root    4096 Nov 23 12:29 ..

# OSバージョン確認
vagrant@debian10:/$ cat /etc/debian_version
10.6

vagrant@debian10:/$ cat /etc/os-release
PRETTY_NAME="Debian GNU/Linux 10 (buster)"
NAME="Debian GNU/Linux"
VERSION_ID="10"
VERSION="10 (buster)"
VERSION_CODENAME=buster
ID=debian
HOME_URL="https://www.debian.org/"
SUPPORT_URL="https://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"

# タイムゾーンの確認
# デフォルトはUTC
vagrant@debian10:/$ date
Mon 23 Nov 2020 12:41:36 PM UTC

vagrant@debian10:/$ timedatectl 
               Local time: Mon 2020-11-23 12:41:56 UTC
           Universal time: Mon 2020-11-23 12:41:56 UTC
                 RTC time: Mon 2020-11-23 12:41:56
                Time zone: UTC (UTC, +0000)
System clock synchronized: no
              NTP service: inactive
          RTC in local TZ: no

# タイムゾーンの変更
# UTC → JST
vagrant@debian10:/$ sudo timedatectl set-timezone Asia/Tokyo

# タイムゾーンの変更確認
vagrant@debian10:/$ date
Mon 23 Nov 2020 09:43:27 PM JST

vagrant@debian10:/$ timedatectl
               Local time: Mon 2020-11-23 21:43:30 JST
           Universal time: Mon 2020-11-23 12:43:30 UTC
                 RTC time: Mon 2020-11-23 12:43:30
                Time zone: Asia/Tokyo (JST, +0900)
System clock synchronized: no
              NTP service: inactive
          RTC in local TZ: no

# パッケージ更新チェック
vagrant@debian10:/$ sudo apt update
Hit:1 http://deb.debian.org/debian buster InRelease
Get:2 http://deb.debian.org/debian buster-updates InRelease [51.9 kB]
...
7 packages can be upgraded. Run 'apt list --upgradable' to see them.

# パッケージ更新
vagrant@debian10:/$ sudo apt upgrade
...
...

# ゲストOSからログアウト
vagrant@debian10:~$ exit
logout
Connection to 127.0.0.1 closed.

■ [おまけ] ゲストOSで「ll」コマンドが利用できる様に設定する

# ゲストOSで作業
vagrant@debian10:~$ cd ~

# .bashrcの下記コメントを外す
vagrant@debian10:~$ vi .bashrc
# some more ls aliases
#alias ll='ls -l'
#alias la='ls -A'
#alias l='ls -CF'

# ↓↓↓へ変更
alias ll='ls -la'  # お好みで。自分はaオプションを追加
alias la='ls -A'
alias l='ls -CF'

# 変更の反映
vagrant@debian10:~$ source .bashrc
sfuksfuk

3. ゲストOS、サービス・ポートの状況確認

■ 起動サービスの確認

nginx、php-fpm、mysqldなし!

vagrant@debian10:~$ systemctl list-units --type=service
UNIT                                                                     LOAD   ACTIVE SUB     DESCRIPTION
apparmor.service                                                         loaded active exited  Load AppArmor profiles   
console-setup.service                                                    loaded active exited  Set console font and keym 
cron.service                                                             loaded active running Regular background progra 
dbus.service                                                             loaded active running D-Bus System Message Bus  
getty@tty1.service                                                       loaded active running Getty on tty1
haveged.service                                                          loaded active running Entropy daemon using the  
ifplugd.service                                                          loaded active running LSB: Brings up/down netwo 
ifup@eth0.service                                                        loaded active exited  ifup for eth0
ifupdown-pre.service                                                     loaded active exited  Helper to synchronize boo 
keyboard-setup.service                                                   loaded active exited  Set the console keyboard  
kmod-static-nodes.service                                                loaded active exited  Create list of required s 
memcached.service                                                        loaded active running memcached daemon
networking.service                                                       loaded active exited  Raise network interfaces  
postfix.service                                                          loaded active exited  Postfix Mail Transport Ag 
postfix@-.service                                                        loaded active running Postfix Mail Transport Ag 
resolvconf.service                                                       loaded active exited  Nameserver information ma 
rsyslog.service                                                          loaded active running System Logging Service    
ssh.service                                                              loaded active running OpenBSD Secure Shell serv 
sysstat.service                                                          loaded active exited  Resets System Activity Da 
systemd-fsck@dev-disk-by\x2duuid-44053f95\x2de9c8\x2d4ad2\x2db17a\x2de97bc71c8d1a.service loaded active exited  File Systsystemd-journal-flush.service                                            loaded active exited  Flush Journal to Persiste 
systemd-journald.service                                                 loaded active running Journal Service
systemd-logind.service                                                   loaded active running Login Service
systemd-modules-load.service                                             loaded active exited  Load Kernel Modules       
systemd-random-seed.service                                              loaded active exited  Load/Save Random Seed     
systemd-remount-fs.service                                               loaded active exited  Remount Root and Kernel F 
systemd-sysctl.service                                                   loaded active exited  Apply Kernel Variables    
systemd-sysusers.service                                                 loaded active exited  Create System Users       
systemd-tmpfiles-setup-dev.service                                       loaded active exited  Create Static Device Node 
systemd-tmpfiles-setup.service                                           loaded active exited  Create Volatile Files and 
systemd-udev-trigger.service                                             loaded active exited  udev Coldplug all Devices 
systemd-udevd.service                                                    loaded active running udev Kernel Device Manage 
systemd-update-utmp.service                                              loaded active exited  Update UTMP about System  
systemd-user-sessions.service                                            loaded active exited  Permit User Sessions      
user-runtime-dir@1000.service                                            loaded active exited  User Runtime Directory /r 
user@1000.service                                                        loaded active running User Manager for UID 1000 
vboxadd-service.service                                                  loaded active running vboxadd-service.service   
vboxadd.service                                                          loaded active exited  vboxadd.service

LOAD   = Reflects whether the unit definition was properly loaded.
ACTIVE = The high-level unit activation state, i.e. generalization of SUB.
SUB    = The low-level unit activation state, values depend on unit type.

38 loaded units listed. Pass --all to see loaded but inactive units, too.
To show all installed unit files use 'systemctl list-unit-files'.

■ 全サービスの確認

nginx、php-fpm、mysqldなし!

vagrant@debian10:~$ systemctl list-unit-files --type=service
UNIT FILE                              STATE
apparmor.service                       enabled        
apt-daily-upgrade.service              static
apt-daily.service                      static
...
...
割愛!

■ ポート確認

80、3306なし!

vagrant@debian10:~$ sudo netstat -atn
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State      
tcp        0      0 127.0.0.1:11211         0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:25              0.0.0.0:*               LISTEN
tcp        0      0 10.0.2.15:22            10.0.2.2:52230          ESTABLISHED
tcp6       0      0 :::22                   :::*                    LISTEN
tcp6       0      0 :::25                   :::*                    LISTEN

次から各種サービスのインストールを実施します。

sfuksfuk

4. Nginx インストール

■ [ゲストOS] nginxインストールと確認

# ゲストOSにsshでログインする
$ vagrant ssh
Last login: Tue Nov 24 22:32:24 2020 from 10.0.2.2

# nginx インストール
vagrant@debian10:~$ sudo apt install nginx
Reading package lists... Done
Building dependency tree
Reading state information... Done
...
...

# version 確認
vagrant@debian10:~$ sudo nginx -v
nginx version: nginx/1.14.2

# service 状況確認
# 起動中, vendor preset: enabled
vagrant@debian10:~$ sudo systemctl status nginx
● nginx.service - A high performance web server and a reverse proxy server
   Loaded: loaded (/lib/systemd/system/nginx.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2020-11-24 22:39:00 JST; 1min 19s ago
     Docs: man:nginx(8)
 Main PID: 2919 (nginx)
    Tasks: 2 (limit: 1150)
   Memory: 5.6M
   CGroup: /system.slice/nginx.service
           ├─2919 nginx: master process /usr/sbin/nginx -g daemon on; master_process on;
           └─2920 nginx: worker process

Nov 24 22:39:00 debian10.localdomain systemd[1]: Starting A high performance web server and a reverse proxy server...
Nov 24 22:39:00 debian10.localdomain systemd[1]: nginx.service: Failed to parse PID from file /run/nginx.pid: Invalid argumen
Nov 24 22:39:00 debian10.localdomain systemd[1]: Started A high performance web server and a reverse proxy server.

■ [ホストOS] ブラウザで確認

ゲストOSへ接続 👍

sfuksfuk

5. PHP インストール

■ [ゲストOS] PHPインストールと確認

# ゲストOSにsshでログインする
$ vagrant ssh
Last login: Tue Nov 24 22:35:15 2020 from 10.0.2.2

# パッケージマネージャhttps経由アクセス可とする
# [参考] https://packages.debian.org/ja/jessie/apt-transport-https
vagrant@debian10:~$ sudo apt -y install apt-transport-https ca-certificates
Reading package lists... Done
Building dependency tree       
Reading state information... Done
ca-certificates is already the newest version (20200601~deb10u1).
...
...

# GPGキー追加
vagrant@debian10:~$ sudo wget -O /etc/apt/trusted.gpg.d/php.gpg https://packages.sury.org/php/apt.gpg
--2020-11-24 22:54:26--  https://packages.sury.org/php/apt.gpg
...
...

# キー確認
vagrant@debian10:~$ ll /etc/apt/trusted.gpg.d/ | grep php
-rw-r--r-- 1 root root 1769 Mar 18  2019 php.gpg

# lsb_release インストール
# [参考] https://packages.debian.org/ja/jessie/lsb-release
vagrant@debian10:~$ sudo apt install lsb-release
Reading package lists... Done 
Building dependency tree       
Reading state information... Done
lsb-release is already the newest version (10.2019051400).
0 upgraded, 0 newly installed, 0 to remove and 0 not upgraded.

# リポジトリ追加
vagrant@debian10:~$ echo "deb https://packages.sury.org/php/ $(lsb_release -sc) main" | sudo tee /etc/apt/sources.list.d/php.list
deb https://packages.sury.org/php/ buster main

# パッケージリスト最新化
vagrant@debian10:~$ sudo apt update
Hit:1 http://security.debian.org/debian-security buster/updates InRelease
Hit:2 http://deb.debian.org/debian buster InRelease

# PHP7.4関連パッケージ確認
vagrant@debian10:~$ sudo apt search php7.4
Sorting... Done
Full Text Search... Done
...
...

# php, php-fpm インストール
vagrant@debian10:~$ sudo apt install php7.4 php7.4-fpm
Reading package lists... Done
...
...

# version 確認
vagrant@debian10:~$ php -v
PHP 7.4.12 (cli) (built: Nov  3 2020 14:31:48) ( NTS )
Copyright (c) The PHP Group
Zend Engine v3.4.0, Copyright (c) Zend Technologies
    with Zend OPcache v7.4.12, Copyright (c), by Zend Technologies

# PHP 拡張機能確認
# [参考] https://make.wordpress.org/hosting/handbook/handbook/server-environment/#php-extensions
# 上記を参考に不足機能を洗い出す
vagrant@debian10:~$ php -m
[PHP Modules]
calendar
Core
ctype
...
...

# PHP 拡張機能インストール(WordPress不足分)
vagrant@debian10:~$ sudo apt install \
> php7.4-curl \
> php7.4-mbstring \
> php7.4-mysql \
> php7.4-xml \
> php7.4-zip \
> php-imagick \
> php7.4-xdebug
Reading package lists... Done
Building dependency tree       
...
...

# PHP ↑追加分、拡張機能確認
vagrant@debian10:~$ php -m
[PHP Modules]
calendar
Core
ctype
curl
,,,
,,,

# php-fpm 起動確認
# 起動中, vendor preset: enabled
vagrant@debian10:~$ systemctl status php7.4-fpm
● php7.4-fpm.service - The PHP 7.4 FastCGI Process Manager
   Loaded: loaded (/lib/systemd/system/php7.4-fpm.service; enabled; vendor preset: enabled)
   Active: active (running) since Tue 2020-11-24 23:16:45 JST; 2min 47s ago
     Docs: man:php-fpm7.4(8)
  Process: 13711 ExecStartPost=/usr/lib/php/php-fpm-socket-helper install /run/php/php-fpm.sock /etc/php/7.4/fpm/pool.d/w Main PID: 13708 (php-fpm7.4)
   Status: "Processes active: 0, idle: 2, Requests: 0, slow: 0, Traffic: 0req/sec"
    Tasks: 3 (limit: 1150)
   Memory: 17.5M
   CGroup: /system.slice/php7.4-fpm.service
           ├─13708 php-fpm: master process (/etc/php/7.4/fpm/php-fpm.conf)
           ├─13709 php-fpm: pool www
           └─13710 php-fpm: pool www

# www.conf 確認
vagrant@debian10:~$ sudo cat /etc/php/7.4/fpm/pool.d/www.conf
# nginx連携用設定用に以下の設定を確認しておく
listen = /run/php/php7.4-fpm.sock
sfuksfuk

6. Composer インストール

■ [ゲストOS] Composerインストールと確認

# ゲストOSにsshでログインする
$ vagrant ssh
Last login: Tue Nov 24 22:51:37 2020 from 10.0.2.2
vagrant@debian10:~$ 

# ホームdirへ移動
vagrant@debian10:~$ cd ~

# Composerダウンロード
# [参考] https://getcomposer.org/download/
vagrant@debian10:~$ php -r "copy('https://getcomposer.org/installer', 'composer-setup.php');"

# /usr/local/binにインストール
vagrant@debian10:~$ sudo php composer-setup.php --install-dir=/usr/local/bin --filename=composer;
All settings correct for using Composer
Downloading...

Composer (version 2.0.7) successfully installed to: /usr/local/bin/composer
Use it: php /usr/local/bin/composer

# セットアップファイル削除
vagrant@debian10:~$ php -r "unlink('composer-setup.php');"

# version 確認
vagrant@debian10:~$ composer -v
   ______
  / ____/___  ____ ___  ____  ____  ________  _____
 / /   / __ \/ __ `__ \/ __ \/ __ \/ ___/ _ \/ ___/
/ /___/ /_/ / / / / / / /_/ / /_/ (__  )  __/ /
\____/\____/_/ /_/ /_/ .___/\____/____/\___/_/
                    /_/
Composer version 2.0.7 2020-11-13 17:31:06
...
...

sfuksfuk

7. Nginxとphp-fpmの連携

下記(通常のWordPress のルール)を参考に設定します
https://ja.wordpress.org/support/article/nginx/

■ [ゲストOS] wordpess用config 作成

# conf作成  ※設定内容は下記
sudo vi /etc/nginx/conf.d/wordpress.conf

# 構文チェック
vagrant@debian10:~$ sudo nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful

# 動作確認用ファイル作成
vagrant@debian10:~$ echo '<?php phpinfo() ?>' > /var/www/wordpress/index.php

# nginx 再起動
sudo systemctl restart nginx

[wordpress.conf 設定内容]
※調整するかも

# PHPへのバックエンド接続を抽象化したアップストリーム
upstream php-fpm {
        ## /etc/php/7.4/fpm/pool.d/www.conf と合わせる
        server unix:/run/php/php7.4-fpm.sock;
}

server {
        ## サーバーの名前はここに記述します。
        server_name 192.168.100.10;
        ## ルートディレクトリの指定
        root /var/www/wordpress;
        ## これは http ブロックに含まれているはずで、もし含まれていればここでは必要ありません。
        index index.php;

        location = /favicon.ico {
                log_not_found off;
                access_log off;
        }

        location = /robots.txt {
                allow all;
                log_not_found off;
                access_log off;
        }

        location / {
                # 静的なコンテンツのために PHP を実行しないため、これはこれでかっこいいです。
                # デフォルトではないパーマリンクがクエリ文字列を使っても壊れないように、"?$args "の部分をインクルードしています。
                try_files $uri $uri/ /index.php?$args;
        }

        location ~ \.php$ {
                # 注意: php.iniに "cgi.fix_pathinfo = 0; "を設定してください。
                include snippets/fastcgi-php.conf;
                fastcgi_intercept_errors on;
                fastcgi_pass php-fpm;
        }

        location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ {
                expires max;
                log_not_found off;
        }
}

■ [ホストOS] ブラウザで確認

ゲストOSへ接続 👍

sfuksfuk

8. MariaDB インストール

■ [ゲストOS] MariaDBインストールと確認

[参考] phpMyAdmin を使用したデータベースの作成(キャラクタセット)
https://ja.wordpress.org/support/article/creating-database-for-wordpress/

# ゲストOSにsshでログインする
$ vagrant ssh
Last login: Thu Nov 26 21:23:24 2020 from 10.0.2.2

# MariaDB インストール
vagrant@debian10:~$ sudo apt install mariadb-server
Reading package lists... Done
Building dependency tree       
Reading state information... Done
The following additional packages will be installed:

# MariaDB 起動確認
# 起動中, vendor preset: enabled
vagrant@debian10:~$ sudo systemctl status mariadb
● mariadb.service - MariaDB 10.3.25 database server
   Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2020-11-26 21:28:15 JST; 1min 11s ago
     Docs: man:mysqld(8)
           https://mariadb.com/kb/en/library/systemd/
 Main PID: 3036 (mysqld)
   Status: "Taking your SQL requests now..."
    Tasks: 31 (limit: 1150)
   Memory: 72.4M
   CGroup: /system.slice/mariadb.service
           └─3036 /usr/sbin/mysqld

Nov 26 21:28:16 debian10.localdomain /etc/mysql/debian-start[3074]: Phase 6/7: Checking and upgrading tables
Nov 26 21:28:16 debian10.localdomain /etc/mysql/debian-start[3074]: Running 'mysqlcheck' with connection arguments: --socket='/var/run/mysqld/mysqld.sock' --h
Nov 26 21:28:16 debian10.localdomain /etc/mysql/debian-start[3074]: # Connecting to localhost...
Nov 26 21:28:16 debian10.localdomain /etc/mysql/debian-start[3074]: # Disconnecting from localhost...
Nov 26 21:28:16 debian10.localdomain /etc/mysql/debian-start[3074]: Processing databases
Nov 26 21:28:16 debian10.localdomain /etc/mysql/debian-start[3074]: information_schema
Nov 26 21:28:16 debian10.localdomain /etc/mysql/debian-start[3074]: performance_schema
Nov 26 21:28:16 debian10.localdomain /etc/mysql/debian-start[3074]: Phase 7/7: Running 'FLUSH PRIVILEGES'
Nov 26 21:28:16 debian10.localdomain /etc/mysql/debian-start[3074]: OK
Nov 26 21:28:16 debian10.localdomain /etc/mysql/debian-start[3160]: Triggering myisam-recover for all MyISAM tables and aria-recover for all Aria tables

# MariaDB 初期設定
# root ユーザーのパスワード等を設定する
vagrant@debian10:/$ sudo mysql_secure_installation
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
      SERVERS IN PRODUCTION USE!  PLEASE READ EACH STEP CAREFULLY!

In order to log into MariaDB to secure it, we'll need the current
password for the root user.  If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.

Enter current password for root (enter for none): 
OK, successfully used password, moving on...

Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorisation.

Set root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading privilege tables..
 ... Success!


By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them.  This is intended only for testing, and to make the installation
go a bit smoother.  You should remove them before moving into a
production environment.

Remove anonymous users? [Y/n] y
 ... Success!

Normally, root should only be allowed to connect from 'localhost'.  This
ensures that someone cannot guess at the root password from the network.

Disallow root login remotely? [Y/n] n
 ... skipping.

By default, MariaDB comes with a database named 'test' that anyone can
access.  This is also intended only for testing, and should be removed
before moving into a production environment.

Remove test database and access to it? [Y/n] y
 - Dropping test database...
 ... Success!
 - Removing privileges on test database...
 ... Success!

Reloading the privilege tables will ensure that all changes made so far
will take effect immediately.

Reload privilege tables now? [Y/n] y
 ... Success!

Cleaning up...

All done!  If you've completed all of the above steps, your MariaDB
installation should now be secure.

Thanks for using MariaDB!

# 接続確認
vagrant@debian10:~$ sudo mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 37
Server version: 10.3.25-MariaDB-0+deb10u1 Debian 10

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

# 設定ファイル確認
vagrant@debian10:~$ ls -laF /etc/mysql/mariadb.conf.d/
total 24
drwxr-xr-x 2 root root 4096 Nov 26 21:28 ./
drwxr-xr-x 4 root root 4096 Nov 26 21:28 ../
-rw-r--r-- 1 root root  733 Oct 13 02:46 50-client.cnf
-rw-r--r-- 1 root root  336 Oct 13 02:46 50-mysql-clients.cnf
-rw-r--r-- 1 root root 1032 Oct 13 02:46 50-mysqld_safe.cnf
-rw-r--r-- 1 root root 3940 Oct 13 02:46 50-server.cnf

# 外部接続を可能としておく
# キャラクタセットを確認しておく
vagrant@debian10:~$ sudo vi /etc/mysql/mariadb.conf.d/50-server.cnf
# Instead of skip-networking the default is now to listen only on
# localhost which is more compatible and is not less secure.
# bind-address            = 127.0.0.1    # ← コメントアウトする

#
# * Character sets
#
# MySQL/MariaDB default is Latin1, but in Debian we rather default to the full
# utf8 4-byte character set. See also client.cnf
#
character-set-server  = utf8mb4
collation-server      = utf8mb4_general_ci

# MariaDB 再起動
vagrant@debian10:~$ sudo systemctl restart mariadb

# MariaDB 起動確認
vagrant@debian10:~$ sudo systemctl status mariadb
● mariadb.service - MariaDB 10.3.25 database server
   Loaded: loaded (/lib/systemd/system/mariadb.service; enabled; vendor preset: enabled)
   Active: active (running) since Thu 2020-11-26 21:55:01 JST; 15s ago
     Docs: man:mysqld(8)
           https://mariadb.com/kb/en/library/systemd/
  Process: 1350 ExecStartPre=/usr/bin/install -m 755 -o mysql -g root -d /var/run/mysqld (code=exited, status=0/SUCCESS)
  Process: 1351 ExecStartPre=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
  Process: 1353 ExecStartPre=/bin/sh -c [ ! -e /usr/bin/galera_recovery ] && VAR= ||   VAR=`cd /usr/bin/..; /usr/bin/galera_recovery`; [ $? -eq 0 ]   && systemctl set-environment _WSREP_S  Process: 1428 ExecStartPost=/bin/sh -c systemctl unset-environment _WSREP_START_POSITION (code=exited, status=0/SUCCESS)
  Process: 1430 ExecStartPost=/etc/mysql/debian-start (code=exited, status=0/SUCCESS)
 Main PID: 1397 (mysqld)
   Status: "Taking your SQL requests now..."
    Tasks: 31 (limit: 1150)
   Memory: 72.7M
   CGroup: /system.slice/mariadb.service
           └─1397 /usr/sbin/mysqld

sfuksfuk

9. WordPress データベース作成

■ [ゲストOS] MariaDBインストールと確認

[参考]
https://ja.wordpress.org/support/article/creating-database-for-wordpress/

# ゲストOSにsshでログインする
$ vagrant ssh
Last login: Thu Nov 26 21:42:21 2020 from 10.0.2.2

# MariaDBにrootでログインする
vagrant@debian10:~$ sudo mysql -u root -p
Enter password: 
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 37
Server version: 10.3.25-MariaDB-0+deb10u1 Debian 10

Copyright (c) 2000, 2018, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

# データベース作成
MariaDB [(none)]> create database wordpress;
Query OK, 1 row affected (0.000 sec)

MariaDB [(none)]> show databases;
+--------------------+   
| Database           |   
+--------------------+   
| information_schema |   
| mysql              |   
| performance_schema |   
| wordpress          |   
+--------------------+   
4 rows in set (0.001 sec)

# wordpress ユーザー作成
MariaDB [(none)]> create user 'wpuser'@'localhost' identified by '<passwordを設定する>';
Query OK, 0 rows affected (0.000 sec)

# ローカル接続許可
MariaDB [(none)]> grant all privileges on wordpress.* to 'wpuser'@'localhost';
Query OK, 0 rows affected (0.000 sec)

# 外部接続許可
MariaDB [(none)]> grant all privileges on wordpress.* to 'wpuser'@'%' identified by '<passwordを設定する>' with grant option;
Query OK, 0 rows affected (0.000 sec)

MariaDB [(none)]> select user, host from mysql.user;
+--------+-----------+
| user   | host      |
+--------+-----------+
| wpuser | %         |
| root   | localhost |
| wpuser | localhost |
+--------+-----------+
3 rows in set (0.000 sec)

MariaDB [(none)]> exit
Bye

# ポートの確認
# 3306 OK!
vagrant@debian10:~$ sudo netstat -atn
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.1:11211         0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN
tcp        0      0 0.0.0.0:25              0.0.0.0:*               LISTEN
tcp        0      0 10.0.2.15:22            10.0.2.2:63496          ESTABLISHED
tcp6       0      0 :::3306                 :::*                    LISTEN
tcp6       0      0 :::80                   :::*                    LISTEN
tcp6       0      0 :::22                   :::*                    LISTEN
tcp6       0      0 :::25                   :::*                    LISTEN
tcp6       0      0 192.168.100.10:3306     192.168.100.1:63825     ESTABLISHED

■ [ホストOS] DB接続ツールで確認

MariaDBへ接続 👍

sfuksfuk

10. WordPress インストール

■ [ゲストOS] MariaDBインストールと確認

# ゲストOSにsshでログインする
$ vagrant ssh
Last login: Thu Nov 26 21:58:48 2020 from 10.0.2.2

# 作業用フォルダへ移動
vagrant@debian10:~$ cd /vagrant/

# wordpress ダウンロード
vagrant@debian10:/vagrant$ curl -O https://ja.wordpress.org/wordpress-latest-ja.tar.gz
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed  
100 13.0M  100 13.0M    0     0  2159k      0  0:00:06  0:00:06 --:--:-- 2084k

# wordpress 解凍
vagrant@debian10:/vagrant$ tar xvf wordpress-latest-ja.tar.gz
...
...

# 確認
vagrant@debian10:/vagrant$ ll
total 13372
drwxrwxrwx  1 vagrant vagrant        0 Nov 26 22:24 .
drwxr-xr-x 19 root    root        4096 Nov 23 21:12 ..
drwxrwxrwx  1 vagrant vagrant     4096 Nov  1 09:00 wordpress
-rwxrwxrwx  1 vagrant vagrant 13682436 Nov 26 22:23 wordpress-latest-ja.tar.gz

# 解凍ファイルをwordpress公開フォルダへ移動
vagrant@debian10:/vagrant$ mv -f ./wordpress/* /var/www/wordpress/

# 残骸削除
vagrant@debian10:/vagrant$ rm -r wordpress

# 公開フォルダ、ファイル確認
vagrant@debian10:/vagrant$ ls -laF /var/www/wordpress/
total 313
drwxrwxrwx 1 vagrant vagrant  4096 Nov 26 22:28 ./
drwxr-xr-x 4 root    root     4096 Nov 24 22:38 ../
-rwxrwxrwx 1 vagrant vagrant   405 Feb  6  2020 index.php*
-rwxrwxrwx 1 vagrant vagrant 19915 Feb 12  2020 license.txt*
-rwxrwxrwx 1 vagrant vagrant 10089 Nov  1 09:00 readme.html*
-rwxrwxrwx 1 vagrant vagrant  7101 Jul 29 02:20 wp-activate.php*
drwxrwxrwx 1 vagrant vagrant 40960 Nov  1 09:00 wp-admin/
-rwxrwxrwx 1 vagrant vagrant   351 Feb  6  2020 wp-blog-header.php*
-rwxrwxrwx 1 vagrant vagrant  2332 Jul 23 09:52 wp-comments-post.php*
-rwxrwxrwx 1 vagrant vagrant  3931 Nov  1 09:00 wp-config-sample.php*
drwxrwxrwx 1 vagrant vagrant     0 Nov  1 09:00 wp-content/
-rwxrwxrwx 1 vagrant vagrant  3940 Feb  6  2020 wp-cron.php*
drwxrwxrwx 1 vagrant vagrant 81920 Nov  1 09:00 wp-includes/
-rwxrwxrwx 1 vagrant vagrant  2496 Feb  6  2020 wp-links-opml.php*
-rwxrwxrwx 1 vagrant vagrant  3300 Feb  6  2020 wp-load.php*
-rwxrwxrwx 1 vagrant vagrant 48761 Jul  7 12:59 wp-login.php*
-rwxrwxrwx 1 vagrant vagrant  8509 Apr 14  2020 wp-mail.php*
-rwxrwxrwx 1 vagrant vagrant 20181 Jul  6 19:50 wp-settings.php*
-rwxrwxrwx 1 vagrant vagrant 31159 Jul 24 06:11 wp-signup.php*
-rwxrwxrwx 1 vagrant vagrant  4755 Feb  6  2020 wp-trackback.php*
-rwxrwxrwx 1 vagrant vagrant  3236 Jun  9 04:55 xmlrpc.php*

■ [ホストOS] ブラウザで確認
ゲストOSへ接続 👍

sfuksfuk

11. Vagrant box 作成

WordPressの初期設定でDBにテーブルが作成されてしまうので
初期設定前に作成しておく

■ [ホストOS] Vagrant の作成

# 仮想マシン停止
$ vagrant halt
==> default: Attempting graceful shutdown of VM...

# カスタマイズした仮想マシンをベースにボックスを作成
$ vagrant package default --output debian10-dev-wp.box
==> default: Clearing any previously set forwarded ports...
==> default: Exporting VM...
==> default: Compressing package to: C:/debian10/debian10-dev-wp.box

# 作成したボックスを追加
$ vagrant box add debian10-dev-wp debian10-dev-wp.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'debian10-dev-wp' (v0) for provider:
    box: Unpacking necessary files from: file://C:/debian10/debian10-dev-wp.box
    box:
==> box: Successfully added box 'debian10-dev-wp' (v0) for 'virtualbox'!

# 確認
$ vagrant box list
debian10-dev-wp    (virtualbox, 0)
generic/debian10   (virtualbox, 3.1.6)

sfuksfuk

12. 編集用設定ファイル準備とVagrantfileの拡張

■ [ゲストOS] 設定ファイルのコピー

ゲストOSの各種設定ファイルをホストOSのマウント用フォルダへコピーする
対象は下記
・PHP:php.ini
・nginx:wordpress.conf
・MariaDB:50-server.cnf

# ゲストOSにsshでログインする
$ vagrant ssh
Last login: Thu Nov 26 22:21:09 2020 from 10.0.2.2

# PHP
vagrant@debian10:~$ mkdir -p /vagrant/php/
vagrant@debian10:~$ cp /etc/php/7.4/fpm/php.ini /vagrant/php/php.ini
vagrant@debian10:~$ cp /vagrant/php/php.ini /vagrant/php/php.ini.org

# nginx
vagrant@debian10:~$ mkdir -p /vagrant/nginx/conf.d/
vagrant@debian10:~$ cp /etc/nginx/conf.d/wordpress.conf /vagrant/nginx/conf.d/wordpress.conf
vagrant@debian10:~$ cp /vagrant/nginx/conf.d/wordpress.conf /vagrant/nginx/conf.d/wordpress.conf.org

# MariaDB
vagrant@debian10:~$ mkdir -p /vagrant/mysql/mariadb.conf.d/
vagrant@debian10:~$ cp /etc/mysql/mariadb.conf.d/50-server.cnf /vagrant/mysql/mariadb.conf.d/50-server.cnf
vagrant@debian10:~$ cp /vagrant/mysql/mariadb.conf.d/50-server.cnf /vagrant/mysql/mariadb.conf.d/50-server.cnf.org

■ [ホストOS] Vagrantフォルダ構成

下記の構成となっている事を確認
各種設定ファイルはホストPCで必要に応じて都度編集する。
後述の設定でゲストOSへ反映可能とする

debian10-dev-wp
  ├ vagrant/
  │  ├ php/
  │  │  └ php.ini
  │  │  └ php.ini.org
  │  ├ nginx
  │  │  └ conf.d/
  │  │     └ wordpress.conf
  │  │     └ wordpress.conf.org
  │  └ mysql/
  │     └ mariadb.conf.d/
  │         └ 50-server.cnf
  │         └ 50-server.cnf.org
  ├ wordpress/
  └ Vagrantfile

■ [ホストOS] Vagrantfile拡張

shellを追加し、起動時、provison時に設定ファイル上書き、service再起動
※必要がない場合は下記をコメントアウトする or always指定を外す
「config.vm.provision :shell, run: "always", inline:$config_set_script」

# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure("2") do |config|
  # Debian10
  config.vm.box = "generic/debian10"

  # network
  config.vm.network "private_network", ip: "192.168.100.10"

  # macine
  config.vm.provider "virtualbox" do |vb|
    vb.name = "debian10-dev-wp"
    vb.memory = "1024"
	vb.cpus = "1"
  end

  # sync dir
  config.vm.synced_folder "./wordpress", '/var/www/wordpress', :mount_options => ['dmode=777', 'fmode=777']
  config.vm.synced_folder "./vagrant", '/vagrant', :mount_options => ['dmode=777', 'fmode=777']

  config.vm.provision :shell, run: "always", inline:$config_set_script
end

$config_set_script = <<END
  # php setting file copy 
  cp /vagrant/php/php.ini /etc/php/7.4/fpm/php.ini

  # php-fpm restart
  systemctl restart php7.4-fpm

  # nginx setting file copy
  cp -f /vagrant/nginx/conf.d/wordpress.conf /etc/nginx/conf.d/wordpress.conf

  # web server restart
  systemctl restart nginx

  # mysql setting file copy
  cp -f /vagrant/mysql/mariadb.conf.d/50-server.cnf /etc/mysql/mariadb.conf.d/50-server.cnf

  # db server restart
  systemctl restart mysqld
END
sfuksfuk

13. WordPress 初期設定

■ [ホストOS] ブラウザで接続

画面の説明通りに設定を進める
ログイン完了 👍


sfuksfuk

とりあえず完了!
wordpress以外でもPHPなら汎用的に使える環境ができたと思います。(たぶん)

しかし、夜な夜な仕事終わって家でやってると意外と時間が掛かった。。。
ログ取りながらの作業ってメンドクサイ。

ちなみにスクラップの使い方間違ってんのかな??

まっ、いいか

このスクラップは2020/11/28にクローズされました