Vagrant上のCentOSでhttpd.confをVagrant共有ディレクトリのシンボリックリンクにしているとOSブート時にhttpdが自動起動しない #vagrant #apache

これはApacheに関わらず、Vagrant共有ディレクトリにサービス起動に必要なファイルを配置している場合に発生する現象です。 解決方法を考えてみましたが、起動スクリプトを変更するという微妙な方法になりました。 どなたか良い解決方法をご存知なら教えていただきたいです。

現象

以下再現手順。

$ vagrant ssh

Apacheインストール
[vagrant@localhost ~]$ sudo yum -y install httpd

自動起動ON
[vagrant@localhost ~]$ sudo chkconfig add httpd
[vagrant@localhost ~]$ exit

OS再起動
$ vagrant reload

自動起動確認OK
$ vagrant ssh
[vagrant@localhost ~]$ ps -ef | grep httpd
root      1614     1  0 02:56 ?        00:00:00 /usr/sbin/httpd
apache    1616  1614  0 02:56 ?        00:00:00 /usr/sbin/httpd
apache    1617  1614  0 02:56 ?        00:00:00 /usr/sbin/httpd
apache    1618  1614  0 02:56 ?        00:00:00 /usr/sbin/httpd
apache    1619  1614  0 02:56 ?        00:00:00 /usr/sbin/httpd
apache    1620  1614  0 02:56 ?        00:00:00 /usr/sbin/httpd
apache    1621  1614  0 02:56 ?        00:00:00 /usr/sbin/httpd
apache    1622  1614  0 02:56 ?        00:00:00 /usr/sbin/httpd
apache    1623  1614  0 02:56 ?        00:00:00 /usr/sbin/httpd
vagrant   1625  1590  0 02:56 pts/0    00:00:00 grep httpd

/etc/httpd/conf/httpd.confを/vagrant/httpd.confのシンボリックリンクに変更
[vagrant@localhost ~]$ cp /etc/httpd/conf/httpd.conf /vagrant/.
[vagrant@localhost ~]$ sudo rm /etc/httpd/conf/httpd.conf
[vagrant@localhost ~]$ sudo ln -s /vagrant/httpd.conf /etc/httpd/conf/.
[vagrant@localhost ~]$ exit

OS再起動
$ vagrant reload

自動起動していない
$ vagrant ssh
[vagrant@localhost ~]$ ps -ef | grep httpd
vagrant   1647  1590  0 03:01 pts/0    00:00:00 grep httpd

起動コマンドで普通に起動する
[vagrant@localhost ~]$ sudo service httpd start
                                                           [  OK  ]

原因

これは、/etc/init.dの起動スクリプトが実行されるタイミングで/vagrantディレクトリがマウントされていないことが原因です。 その時点で必要なファイルが存在しないため、起動でエラーになってしまっています。

対策

起動スクリプトからVagrant共有ディレクトリのマウント状態をチェックするスクリプトを実行することで解決しました。

1. スクリプトの作成

[vagrant@localhost ~]$ sudo vi /usr/local/bin/vagrant-mount-checker
#!/bin/sh
check_vagrant_mount() {
  local prog=$1;
  for ((i = 1; i <= 6; i++))
  do
      [ -f /vagrant/Vagrantfile ] && return 0
      sleep 5
  done

  /usr/bin/logger -t vagrant-mount-checker "$prog couldn't start, because the vagrant shared directory didn't mount."
  return 1
}


2.起動スクリプトを編集

[vagrant@localhost ~]$ sudo vi /etc/init.d/httpd
~
#以下を処理の最初に追加
. /usr/local/bin/vagrant-mount-checker
check_vagrant_mount `basename $0`|| exit 1
~