vagrantで複数の仮想サーバを作る
公式を参考に。
Multi-Machine - Vagrant Documentation
準備
適当なディレクトリを作成して、vagrant initする。ここは前回と変わりありません。
$ mkdir multi-server $ cd multi-server $ vagrant init
Vagrantfileの編集
# Vagrantfile Vagrant.configure("2") do |config| # webという仮想サーバを定義 config.vm.define :web do |web| # 中は、以前と同じですが、config.vmとなっていたところがweb.vmとなっています。 web.vm.box = "base" web.vm.network :private_network, ip:"192.168.50.13" end # dbという仮想サーバを定義 config.vm.define :db do |db| # こちらはconfig.vmがdb.vmに変わります。 db.vm.box = "base" db.vm.network :private_network, ip:"192.168.50.14" end end
起動、利用、停止、破棄
前回同様vagrant upで起動します。
$ vagrant up Bringing machine 'web' up with 'virtualbox' provider... [web] Importing base box 'base'... [web] Matching MAC address for NAT networking... [web] Setting the name of the VM... [web] Clearing any previously set forwarded ports... [web] Fixed port collision for 22 => 2222. Now on port 2200. [web] Creating shared folders metadata... [web] Clearing any previously set network interfaces... [web] Preparing network interfaces based on configuration... [web] Forwarding ports... [web] -- 22 => 2200 (adapter 1) [web] Booting VM... [web] Waiting for VM to boot. This can take a few minutes. [web] VM booted and ready for use! [web] Configuring and enabling network interfaces... [web] Mounting shared folders... [web] -- /vagrant Bringing machine 'db' up with 'virtualbox' provider... [db] Importing base box 'base'... [db] Matching MAC address for NAT networking... [db] Setting the name of the VM... [db] Clearing any previously set forwarded ports... [db] Fixed port collision for 22 => 2200. Now on port 2201. [db] Creating shared folders metadata... [db] Clearing any previously set network interfaces... [db] Preparing network interfaces based on configuration... [db] Forwarding ports... [db] -- 22 => 2201 (adapter 1) [db] Booting VM... [db] Waiting for VM to boot. This can take a few minutes. [db] VM booted and ready for use! [db] Configuring and enabling network interfaces... [db] Mounting shared folders... [db] -- /vagrant
これで、web,dbそれぞれの仮想サーバが起動します。ちなみに同じBoxを使っても、各サーバ用にコピーされるだけで、上書きされたりはしません。
vagrantコマンドの最後に仮想サーバの定義名をつけることで対象サーバを指定できます。
$ vagrant ssh web $ vagrant ssh db
Vagrantfileの*.vm.networkで指定したIPアドレスを使って、お互いに通信することが出来ます。
# webサーバにSSHログイン $ vagrant ssh web # そこから、dbサーバにSSHログイン $ ssh vagrant@192.168.50.14 # パスワードはvagrant
最後は仮想サーバを止めておきましょう
$ vagrant halt [web] Attempting graceful shutdown of VM... [db] Attempting graceful shutdown of VM...
いらなくなったら容量も圧迫するので破棄しましょう。
$ vagrant destroy Are you sure you want to destroy the 'db' VM? [y/N] y [db] Destroying VM and associated drives... Are you sure you want to destroy the 'web' VM? [y/N] y [web] Destroying VM and associated drives...
所感
これで、複数台構成の確認もできますね。複数サーバがある環境を作るの大変かと思ってましたが、とりあえずvagrantを使えば、Webアプリの動作確認レベルで困ることはなさそうです。*1
次は、Saharaというプラグインを使って、仮想サーバをある状態にロールバックしたりすることが出来るようにして、失敗したらやり直せるようにします。
*1:実際はネットワーク環境やサーバなどの物理的な制約によってトラブルが起きがちです。実際の本番環境でも必ず確認しましょう。