vagrant的官方网站:http://www.vagrantup.com/

Vagrant是用Ruby语言开发的专门用于构建虚拟化开发环境的工具,Vagrant封装了虚拟镜像,Virtualbox接口以及大量的成熟的配置工具,从而帮助我们快速的创建,配置可重复使用与大量分发的虚拟开发环境.

##新建一台Ubuntu VM

1
2
3
4
5
$vagrant box add precise64 http://files.vagrantup.com/precise64.box
$mkdir my_box
$cd my_box
$vagrant init precise64
$vagrant up

##vagrant 基本命令 VM Lifecycle

1
2
3
4
5
6
$vagrant up        #startup VM
$vagrant ssh #ssh login
$vagrant suspend #suspend VM
$vagrant halt #shutdown VM
$vagrant destroy #remove VM
$vagrant status

##BOXes

第三方box 提供
http://www.vagrantbox.es/

##box管理

1
2
3
$vagrant box list
$vagrant box add
$vagrant box remove

##配置文件

Vagrantfile 内容

1
2
3
4
5
Vagrant.configure("2") do |config|
config.vm.box = "precise64"
#如果找不到 box文件,从以下地址下载
config.vm.box_url = "http://files.vagrantup.com/precise64.box"
end

Shared Folder

在host与VM间共享文件夹,
例如在Host里面编辑代码,在VM中执行,
VirtualBox Shared Folder 效率较差,所以vagrant使用NFS共享。

1
2
config.vm.share_folder "foo", "/GuestOS/path", "/HostOS/path",
:nfs => true

Networking

Port Forwarding

1
config.vm.network :forwarded_port, guest: 80, host: 8080

将guest 80端口转发到host 8080端口

Host-only networking

1
config.vm.network :private_network, ip: "172.16.1.10"

为guest OS指定ip地址,只有host可以访问

Bridged Networking

1
config.vm.network :public_network

打包现有VM成box

1
$vagrant package

集成chef

1
2
3
4
5
6

config.vm.provision :chef_solo do |chef|
chef.cookbooks_path = "./cookbooks"
chef.add_recipe "nginx"
chef.json = { :nginx => { :worker_processes => "4"}}
end

Chef Example

1
2
3
4
5
6
7
8
9
package "nginx"
service "nginx" do
supports :status => true, :restart => true, reload => true
action [:enable, :start]
end
template "/etc/nginx/nginx.conf" do
source "nginx.conf.erb"
notifies :reload,"service[nginx]"
end

Multi-VM

同一个vagrantfile 可以设定多个VM,vagrant up 会同时启动多个虚拟机

Example:
一台 Web server,一台 application servers,一台 database server

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

Vagrant.configure("2") do |config|
config.vm.define :web do |web|
web.vm.box = "precise64"
web.vm.network :private_network, :ip => "172.16.1.2"
end
config.vm.define :app do |app|
app.vm.box = "precise64"
app.vm.network :private_network, :ip => "172.16.1.3"
end
config.vm.define :db do |db|
db.vm.box = "precise64"
db.vm.network :private_network, :ip => "172.16.1.4"
end
end