玩转一下 Vagrant

发布于 2022-09-23 13:00:56 字数 21123 浏览 188 评论 0

Vagrant 是一款用于构建及配置虚拟开发环境的软件,基于 Ruby 主要以命令行的方式运行。 主要使用 Oracle 的开源 VirtualBox 虚拟化系统,与 Chef,Salt,Puppet 等环境配置管理软件搭配使用, 可以实行快速虚拟开发环境的构建。

安装 Vagrant

安装 Virtualbox

添加 Box

在 Vagrant 中,box 是一种打包好的镜像,通过这个镜像,可以生成相应的虚拟机。box 可以通过官方网站下载,也可以自己制作,在团队内分享。官方的 Box 可以在创建时自动下载。

➜  ~ vagrant box add centos7 ~/vagrant/centos-7.0-x86_64.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'centos7' (v0) for provider:
    box: Unpacking necessary files from: file:///Users/bingoobjca/vagrant/centos-7.0-x86_64.box
==> box: Successfully added box 'centos7' (v0) for 'virtualbox'!

初始化开发环境。

创建一个开发目录(比如:~/centos),也可以使用已有的目录。切换到开发目录里,用镜像初始化当前目录的环境。

初始化

  ~ mkdir centos
  ~ cd centos
  centos vagrant init centos7 ; vagrant up
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.
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos7'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: centos_default_1560154346360_66843
==> default: Clearing any previously set forwarded ports...
Vagrant is currently configured to create VirtualBox synced folders with
the `SharedFoldersEnableSymlinksCreate` option enabled. If the Vagrant
guest is not trusted, you may want to disable this option. For more
information on this option, please refer to the VirtualBox manual:

  https://www.virtualbox.org/manual/ch04.html#sharedfolders

This option can be disabled globally with an environment variable:

  VAGRANT_DISABLE_VBOXSYMLINKCREATE=1

or on a per folder basis within the Vagrantfile:

  config.vm.synced_folder '/host/path', '/guest/path', SharedFoldersEnableSymlinksCreate: false
==> default: Clearing any previously set network interfaces...
==> default: Preparing network interfaces based on configuration...
    default: Adapter 1: nat
==> default: Forwarding ports...
    default: 22 (guest) => 2222 (host) (adapter 1)
==> default: Booting VM...
==> default: Waiting for machine to boot. This may take a few minutes...
    default: SSH address: 127.0.0.1:2222
    default: SSH username: vagrant
    default: SSH auth method: private key
    default:
    default: Vagrant insecure key detected. Vagrant will automatically replace
    default: this with a newly generated keypair for better security.
    default:
    default: Inserting generated public key within guest...
    default: Removing insecure key from the guest if it's present...
    default: Key inserted! Disconnecting and reconnecting using new SSH key...
==> default: Machine booted and ready!
==> default: Checking for guest additions in VM...
    default: The guest additions on this VM do not match the installed version of
    default: VirtualBox! In most cases this is fine, but in rare cases it can
    default: prevent things such as shared folders from working properly. If you see
    default: shared folder errors, please make sure the guest additions within the
    default: virtual machine match the version of VirtualBox you have installed on
    default: your host and reload your VM.
    default:
    default: Guest Additions Version: 4.3.28
    default: VirtualBox Version: 6.0
==> default: Mounting shared folders...
    default: /vagrant => /Users/bingoobjca/centos

启动环境 vagrant up,用户 root/vagrant,密码 vagrant

  centos vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Machine already provisioned. Run `vagrant provision` or use the `--provision`
==> default: flag to force provisioning. Provisioners marked to run always will still run.

SSH 登录虚拟机

  centos vagrant ssh
Last login: Thu Jul 16 08:48:31 2015 from 10.0.2.2
Welcome to your Vagrant-built virtual machine.
[vagrant@bogon ~]$

常用命令:

  • vagrant init # 初始化
  • vagrant up # 启动虚拟机
  • vagrant halt # 关闭虚拟机
  • vagrant reload # 重启虚拟机
  • vagrant ssh # SSH 至虚拟机
  • vagrant status # 查看虚拟机运行状态
  • vagrant suspend # 挂起当前虚拟机
  • vagrant resume # 恢复被挂起的vm
  • vagrant box list # 列出所有box列表
  • vagrant box remove {base name} # 删除
  • vagrant destroy # 停止当前正在运行的虚拟机并销毁所有创建的资源
  • vagrant package # 把当前的运行的虚拟机环境进行打包,可用于分发开发环境
  • vagrant plugin # 安装卸载插件
  • vagrant provision # 设置基本的环境,进一步设置可以使用Chef/Puppet进行搭建
  • vagrant ssh-config # 输出ssh连接的一些信息
  • vagrant version # 获取vagrant的版本

参考:

  1. Mac OS 下安装 Vagrant

---------------------------------------

  1. 安装 go curl -O https://dl.google.com/go/go1.12.5.linux-amd64.tar.gz; tar zxf go1.12.5.linux-amd64.tar.gz; echo "export PATH=\$PATH:/home/vagrant/go/bin" >> ~/.bashrc; source ~/.bashrc
  2. 安装 git sudo yum install git
  3. 安装 upx curl -LO https://github.com/upx/upx/releases/download/v3.95/upx-3.95-amd64_linux.tar.xz; tar -xf upx-3.95-amd64_linux.tar.xz; echo "export PATH=\$PATH:/home/vagrant/upx-3.95-amd64_linux" >> ~/.bashrc; source ~/.bashrc

几个包的大小

➜  vagrant ls -lh
total 1000448
-rwxrwxrwx@ 1 bingoobjca  staff   475M  2 13 10:38 centos-7.0-x86_64.box
➜  vagrant ls -lh ~/Downloads/VirtualBox-6.0.8-130520-OSX.dmg
-rw-r--r--@ 1 bingoobjca  staff   137M  6 10 16:09 /Users/bingoobjca/Downloads/VirtualBox-6.0.8-130520-OSX.dmg
➜  vagrant ls -lh ~/Downloads/vagrant_2.2.4_x86_64.dmg
-rw-r--r--@ 1 bingoobjca  staff    31M  6 10 15:57 /Users/bingoobjca/Downloads/vagrant_2.2.4_x86_64.dmg

在 Vagrantfile 中指定IP和端口转发:

# hostname 设置
config.vm.hostname = "centos7"
# 网络设置,指定IP
config.vm.network "private_network", ip: "192.168.33.30"
config.vm.network "forwarded_port", guest: 8000, host: 8000
# 目录共享第一个参数是主机的目录,第二个参数是虚拟机挂载的目录
config.vm.synced_folder  "/Users/haohao/data", "/vagrant_data"

在 centos7 中设置语言(编辑 ~/.bash_profile):

export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8

关闭防火墙: sudo iptables -F

centos6 vagrant ssh-config output

➜  centos6 vagrant ssh-config
Host default
  HostName 127.0.0.1
  User vagrant
  Port 2200
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /Users/bingoobjca/centos6/.vagrant/machines/default/virtualbox/private_key
  IdentitiesOnly yes
  LogLevel FATA

Vagrant Cheat Sheet

转一篇 Vagrant 介绍-从使用到放弃再到掌握完全指南

起源

久闻 Vagrant 大名,之前经常看到有开源项目使用它作为分布式开发的环境配置。

因为今天在看 contiv 正好里面使用 vagrant 搭建的开发测试环境,所以顺便了解下。它的 Vagrantfile 文件中定义了三台主机。并安装了很多依赖软件,如 consul、etcd、docker、go 等,整的比较复杂。

netplugin git:(master) vagrant status
Current machine states:

netplugin-node1           running (virtualbox)
netplugin-node2           running (virtualbox)
netplugin-node3           running (virtualbox)

This environment represents multiple VMs. The VMs are all listed
above with their current state. For more information about a specific
VM, run `vagrant status NAME`.

Vagrant 是 hashicorp 这家公司的产品,这家公司主要做数据中心PAAS和虚拟化,其名下大名鼎鼎的产品有 Consul、Vault、Nomad、Terraform。他们的产品都是基于 Open Source 的 https://github.com/hashicorp。

用途

Vagrant 是用来管理虚拟机的,如 VirtualBox、VMware、AWS 等,主要好处是可以提供一个可配置、可移植和复用的软件环境,可以使用 shell、chef、puppet 等工具部署。所以 vagrant 不能单独使用,如果你用它来管理自己的开发环境的话,必须在自己的电脑里安装了虚拟机软件,我使用的是 virtualbox。

Vagrant 提供一个命令行工具 vagrant,通过这个命令行工具可以直接启动一个虚拟机,当然你需要提前定义一个 Vagrantfile 文件,这有点类似 Dockerfile 之于 docker 了。

跟 docker 类比这来看 vagrant 就比较好理解了,vagrant 也是用来提供一致性环境的,vagrant 本身也提供一个镜像源,使用 vagrant init hashicorp/precise64 就可以初始化一个 Ubuntu 12.04 的镜像。

用法

你可以下载安装文件来安装 vagrant,也可以使用 RubyGem 安装,它是用 Ruby 开发的。

Vagrantfile

Vagrantfile 是用来定义 vagrant project 的,使用 ruby 语法,不过你不必了解 ruby 就可以写一个 Vagrantfile。 看个例子,选自 https://github.com/fenbox/Vagrantfile

# -*- mode: ruby -*-
# vi: set ft=ruby :

# All Vagrant configuration is done below. The "2" in Vagrant.configure
# configures the configuration version (we support older styles for
# backwards compatibility). Please don't change it unless you know what
# you're doing.
Vagrant.configure("2") do |config|
  # The most common configuration options are documented and commented below.
  # For a complete reference, please see the online documentation at
  # https://docs.vagrantup.com.

  # Every Vagrant development environment requires a box. You can search for
  # boxes at https://atlas.hashicorp.com/search.
  config.vm.box = "ubuntu/trusty64"

  # Disable automatic box update checking. If you disable this, then
  # boxes will only be checked for updates when the user runs
  # `vagrant box outdated`. This is not recommended.
  # config.vm.box_check_update = false

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine. In the example below,
  # accessing "localhost:8080" will access port 80 on the guest machine.
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a private network, which allows host-only access to the machine
  # using a specific IP.
  config.vm.network "private_network", ip: "192.168.33.10"

  # Create a public network, which generally matched to bridged network.
  # Bridged networks make the machine appear as another physical device on
  # your network.
  # config.vm.network "public_network"

  # Share an additional folder to the guest VM. The first argument is
  # the path on the host to the actual folder. The second argument is
  # the path on the guest to mount the folder. And the optional third
  # argument is a set of non-required options.
  # config.vm.synced_folder "../data", "/vagrant_data"

  # Provider-specific configuration so you can fine-tune various
  # backing providers for Vagrant. These expose provider-specific options.
  # Example for VirtualBox:
  #
  # config.vm.provider "virtualbox" do |vb|
  #   # Display the VirtualBox GUI when booting the machine
  #   vb.gui = true
  #
  #   # Customize the amount of memory on the VM:
  #   vb.memory = "1024"
  # end
  #
  # View the documentation for the provider you are using for more
  # information on available options.

  # Define a Vagrant Push strategy for pushing to Atlas. Other push strategies
  # such as FTP and Heroku are also available. See the documentation at
  # https://docs.vagrantup.com/v2/push/atlas.html for more information.
  # config.push.define "atlas" do |push|
  #   push.app = "YOUR_ATLAS_USERNAME/YOUR_APPLICATION_NAME"
  # end

  # Enable provisioning with a shell script. Additional provisioners such as
  # Puppet, Chef, Ansible, Salt, and Docker are also available. Please see the
  # documentation for more information about their specific syntax and use.
  # config.vm.provision "shell", inline: <<-SHELL
  #   apt-get update
  #   apt-get install -y apache2
  # SHELL
  config.vm.provision :shell, path: "bootstrap.sh"
end

Boxes

Vagrant 的基础镜像,相当于 docker images。可以在这些基础镜像的基础上制作自己的虚拟机镜像。

添加一个 box

$ vagrant box add hashicorp/precise64

在 Vagrantfile 中指定 box

Vagrant.configure("2") do |config|
  config.vm.box = "hashicorp/precise64"
  config.vm.box_version = "1.1.0"
end

使用 ssh 进入 vagrant

vagrant up 后就可以用 vagrant ssh $name 进入虚拟机内,如果主机上就一个 vagrant 可以不指定名字。默认进入的用户是 vagrant。

文件同步

vagrant up 后在虚拟机中会有一个 /vagrant 目录,这跟你定义 Vagrantfile 是同一级目录。

这个目录跟你宿主机上的目录文件是同步的。

软件安装

在 Vagrantfile 中定义要安装的软件和操作。

例如安装 apache

在与 Vagrantfile 同级的目录下创建一个 bootstrap.sh 文件。

#!/usr/bin/env bash

apt-get update
apt-get install -y apache2
if ! [ -L /var/www ]; then
  rm -rf /var/www
  ln -fs /vagrant /var/www
fi

然后在 Vagrantfile 中使用它。

Vagrant.configure("2") do |config|
  config.vm.box = "hashicorp/precise64"
  config.vm.box_version = "1.1.0"
end

网络

端口转发

Vagrant.configure("2") do |config|
  config.vm.box = "hashicorp/precise64"
  config.vm.provision :shell, path: "bootstrap.sh"
  config.vm.network :forwarded_port, guest: 80, host: 4567
end

执行 vagrant reload 或者 vagrant up 可以生效。

分享

你自己做的 vagrant 是可以分享给别人的用的,只要你有一个 hashicorp 账号,vagrant login 后就可以执行 vagrant share 分享,会生成一个 URL,其它人也可以访问到你的 vagrant 里的服务。

中止

vagrant suspend
Vagrant halt
Vagrant destroy

重构

再次执行 vagrant up 即可。

boxes 存放位置

参考 As mentioned in the docs, boxes are stored at:

Mac OS X and Linux: ~/.vagrant.d/boxes
Windows: C:/Users/USERNAME/.vagrant.d/boxes

You can also use the env var VAGRANT_HOME to specify the location of .vagrant.d, as in VAGRANT_HOME=D:.vagrant.d (Yes, it works in Windows too).

  nginx-consul-vagrant git:(master) exa -l -T -L=2 ~/.vagrant.d/boxes
drwxr-xr-x  - bingoobjca 27 8 10:00 /Users/bingoobjca/.vagrant.d/boxes
drwxr-xr-x  - bingoobjca 27 8 10:00 ├── cbednarski-VAGRANTSLASH-ubuntu-1604
drwxr-xr-x  - bingoobjca 27 8 10:00 │  ├── 0.3.1
.rw-r--r-- 47 bingoobjca 27 8 10:00 │  └── metadata_url
drwxr-xr-x  - bingoobjca 10 6 15:59 ├── centos7
drwxr-xr-x  - bingoobjca 10 6 15:59 │  └── 0
drwxr-xr-x  - bingoobjca 12 6 15:58 ├── generic-VAGRANTSLASH-centos6
drwxr-xr-x  - bingoobjca 12 6 15:58 │  ├── 1.9.14
.rw-r--r-- 40 bingoobjca 12 6 15:58 │  └── metadata_url
drwxr-xr-x  - bingoobjca  6 8 14:23 └── ubuntu-VAGRANTSLASH-bionic64
drwxr-xr-x  - bingoobjca  6 8 14:23    ├── 20190801.1.0
.rw-r--r-- 40 bingoobjca  6 8 14:23    └── metadata_url

查看版本

➜  vagrant --version
Vagrant 2.2.5

vagrant 的 box 哪里下?镜像在哪儿找?教你在 vagrant 官网下载各种最新 .box 资源

进入 vagrant官网

点击findbox【寻找 box】,进入有很多 box 的 列表

比如我要下载 centos7,点击它,选择进入了它的 详情页

点击版本号,进入 1905.1版本详情页

拼 URL 'https://app.vagrantup.com/centos/boxes/7/versions/1905.1'+'/providers/'+'供应商名字/'+'.box'

公式:下载链接 = 产品版本链接 + 供应商英文意思 + 要下载的供应商名称(如virtualbox)+'.box'
https://app.vagrantup.com/centos/boxes/7/versions/1905.1/providers/virtualbox.box

用迅雷下载链接,稍微快点

vagrant 添加带版本号的 box

进入到 box 的下载目录,新建一个文件 centos.1905.1.json:

{
    "name": "centos/7",
    "versions": [{
        "version": "1905.1",
        "providers": [{
            "name": "virtualbox",
            "url": "./centos.1905.1.box"
        }]
    }]
}

执行命令添加:vagrant box add centos.1905.1.json

查看 box 列表:vagrant box list

➜ vagrant box add centos.1905.1.json
==> box: Loading metadata for box 'centos.1905.1.json'
    box: URL: file:///Users/bingoobjca/vagrant/centos.1905.1.json
==> box: Adding box 'centos/7' (v1905.1) for provider: virtualbox
    box: Downloading: ./centos.1905.1.box
==> box: Successfully added box 'centos/7' (v1905.1) for 'virtualbox'!
➜ vagrant box list
centos/7 (virtualbox, 1905.1)

Vagrant centos 上修正 yum 源

sudo rm -rf /etc/yum.repos.d/*.repo 
sudo curl -o /etc/yum.repos.d/CentOS-Base.repo https://mirrors.aliyun.com/repo/Centos-7.repo 
sudo curl -o /etc/yum.repos.d/epel.repo https://mirrors.aliyun.com/repo/epel-7.repo 
sudo sed -i '/aliyuncs/d' /etc/yum.repos.d/CentOS-Base.repo 
sudo sed -i 's/http/https/g' /etc/yum.repos.d/CentOS-Base.repo 
sudo sed -i 's/$releasever/7/g' /etc/yum.repos.d/CentOS-Base.repo 
sudo sed -i '/aliyuncs/d' /etc/yum.repos.d/epel.repo 
sudo sed -i 's/http/https/g' /etc/yum.repos.d/epel.repo 
sudo yum clean all 
sudo yum makecache fast 

设置通向主机的代理

export http_proxy=http://192.168.33.1:9999;
export https_proxy=http://192.168.33.1:9999;

CentOS 上:

$ ip a
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 52:54:00:8a:fe:e6 brd ff:ff:ff:ff:ff:ff
    inet 10.0.2.15/24 brd 10.0.2.255 scope global noprefixroute dynamic eth0
       valid_lft 67718sec preferred_lft 67718sec
    inet6 fe80::5054:ff:fe8a:fee6/64 scope link
       valid_lft forever preferred_lft forever
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:a2:d6:37 brd ff:ff:ff:ff:ff:ff
    inet 192.168.33.10/24 brd 192.168.33.255 scope global noprefixroute eth1
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:fea2:d637/64 scope link
       valid_lft forever preferred_lft forever

Host 上:

$ ifconfig
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
	options=1203<RXCSUM,TXCSUM,TXSTATUS,SW_TIMESTAMP>
	inet 127.0.0.1 netmask 0xff000000
	inet6 ::1 prefixlen 128
	inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
	nd6 options=201<PERFORMNUD,DAD>
utun0: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 1380
	inet6 fe80::acaf:7d2:8632:7e8%utun0 prefixlen 64 scopeid 0x14
	nd6 options=201<PERFORMNUD,DAD>
utun1: flags=8051<UP,POINTOPOINT,RUNNING,MULTICAST> mtu 2000
	inet6 fe80::8be0:a97d:27bf:a759%utun1 prefixlen 64 scopeid 0x15
	nd6 options=201<PERFORMNUD,DAD>
vboxnet0: flags=8943<UP,BROADCAST,RUNNING,PROMISC,SIMPLEX,MULTICAST> mtu 1500
	ether 0a:00:27:00:00:00
	inet 192.168.33.1 netmask 0xffffff00 broadcast 192.168.33.255

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

澜川若宁

暂无简介

0 文章
0 评论
22 人气
更多

推荐作者

linfzu01

文章 0 评论 0

可遇━不可求

文章 0 评论 0

枕梦

文章 0 评论 0

qq_3LFa8Q

文章 0 评论 0

JP

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文