はじめてのVagrant

仮想環境構築ツールのVagrantをMac OS Xにインストールした時のメモです。

環境

Mac OS X 10.9.4

VirtualBoxのインストール

https://www.virtualbox.org/wiki/Downloads

Mac版をダウンロードしてインストールします。

バージョンは現時点最新の4.3.16

Vagrantのインストール

http://downloads.vagrantup.com/

Mac版をダウンロードしてインストールします。

バージョンは現時点最新の1.3.5

準備

Vagrant用のファイルは以下ディレクトリに格納するようにします。

$ mkdir -p ~/vagrant
$ cd ~/vagrant

仮想イメージを取得する

以下のURLから「box」というVagrant用のOSイメージのURLを探してコピーします。
ここではCentOS 6.5 x86_64を追加してみます。

http://www.vagrantbox.es/

$ vagrant box add centos653 https://github.com/2creatives/vagrant-centos/releases/download/v6.5.3/centos65-x86_64-20140116.box
Downloading or copying the box...
Extracting box...te: 1868k/s, Estimated time remaining: 0:00:01)
Successfully added box 'centos653' with provider 'virtualbox'!

仮想サーバを起動する

$ vagrant init centos653
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.
$ vagrant up

仮想サーバにアクセスする

$ vagrant ssh

使い方

# 仮想サーバを追加する
$ vagrant box add [box-name] [box-url]
 
# 仮想サーバを起動する
$ vagrant up
 
# 仮想サーバをシャットダウンする
$ vagrant halt

# 仮想サーバをまっさらな状態にする
$ vagrant destroy

# 追加したboxを表示する
$ vagrant box list

# boxを削除する
$ vagrant box remove [box-name]

仮想サーバの状態をエクスポートする

$ vagrant package
[default] Clearing any previously set forwarded ports...
[default] Creating temporary directory for export...
[default] Exporting VM...
[default] Compressing package to: /Users/username/vagrant/package.box

これでエクスポート完了。

package.boxというファイルが生成されるのでそれをaddすればインポートすることができる。

$ vagrant box add centos653_2 package.box
Downloading or copying the box...
Extracting box...te: 132M/s, Estimated time remaining: 0:00:01)
Successfully added box 'centos653_2' with provider 'virtualbox'!

SSHの設定

ssh [host]でログインできるようにします。

$ vagrant ssh-config --host vagrant-node1 >> ~/.ssh/config

これで以下のようにログインできるようになります。

$ ssh vagrant-node1

ネットワークの設定

このままだとlocalhostでの接続になっていますので、直接IPアドレスを指定して接続できるように設定します。

# ~/vagrant/Vagrantfile

config.vm.network :private_network, ip: "192.168.33.10"

以上、Vagrantの使い方でしたー。