0%

Introduction to Vagrant

開始玩虛擬化之後,紀錄如何用VirtualBox + Vagrant打造自己的開發環境。

Box

可以把Box想像成光碟,需要安裝的時候,就拿出光碟開始安裝環境。

1
2
3
$ vagrant box list # 列出目前所有的Box
$ vagrant box add {title} {url}
$ vagrant box remove {title}

從網路下載的Box會存在`~.vagrant.d\boxes’下。

Create a virtual machine

有兩種方式,從Box衍生出來,或是寫個VagrantFile衍生。

從Box開始

1
2
$ vagrant init {title}
$ vagrant init {boxname}

後者會將box存到Box List中。
兩者都會產生一個VagrantFile檔案。

從VagrantFile開始

可以從網路上找到,或是自己從頭打造一個,裡面的內容大概像這樣,之後什麼都不用作,直接開啟VM就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# -*- mode: ruby; -*-
Vagrant.configure("2") do |config|
config.vm.guest = :freebsd
config.vm.box_url = "http://files.wunki.org/freebsd-10.0-amd64-wunki.box"
config.vm.box = "freebsd-10.0-amd64-wunki"
config.vm.network "private_network", ip: "10.0.1.10"

# Use NFS as a shared folder
config.vm.synced_folder ".", "/vagrant", :nfs => true, id: "vagrant-root"

config.vm.provider :virtualbox do |vb|
# vb.customize ["startvm", :id, "--type", "gui"]
vb.customize ["modifyvm", :id, "--memory", "512"]
vb.customize ["modifyvm", :id, "--cpus", "2"]
vb.customize ["modifyvm", :id, "--hwvirtex", "on"]
vb.customize ["modifyvm", :id, "--audio", "none"]
vb.customize ["modifyvm", :id, "--nictype1", "virtio"]
vb.customize ["modifyvm", :id, "--nictype2", "virtio"]
end
end

Manage Virtual Machine Commands

1
2
3
4
5
6
7
8
$ vagranmt up # 開啟VM
$ vagrant halt # 讓VM進入Poweroff Mode
$ vagrant suspend # 讓VM進入Suspend Mode
$ vagrant resume # 讓VM從Suspend Mode醒來
$ vagrant reload #重啟VM,主要是重新載入Configure file
$ vagrant status # 觀看目前VM狀況
$ vagrant destroy # 摧毀目前VM設定
$ vagrant ssh # 利用ssh管理VM

Multi-VM Environment

可以在一個VagrantFile中,同時設定多台VM環境。範例如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Vagrant.configure("2") do |config|
config.vm.define :web do |web|
web.vm.provider "virtualbox" do |v|
v.customize ["modifyvm", :id, "--name", "web", "--memory", "512"]
end
web.vm.box = "base"
web.vm.hostname = "web"
web.vm.network :private_network, ip: "11.11.1.1"
end

config.vm.define :db do |db|
db.vm.provider "virtualbox" do |v|
v.customize ["modifyvm", :id, "--name", "db", "--memory", "512"]
end
db.vm.box = "base"
db.vm.hostname = "db"
db.vm.network :private_network, ip: "11.11.1.2"
end
end

這樣同時有dbweb兩台VM。
之前上面的Manage VM Command緌果沒特別指定哪台vm的話,就會兩台同時動作,如果要指定特定機器的話,就像這樣。
vagrant halt web

重新打包一個Box

在手動設定環境之後,希望江設定好得環境存起來,方便他人或是自己之後使用。

1
$ vagrant package --output={boxname}

其他資料