---
title: "[转 ]vagrant使用简介"
author: "longgangbai"
date: "2014-01-10T13:53:30Z"
tags: []
categories: ["编程语言"]
slug: "vagrant"
draft: false
lastmod: "2014-01-10T13:53:30Z"
id: 2002302
url: "https://topmanopensource.iteye.com/blog/2002302"
---

**1&gt; 简介：**

 vagrant提供了易于配置，重复性好，便携式的工作环境，这些对开发人员非常有用，它可以让开发人员可以创建简单且可重复使用的基于VirtualBox的虚拟机（现在也支持VMware和AWS等），这些虚拟机可以快速的创建和销毁。vagrant也可以和puppet,chef等结合,实现虚拟机管理的自动化。vagrant的官网：[http://www.vagrantup.com](http://www.vagrantup.com/)本文出自cclo的blog，转载时请务必以超链接形式标明文章原始出处：[http://xuclv.blog.51cto.com/5503169/1239250](http://xuclv.blog.51cto.com/5503169/1239250)

 

**2&gt; 安装：（OS：ubuntu12.04 vagrant:1.2.2）**

 $ sudo apt-get install virtualbox

 $ sudo dpkg -i vagrant\_1.2.2\_x86\_64.deb

 

 版本1.0.x也可以这样安装（OS：ubuntu12.04）

 sudo apt-get install vagrant

 或

 1:sudo apt-get install virtualbox

 2:sudo apt-get install ruby1.9.1 rubygems

 3:gem install vagrant

 

 NOTE:在物理机的基础上安装virtualbox，如果用vm创建的虚拟机中再安装virtualbox和vagrant，那么vagrant将起不来。这里[http://downloads.vagrantup.com/](http://downloads.vagrantup.com/)下载相应的vagrant版本，注意1.0.x版本和1.1+版本的配置有较大不同，稍后在做介绍。

 

**3&gt; 一个简单的项目**

 版本1.1+

 $ vagrant init precise32 http://files.vagrantup.com/precise32.box

 $ vagrant up

 

 版本1.0.x and 1.1+

 $ vagrant box add precise32 http://files.vagrantup.com/precise32.box

 $ vagrant init precise32

 $ vagrant up

 上述命令运行后，将有一个虚拟机VirtualBox运行Ubuntu 12.04 LTS 32位的系统。使用命令$ vagrant ssh进入该系统。

 

NOTE："precise32"为虚拟机的名字，可以更改为你想用的名字。

      box是一个zip包，包含了vagrant的配置信息和VirtualBox的虚拟机镜像文件

      "http://files.vagrantup.com/precise32.box"为镜像所在的路径，可以为本地路径，所以建议将box下载下来后，指定为本地路径，速度会更快

      这里[http://www.vagrantbox.es/](http://www.vagrantbox.es/)有许多公共的base boxes可供下载和使用，后续将会介绍如何创建一个base box。

 

**4&gt; 常用的vagrant命令**:

 $ vagrant box add NAME URL    #添加一个box

 $ vagrant box list            #查看本地已添加的box

 $ vagrant box remove NAME virtualbox #删除本地已添加的box，如若是版本1.0.x，执行$ vagrant box remove  NAME

 $ vagrant init NAME          #初始化，实质应是创建Vagrantfile文件

 $ vagrant up                   #启动虚拟机

 $ vagrant halt                 #关闭虚拟机

 $ vagrant destroy            #销毁虚拟机

 $ vagrant reload             #重启虚拟机

 $ vagrant package            #当前正在运行的VirtualBox虚拟环境打包成一个可重复使用的box

 $ vagrant ssh                 #进入虚拟环境

 

**5&gt; Vagrantfile**

 官方解释是这样的：The primary function of the Vagrantfile is to describe the type of machine required for a project, and how to configure and provision these machines。翻译出来太生涩，简单来说就是配置这个虚拟主机网络连接方式，端口转发，同步文件夹，以及怎么和puppet，chef结合的一个配置文件。执行完$ vagrant init后,在工作目录中,你会发现此文件。

 

 NOTE：配置版本说明：

 

1

2

3

`Vagrant.configure("2") do` `|config|`

`# ...`

`end`

 当前支持的两个版本:"1"和"2". "1"：描述是Vagrant 1.0.x的配置（如看到Vagrant::Config.run do |config| 此也为Vagrant 1.0.x 的配置）；"2"：描述的是1.1+ leading up to 2.0.x的配置。vagrant 1.1+ 的Vagrantfiles能够与vagrant 1.0.x的Vagrantfiles保持向后兼容，也大幅引入新的功能和配置选项。

 

**6&gt; 配置网络**（本文将提供2种版本的常用配置，其中版本1的配置经过实践验证）

（1) 端口转发：（假设虚拟机的80端口提供web服务，此处将通过访问物理机的8080端口转发到虚拟机的80端口，来实现web的访问）

 版本"2"：

 

1

2

3

`Vagrant.configure("2") do` `|config|`

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

`end`

 

 版本"1"

 

1

2

3

4

`Vagrant::Config.run do` `|config|`

`# Forward guest port 80 to host port 8080`

`config.vm.forward_port 80, 8080`

`end`

 

 （2）桥接网络（公共网络，局域网DHCP服务器自动分配IP）

  版本"2"

 

1

2

3

`Vagrant.configure("2") do` `|config|`

`config.vm.network :public_network`

`end`

 

 

  版本"1"

1

2

3

`Vagrant::Config.run do` `|config|`

`config.vm.network :bridged`

`end`

  $ VBoxManage list bridgedifs | grep ^Name    #可通过此命令查看本机的网卡

    Name:            eth0

  指定网卡，配置可写为如下：

1

2

3

`Vagrant::Config.run do` `|config|`

`config.vm.network :bridged, :bridge => "eth0"`

`end`

 

 

  (3) 私有网络：允许多个虚拟机通过主机通过网络互相通信，vagrant允许用户分配一个静态IP，然后使用私有网络设置。

  版本"2"

 

1

2

3

`Vagrant.configure("2") do` `|config|`

`config.vm.network :private_network, ip: "192.168.50.4"`

`end`

 

  版本"1"

 

1

2

3

`Vagrant::Config.run do` `|config|`

`config.vm.network :hostonly, "192.168.50.4"`

`end`

 

 

**7&gt; 同步文件夹**

默认的，vagrant将共享你的工作目录（即Vagrantfile所在的目录）到虚拟机中的/vagrant,所以一般不需配置即可，如你需要可配置：

版本"2"

 

1

2

3

4

`Vagrant.configure("2") do` `|config|`

`# other config here`

`config.vm.synced_folder "src/", "/srv/website"`

`end`

 

  "src/"：物理机目录;"/srv/website"虚拟机目录

 

**8&gt; vagrant和shell**（实现在虚拟机启动的时候自运行需要的shell命令或脚本）

 版本"2"

 内嵌脚本：

 

1

2

3

4

`Vagrant.configure("2") do` `|config|`

`config.vm.provision :shell,`

`:inline => "echo Hello, World"`

`end`

 

 复杂点的调用如下：

 

1

2

3

4

5

6

7

`$script = <<SCRIPT`

`echo I am provisioning...`

`date > /etc/vagrant_provisioned_at`

`SCRIPT`

`Vagrant.configure("2") do` `|config|`

`config.vm.provision :shell, :inline => $script`

`end`

 外部脚本:

 

1

2

3

`Vagrant.configure("2") do` `|config|`

`config.vm.provision :shell, :path => "script.sh"`      `#脚本的路径相对于项目根，也可使用绝对路径`

`end`

 

 

 脚本可传递参数：

 

1

2

3

4

5

6

`Vagrant.configure("2") do` `|config|`

`config.vm.provision :shell do` `|s|`

`s.inline = "echo $1"`

`s.args   = "'hello, world!'"`

`end`

`end`

 

 版本"1":

 内部脚本：

 

1

2

3

`Vagrant::Config.run do` `|config|`

`config.vm.provision :shell, :inline => "echo abc > /tmp/test"`

`end`

 

 外部脚本：

 

1

2

3

`Vagrant::Config.run do` `|config|`

`config.vm.provision :shell, :path => "test.sh"`

`end`

 

 脚本参数：

 

1

2

3

4

5

6

`Vagrant::Config.run do` `|config|`

`config.vm.provision :shell do` `|shell|`

`shell.inline = "echo $1 > /tmp/test"`

`shell.args = "'this is test'"`

`end`

`end`

 

**9&gt; vagrant和puppet**(如果不知道puppet，请看这里[http://xuclv.blog.51cto.com/blog/5503169/1154261](http://xuclv.blog.51cto.com/blog/5503169/1154261))

(1) vagrant调用puppet单独使用

 

1

2

3

4

5

6

7

8

`Vagrant.configure("2") do` `|config|`

`config.vm.provision :puppet do` `|puppet|`

`puppet.manifests_path = "my_manifests"#路径相对于项目根，如无配置此项，默认为manifests`

`puppet.manifest_file = "default.pp"`      `#如无配置此项，默认为default.pp`

`puppet.module_path = "modules"`        `#路径相对于根`

`puppet.options = "--verbose --debug"`

`end`

`end`

 

 默认配置的目录结构：

 $ tree

  .

  |-- Vagrantfile

  |-- manifests

  |   |-- default.pp

(2) vagrant让puppet作为代理，连接Puppet master

 

1

2

3

4

5

6

7

`Vagrant.configure("2") do|config|`

`config.vm.provision :puppet_server do|puppet|`

`puppet.puppet_server = "puppet.example.com"#master域名`

`puppet.puppet_node = "node.example.com"#传递给puppet服务器节点的名称。默认为”puppet“`

`puppet.options = "--verbose --debug"#选项`

`end`

`end`

 NOTE：

 版本1配置差别不大，不再详述，区别：Vagrant.configure("2") do |config|改为Vagrant::Config.run do |config|

 以上Vagrantfile配置完毕后，可$ vagrant reload 重启虚拟机以来实现配置生效

 

 

 

官方给了一个例子(可尝试玩玩）：

1.进入工作目录

2.修改Vagrantfile

  $ vim Vagrantfile    #启用或添加如下行：

 

1

2

3

4

`Vagrant.configure("2") do` `|config|`

`config.vm.provision :puppet    #这里没有配置pp文件等的路径，全部采用默认`

`end`

`end`

 3.创建puppet的主目录

  $ mkdir manifests

 4.配置pp文件

  $ vim manifests/default.pp

 

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

`# Basic Puppet Apache manifest`

`class` `apache {`

`exec { 'apt-get update':`

`command => '/usr/bin/apt-get update'`

`}`

`package` `{ "apache2":`

`ensure => present,`

`}`

`service { "apache2":`

`ensure => running,`

`require => Package["apache2"],`

`}`

`file { '/var/www':`

`ensure => link,`

`target => "/vagrant",`

`notify => Service['apache2'],`

`force  => true`

`}`

`}`

`include` `apache`

 

5.重启虚拟机

 $ vagrant reload    #重启后可看到虚拟机中已经安装好了apache

 

**后记：**

总的来说vagrant还是一个简单好用的软件，常用于和puppet或者chef结合，实现测试环境的自动化部署，保证了测试环境的快速创建，便捷部署，一致性，同时也便于销毁。另，这里不常用chef，所以此篇文章不对其进行介绍，有兴趣的可以自行研究.

 

 

 

 

 

 

 

# [使用 Vagrant 打造跨平台开发环境](http://blog.segmentfault.com/fenbox/1190000000264347)

[![Vagrant](http://segmentfault.com/img/bVbg05)](http://segmentfault.com/img/bVbg05/view "点击查看原图")

[Vagrant](http://vagrantup.com/) 是一款用来构建虚拟开发环境的工具，非常适合 php/python/ruby/java 这类语言开发 web 应用，“代码在我机子上运行没有问题”这种说辞将成为历史。

我们可以通过 Vagrant 封装一个 Linux 的开发环境，分发给团队成员。成员可以在自己喜欢的桌面系统（Mac/Windows/Linux）上开发程序，代码却能统一在封装好的环境里运行，非常霸气。

## 安装步骤

### 1. 安装 VirtualBox

虚拟机还是得依靠 VirtualBox 来搭建，免费小巧。  
下载地址：[https://www.virtualbox.org/wiki/Downloads](https://www.virtualbox.org/wiki/Downloads)

** 虽然 Vagrant 也支持 VMware，不过 VMware 是收费的，对应的 Vagrant 版本也是收费的*

### 2. 安装 Vagrant

下载地址：[http://downloads.vagrantup.com/](http://downloads.vagrantup.com/) 根据提示一步步安装。

此外，还得下载官方封装好的基础镜像：  
Ubuntu precise 32 VirtualBox [http://files.vagrantup.com/precise32.box](http://files.vagrantup.com/precise32.box)  
Ubuntu precise 64 VirtualBox [http://files.vagrantup.com/precise64.box](http://files.vagrantup.com/precise64.box)

如果你要其他系统的镜像，可以来这里下载：[http://www.vagrantbox.es/](http://www.vagrantbox.es/)

** 鉴于国内网速，我们将下载镜像的步骤单独剥离出来了*

### 3. 添加镜像到 Vagrant

假设我们下载的镜像存放路径是 `~/box/precise64.box`，在终端里输入：

```bash
$ vagrant box add hahaha ~/box/precise64.box
```

`hahaha` 是我们给这个 box 命的名字，`~/box/precise64.box` 是 box 所在路径

### 4. 初始化开发环境

创建一个开发目录（比如：`~/dev`），你也可以使用已有的目录，切换到开发目录里，用 `hahaha` 镜像初始化当前目录的环境：

```bash
$ cd ~/dev  # 切换目录
$ vagrant init hahaha  # 初始化
$ vagrant up  # 启动环境
```

你会看到终端显示了启动过程，启动完成后，我们就可以用 SSH 登录虚拟机了，剩下的步骤就是在虚拟机里配置你要运行的各种环境和参数了。

```bash
$ vagrant ssh  # SSH 登录
$ cd /vagrant  # 切换到开发目录，也就是宿主机上的 `~/dev`
```

`~/dev` 目录对应虚拟机中的目录是 `/vagrant`

**Windows 用户注意**：Windows 终端并不支持 ssh，所以需要安装第三方 SSH 客户端，比如：Putty、Cygwin 等。

### 5. 其他设置

Vagrant 初始化成功后，会在初始化的目录里生成一个 `Vagrantfile` 的配置文件，可以修改配置文件进行个性化的定制。

Vagrant 默认是使用端口映射方式将虚拟机的端口映射本地从而实现类似 `http://localhost:80` 这种访问方式，这种方式比较麻烦，新开和修改端口的时候都得编辑相比较而言，host-only 模式显得方便多了。打开 `Vagrantfile`，将下面这行的注释去掉（移除 `#`）并保存：

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

重启虚拟机，这样我们就能用 `192.168.33.10` 访问这台机器了，你可以把 IP 改成其他地址，只要不产生冲突就行。

### 6. 打包分发

当你配置好开发环境后，退出并关闭虚拟机。在终端里对开发环境进行打包：

```bash
$ vagrant package
```

打包完成后会在当前目录生成一个 `package.box` 的文件，将这个文件传给其他用户，其他用户只要添加这个 box 并用其初始化自己的开发目录就能得到一个一模一样的开发环境了。

### 7. 常用命令

```bash
$ vagrant init  # 初始化
$ vagrant up  # 启动虚拟机
$ vagrant halt  # 关闭虚拟机
$ vagrant reload  # 重启虚拟机
$ vagrant ssh  # SSH 至虚拟机
$ vagrant status  # 查看虚拟机运行状态
$ vagrant destroy  # 销毁当前虚拟机
```

更多内容请查阅官方文档 [http://docs.vagrantup.com/v2/cli/index.html](http://docs.vagrantup.com/v2/cli/index.html)

### 8. 注意事项

使用 Apache/Nginx 时会出现诸如图片修改后但页面刷新仍然是旧文件的情况，是由于静态文件缓存造成的。需要对虚拟机里的 Apache/Nginx 配置文件进行修改：

```
# Apache 配置添加:
EnableSendfile off

# Nginx 配置添加:
sendfile off;
```

* * *

SegmentFault 团队就是用这种方式统一开发环境的  
本篇文章所用程序版本 VirtualBox 4.2.16，Vagrant 1.2.7