bingoohuang / blog

write blogs with issues
MIT License
178 stars 24 forks source link

玩转一下Vagrant #100

Open bingoohuang opened 5 years ago

bingoohuang commented 5 years ago

image

image

image

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

  1. 安装Vagrant

  2. 安装Virtualbox

  3. 添加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'!
  4. 初始化开发环境。

    创建一个开发目录(比如:~/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.
  5. 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 ~]$

常用命令:

参考:

  1. Mac OS 下安装 Vagrant
bingoohuang commented 5 years ago
  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
bingoohuang commented 5 years ago

几个包的大小

➜  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
bingoohuang commented 5 years ago

在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

bingoohuang commented 5 years ago

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
bingoohuang commented 5 years ago

Vagrant Cheat Sheet image

bingoohuang commented 5 years ago

转一篇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`.
```bash

Vagrant是[hashicorp](https://www.hashicorp.com/)这家公司的产品,这家公司主要做数据中心PAAS和虚拟化,其名下大名鼎鼎的产品有Consul、Vault、Nomad、Terraform。他们的产品都是基于Open Source的[Github地址](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

```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即可。

bingoohuang commented 5 years ago

boxes存放位置

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

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

改位置:

export VAGRANT_HOME=/data/vagrant
bingoohuang commented 5 years ago
➜  vagrant --version
Vagrant 2.2.5
bingoohuang commented 5 years ago

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

  1. 进入vagrant官网
  2. 点击findbox【寻找box】,进入有很多box的列表
  3. 比如我要下载centos7,点击它,选择进入了它的详情页
  4. 点击版本号,进入1905.1版本详情页
  5. 拼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

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

image

image

bingoohuang commented 5 years ago

vagrant 添加带版本号的 box

  1. 进入到 box 的下载目录,新建一个文件 centos.1905.1.json:
    {
        "name": "centos/7",
        "versions": [{
            "version": "1905.1",
            "providers": [{
                "name": "virtualbox",
                "url": "./centos.1905.1.box"
            }]
        }]
    }
  2. 执行命令添加:vagrant box add centos.1905.1.json
  3. 查看 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)
bingoohuang commented 5 years ago

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
bingoohuang commented 5 years ago

macOS升级,virtualbox升级,vagrant升级,结果共享文件夹失效了😭。

从vagrant里面拷贝文件到host里

vagrant ssh-config > config.txt
scp -F config.txt default:/path/to/file .

2019年11月13日

终于找到原因了,跟virtualbox的扩展包是否安装没有关系,跟box有关系,建议用bento/centos提供的box,/vagrant同步就没问题。