Windows10(64bit)にVagrant+VirtualBoxで開発環境作る3

# 概要

[その2](https://qiita.com/halnique/items/33b5fcd002c7bedc9db7)の続き

Vagrantで構築したCentOS 7上にyumリポジトリ追加したりNginx/MySQL/Redis/PHPをインストールした

今回はインストールした諸々の自動起動設定とかして、一旦イメージとしてexportする

今後拡張していった時にぶっ壊れてもここまでは戻れるセーブポイント的な意味で

# 復習

```bash
[vagrant@localhost ~]$ yum list installed | grep -i "nginx\|mysql\|redis\|php"
mysql-community-client.x86_64      5.7.22-1.el7                      @mysql57-community
mysql-community-common.x86_64      5.7.22-1.el7                      @mysql57-community
mysql-community-libs.x86_64        5.7.22-1.el7                      @mysql57-community
mysql-community-server.x86_64      5.7.22-1.el7                      @mysql57-community
mysql80-community-release.noarch   el7-1                             installed
nginx.x86_64                       1:1.12.2-2.el7                    @epel
nginx-all-modules.noarch           1:1.12.2-2.el7                    @epel
nginx-filesystem.noarch            1:1.12.2-2.el7                    @epel
nginx-mod-http-geoip.x86_64        1:1.12.2-2.el7                    @epel
nginx-mod-http-image-filter.x86_64 1:1.12.2-2.el7                    @epel
nginx-mod-http-perl.x86_64         1:1.12.2-2.el7                    @epel
nginx-mod-http-xslt-filter.x86_64  1:1.12.2-2.el7                    @epel
nginx-mod-mail.x86_64              1:1.12.2-2.el7                    @epel
nginx-mod-stream.x86_64            1:1.12.2-2.el7                    @epel
php.x86_64                         7.2.7-1.el7.remi                  @remi-php72
php-cli.x86_64                     7.2.7-1.el7.remi                  @remi-php72
php-common.x86_64                  7.2.7-1.el7.remi                  @remi-php72
php-devel.x86_64                   7.2.7-1.el7.remi                  @remi-php72
php-fpm.x86_64                     7.2.7-1.el7.remi                  @remi-php72
php-json.x86_64                    7.2.7-1.el7.remi                  @remi-php72
php-mbstring.x86_64                7.2.7-1.el7.remi                  @remi-php72
php-pdo.x86_64                     7.2.7-1.el7.remi                  @remi-php72
redis.x86_64                       4.0.10-1.el7.remi                 @remi
```

インストールしたのはこれら

※ RedisとかPHPとか若干バージョン上がっているのは、`yum update`かけたから

```bash
[vagrant@localhost ~]$ sudo yum clean all && sudo yum update -y
```

# 自動起動の設定確認

CentOS 7では`systemctl`を使う

`systemctl list-unit-files`で各serviceの自動起動の設定が確認できる

```bash
[vagrant@localhost ~]$ systemctl list-unit-files | grep -i "nginx\|mysql\|redis\|php"
mysqld.service                                enabled
mysqld@.service                               disabled
nginx.service                                 disabled
php-fpm.service                               disabled
redis-sentinel.service                        disabled
redis.service                                 disabled
```

mysqld.serviceが有効でそれ以外は無効な様子

そもそもmysqld.serviceとmysqld@.serviceの違いはなんだ…

```bash
[vagrant@localhost ~]$ systemctl status mysqld
● mysqld.service - MySQL Server
   Loaded: loaded (/usr/lib/systemd/system/mysqld.service; enabled; vendor preset: disabled)
   Active: active (running) since Mon 2018-07-09 11:25:48 UTC; 43min ago
     Docs: man:mysqld(8)
           http://dev.mysql.com/doc/refman/en/using-systemd.html
 Main PID: 1549 (mysqld)
   CGroup: /system.slice/mysqld.service
           └─1549 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid
[vagrant@localhost ~]$ systemctl status mysqld@
Failed to get properties: Unit name mysqld@.service is missing the instance name.
```

mysqldは起動しているが、mysqld@は知らないと言われてしまったので無視する

# 自動起動の有効化

自動起動有効になっていないNginx/Redis/php-fpmの設定を有効にする

有効にするときは`systemctl enable`を使う

※ 無効にするときは`systemctl disable`

こんな感じで有効化してあげる

```bash
[vagrant@localhost ~]$ sudo systemctl enable nginx redis redis-sentinel php-fpm
```

以下のようになっていればOK

```bash
[vagrant@localhost ~]$ systemctl list-unit-files | grep -i "nginx\|mysql\|redis\|php"
mysqld.service                                enabled
mysqld@.service                               disabled
nginx.service                                 enabled
php-fpm.service                               enabled
redis-sentinel.service                        enabled
redis.service                                 enabled
```

# 自動起動するか確認

OS再起動してちゃんと各プロセスが自動起動するか確認する

まず停止しておく

```bash
[vagrant@localhost ~]$ sudo systemctl stop nginx mysqld redis redis-sentinel php-fpm | grep Active
[vagrant@localhost ~]$ systemctl status nginx mysqld redis redis-sentinel php-fpm | grep Active
   Active: inactive (dead) since Mon 2018-07-09 13:50:58 UTC; 5s ago
   Active: inactive (dead) since Mon 2018-07-09 13:51:01 UTC; 2s ago
   Active: inactive (dead) since Mon 2018-07-09 13:50:58 UTC; 5s ago
   Active: inactive (dead) since Mon 2018-07-09 13:50:58 UTC; 5s ago
   Active: inactive (dead) since Mon 2018-07-09 13:50:58 UTC; 5s ago
[vagrant@localhost ~]$ ps aux | grep -i "nginx\|mysql\|redis\|php"
vagrant  14921  0.0  0.1  12520   976 pts/0    S+   12:24   0:00 grep --color=auto -i nginx\ mysql\|redis\|php
```

止まっている

Vagrantなので、`logout`してから`vagrant reload`で再起動

```bash
[vagrant@localhost ~]$ logout
Connection to 127.0.0.1 closed.
$ vagrant reload
$ vagrant ssh
```

sshしたらそのまま確認

```bash
[vagrant@localhost ~]$ systemctl status nginx mysqld redis redis-sentinel php-fpm | grep Active
   Active: active (running) since Mon 2018-07-09 12:27:05 UTC; 16min ago
   Active: active (running) since Mon 2018-07-09 12:27:06 UTC; 16min ago
   Active: active (running) since Mon 2018-07-09 12:27:03 UTC; 16min ago
   Active: active (running) since Mon 2018-07-09 12:27:03 UTC; 16min ago
   Active: active (running) since Mon 2018-07-09 12:27:04 UTC; 16min ago
[vagrant@localhost ~]$ ps aux | grep -i "nginx\|mysql\|redis\|php"
redis      782  0.3  0.4  51096  2428 ?        Rsl  12:27   0:03 /usr/bin/redis-sentinel *:26379 [sentinel]
redis      786  0.2  0.4  51096  2480 ?        Ssl  12:27   0:02 /usr/bin/redis-server 127.0.0.1:6379
root       788  0.0  1.8 171572  9456 ?        Ss   12:27   0:00 php-fpm: master process (/etc/php-fpm.conf)
mysql      826  0.1 33.2 1119456 165856 ?      Sl   12:27   0:01 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid
apache     827  0.0  0.8 171572  4276 ?        S    12:27   0:00 php-fpm: pool www
apache     828  0.0  0.8 171572  4276 ?        S    12:27   0:00 php-fpm: pool www
apache     829  0.0  0.8 171572  4276 ?        S    12:27   0:00 php-fpm: pool www
apache     830  0.0  0.8 171572  4276 ?        S    12:27   0:00 php-fpm: pool www
apache     831  0.0  0.8 171572  4280 ?        S    12:27   0:00 php-fpm: pool www
root       836  0.0  0.4 120808  2088 ?        Ss   12:27   0:00 nginx: master process /usr/sbin/nginx
nginx      837  0.0  0.6 121272  3116 ?        S    12:27   0:00 nginx: worker process
vagrant   1547  0.0  0.1  12520   972 pts/0    R+   12:43   0:00 grep --color=auto -i nginx\ mysql\|redis\|php
```

無事に諸々動いている模様

# イメージとしてExport

今の状態をVagrantのboxイメージとしてファイルにexportする

※ ファイルとかいらないものがあったら消しておくと良いかも

ログアウトする

```bash
[vagrant@localhost ~]$ logout
Connection to 127.0.0.1 closed.
```

`vagrant package`コマンドでexportする

```bash
$ vagrant package --help
Usage: vagrant package [options] [name|id]

Options:

        --base NAME                  Name of a VM in VirtualBox to package as a base box (VirtualBox Only)
        --output NAME                Name of the file to output
        --include FILE,FILE..        Comma separated additional files to package with the box
        --vagrantfile FILE           Vagrantfile to package with the box
    -h, --help                       Print this help
```

```bash
$ vagrant package --output sample.box
==> default: Attempting graceful shutdown of VM...
==> default: Clearing any previously set forwarded ports...
==> default: Exporting VM...
==> default: Compressing package to: hogehoge/sample.box
$ ll
total 1179556
-rw-r--r-- 1 hoge 197609 1207860212 7月   9 22:00 sample.box
-rw-r--r-- 1 hoge 197609       3085 6月   4 19:39 Vagrantfile
```

こんな感じで出来上がる

# Exportしたイメージを使う

流れとしては↓

1. 作成したイメージファイルを`vagrant box add`する
2. `vagrant init`でaddしたイメージを指定する
3. `vagrant up`する

現在ローカルマシンに登録されているイメージを確認

```bash
$ vagrant box list
centos/7 (virtualbox, 1804.02)
```

[その1](https://qiita.com/halnique/items/0cba26b4250e0b81d790)でCentOS 7のイメージを使ったから、そいつが登録されている

先ほど作成した`sample.box`を登録してやる

```bash
$ vagrant box add --help
Usage: vagrant box add [options] <name, url, or path>

Options:

    -c, --clean                      Clean any temporary download files
    -f, --force                      Overwrite an existing box if it exists
        --insecure                   Do not validate SSL certificates
        --cacert FILE                CA certificate for SSL download
        --capath DIR                 CA certificate directory for SSL download
        --cert FILE                  A client SSL cert, if needed
        --location-trusted           Trust 'Location' header from HTTP redirects and use the same credentials for subsequent urls as for the initial one
        --provider PROVIDER          Provider the box should satisfy
        --box-version VERSION        Constrain version of the added box

The box descriptor can be the name of a box on HashiCorp's Vagrant Cloud,
or a URL, or a local .box file, or a local .json file containing
the catalog metadata.

The options below only apply if you're adding a box file directly,
and not using a Vagrant server or a box structured like 'user/box':

        --checksum CHECKSUM          Checksum for the box
        --checksum-type TYPE         Checksum type (md5, sha1, sha256)
        --name BOX                   Name of the box
    -h, --help                       Print this help
```

```bash
$ vagrant box add --name sample sample.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'sample' (v0) for provider:
    box: Unpacking necessary files from: file://hogehoge/sample.box
    box:
==> box: Successfully added box 'sample' (v0) for 'virtualbox'!
$ vagrant box list
centos/7 (virtualbox, 1804.02)
sample   (virtualbox, 0)
```

これで`sample`という名前で自作イメージが使えるようになったので、このイメージからVMを起動してみる

今まで使っていたCentOS 7ベースのものとは別で立ち上げる

```bash
$ vagrant status
Current machine states:

default                   poweroff (virtualbox)

The VM is powered off. To restart the VM, simply run `vagrant up`
```

`vagrant package`した時に停止されたままなのでこのまま放っておき、別ディレクトリで作業する

※ これはこのまま`vagrant up`すればまた動くので、以降うまくいかなかったらここからやり直せばOK

```bash
$ cd {適当なディレクトリ}
$ vagrant init sample
A `Vagrantfile` has been placed in this directory. You are now
ready to `vagrant up` your first virtual environment! Please read
the comments in the Vagrantfile as well as documentation on
`vagrantup.com` for more information on using Vagrant.
```

いざ

```bash
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'sample'...
==> default: Matching MAC address for NAT networking...
...
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 uid=1000,gid=1000 vagrant /vagrant

The error output from the command was:

mount: unknown filesystem type 'vboxsf'
```

失敗した…そんなに変なもの入れたりしてないけどなー

ホストとゲストでバージョン不一致があると起こる？という情報があった
https://qiita.com/reflet/items/98fd548a6ef341f685bb

そういえば前回から今回の間にVagrantをアップデートしたことを思い出した←

記事を参考にしてpluginを入れてみる

```bash
$ vagrant plugin list
No plugins installed.
$ vagrant plugin install vagrant-vbguest
Installing the 'vagrant-vbguest' plugin. This can take a few minutes...
Installed the plugin 'vagrant-vbguest (0.15.2)'!
$ vagrant plugin list
vagrant-vbguest (0.15.2)
```

リトライ

```bash
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'sample'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: vagrant_default_1533124552268_95517
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
==> default: Machine booted and ready!
[default] No installation found.
Loaded plugins: fastestmirror
Determining fastest mirrors
 * base: ftp.iij.ad.jp
 * epel: ftp.iij.ad.jp
 * extras: ftp.iij.ad.jp
 * remi: ftp.riken.jp
 * remi-php72: ftp.riken.jp
 * remi-safe: ftp.riken.jp
 * updates: ftp.iij.ad.jp
Package gcc-4.8.5-28.el7_5.1.x86_64 already installed and latest version
Package binutils-2.27-28.base.el7_5.1.x86_64 already installed and latest version
Package 1:make-3.82-23.el7.x86_64 already installed and latest version
Package 4:perl-5.16.3-292.el7.x86_64 already installed and latest version
Package bzip2-1.0.6-13.el7.x86_64 already installed and latest version
Resolving Dependencies
--> Running transaction check
---> Package kernel-devel.x86_64 0:3.10.0-862.6.3.el7 will be installed
---> Package kernel-devel.x86_64 0:3.10.0-862.9.1.el7 will be installed
--> Finished Dependency Resolution

Dependencies Resolved

================================================================================
 Package            Arch         Version                    Repository     Size
================================================================================
Installing:
 kernel-devel       x86_64       3.10.0-862.6.3.el7         updates        16 M
 kernel-devel       x86_64       3.10.0-862.9.1.el7         updates        16 M

Transaction Summary
================================================================================
Install  2 Packages

Total download size: 31 M
Installed size: 73 M
Downloading packages:
--------------------------------------------------------------------------------
Total                                              6.5 MB/s |  31 MB  00:04  
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Installing : kernel-devel-3.10.0-862.6.3.el7.x86_64                       1/2
  Installing : kernel-devel-3.10.0-862.9.1.el7.x86_64                       2/2
  Verifying  : kernel-devel-3.10.0-862.9.1.el7.x86_64                       1/2
  Verifying  : kernel-devel-3.10.0-862.6.3.el7.x86_64                       2/2

Installed:
  kernel-devel.x86_64 0:3.10.0-862.6.3.el7                                   
  kernel-devel.x86_64 0:3.10.0-862.9.1.el7                                   

Complete!
Copy iso file C:\Program Files\Oracle\VirtualBox\VBoxGuestAdditions.iso into the box /tmp/VBoxGuestAdditions.iso
Mounting Virtualbox Guest Additions ISO to: /mnt
mount: /dev/loop0 is write-protected, mounting read-only
Installing Virtualbox Guest Additions 5.2.12 - guest version is unknown
Verifying archive integrity... All good.
Uncompressing VirtualBox 5.2.12 Guest Additions for Linux........
VirtualBox Guest Additions installer
Copying additional installer modules ...
Installing additional modules ...
VirtualBox Guest Additions: Building the VirtualBox Guest Additions kernel modules.
VirtualBox Guest Additions: Starting.
Redirecting to /bin/systemctl start vboxadd.service
Redirecting to /bin/systemctl start vboxadd-service.service
Unmounting Virtualbox Guest Additions ISO from: /mnt
==> default: Checking for guest additions in VM...
==> default: Mounting shared folders...
    default: /vagrant => /hoge
```

おお、うまくいった

```bash
$ vagrant ssh
Last login: Mon Jul  9 12:40:32 2018 from 10.0.2.2
[vagrant@localhost ~]$ systemctl status nginx mysqld redis redis-sentinel php-fpm | grep Active
   Active: active (running) since Wed 2018-08-01 11:56:14 UTC; 6min ago
   Active: active (running) since Wed 2018-08-01 11:56:15 UTC; 6min ago
   Active: active (running) since Wed 2018-08-01 11:56:13 UTC; 6min ago
   Active: active (running) since Wed 2018-08-01 11:56:13 UTC; 6min ago
   Active: active (running) since Wed 2018-08-01 11:56:14 UTC; 6min ago
[vagrant@localhost ~]$ ps aux | grep -i "nginx\|mysql\|redis\|php"
redis      786  0.2  0.3  51096  1788 ?        Ssl  11:56   0:00 /usr/bin/redis-sentinel *:26379 [sentinel]
root       787  0.0  0.7 171572  3788 ?        Ss   11:56   0:00 php-fpm: master process (/etc/php-fpm.conf)
redis      791  0.1  0.3  51096  1652 ?        Ssl  11:56   0:00 /usr/bin/redis-server 127.0.0.1:6379
apache     826  0.0  0.7 171572  3600 ?        S    11:56   0:00 php-fpm: pool www
apache     827  0.0  0.7 171572  3604 ?        S    11:56   0:00 php-fpm: pool www
apache     828  0.0  0.7 171572  3604 ?        S    11:56   0:00 php-fpm: pool www
apache     829  0.0  0.7 171572  3604 ?        S    11:56   0:00 php-fpm: pool www
apache     831  0.0  0.7 171572  3608 ?        S    11:56   0:00 php-fpm: pool www
mysql      832  0.2 32.1 1119456 160332 ?      Sl   11:56   0:00 /usr/sbin/mysqld --daemonize --pid-file=/var/run/mysqld/mysqld.pid
root       836  0.0  0.4 120808  2008 ?        Ss   11:56   0:00 nginx: master process /usr/sbin/nginx
nginx      837  0.0  0.5 121272  2512 ?        S    11:56   0:00 nginx: worker process
vagrant  29520  0.0  0.1  12520   972 pts/0    R+   12:02   0:00 grep --color=auto -i nginx\|mysql\|redis\|php
```

nginxとphp-fpmの設定してないし（apacheユーザーで動いてる…）中途半端感あるけど気にしない

# 最後に

Windows10(64bit)にVagrant+VirtualBoxで開発環境作るのは一旦ここまで

このあとやっていきたいことは↓

* [Laravel](http://laravel.jp/)を使ってPHPのWebアプリを作る
* [Chef](https://www.chef.io/chef/)や[Ansible](https://www.ansible.com/)を使ってInfra as Codeを進める
* [Docker](https://www.docker.com/)で環境構築する

などなど