Skip to content

使用 Vagrant + VirtualBox 在 Windows 上快速创建三台能 ping 通局域网及公网的安装好 dockercentos7 虚拟机

下载并且安装软件

https://www.virtualbox.org/wiki/Downloadshttps://www.vagrantup.com/downloadshttps://app.vagrantup.com/centos/boxes/7

添加虚拟机

bash
# 下载 box 文件添加到虚拟机中,执行如下命令
$ vagrant box add centos7 CentOS-7-x86_64.box

image.png

新建配置文件

脚本文件:https://github.com/WuChenDi/Front-End/tree/master/15-vagrant/centos7

Vagrantfile

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

Vagrant.require_version ">= 1.6.0"

boxes = [
    {
        :name => "manager",
        :eth1 => "192.168.31.160",
        :mem => "1024",
        :cpu => "1"
    },
    {
        :name => "worker1",
        :eth1 => "192.168.31.161",
        :mem => "1024",
        :cpu => "1"
    },
    {
        :name => "worker2",
        :eth1 => "192.168.31.162",
        :mem => "1024",
        :cpu => "1"
    }
]

Vagrant.configure(2) do |config|

  config.vm.box = "centos7"
  config.ssh.username = 'root'
  config.ssh.password = 'vagrant'
  config.ssh.insert_key = 'true'

  boxes.each do |opts|
      config.vm.define opts[:name] do |config|
        config.vm.hostname = opts[:name]
        config.vm.provider "vmware_fusion" do |v|
          v.vmx["memsize"] = opts[:mem]
          v.vmx["numvcpus"] = opts[:cpu]
        end

        config.vm.provider "virtualbox" do |v|
          v.customize ["modifyvm", :id, "--memory", opts[:mem]]
          v.customize ["modifyvm", :id, "--cpus", opts[:cpu]]
        end

        config.vm.network :private_network, ip: opts[:eth1]
      end
  end

  config.vm.synced_folder ".", "/home/vagrant"
  config.vm.provision "shell", privileged: true, path: "./setup.sh"

end

setup.sh

bash
#/bin/sh

# install some tools
sudo yum install -y git vim gcc glibc-static telnet psmisc

# install docker
curl -fsSL get.docker.com -o get-docker.sh
sh get-docker.sh

if [ ! $(getent group docker) ]; then
    sudo groupadd docker
else
    echo "docker user group already exists"
fi

sudo gpasswd -a $USER docker
sudo systemctl start docker

rm -rf get-docker.sh

# open password auth for backup if ssh key doesn't work, bydefault, username=vagrant password=vagrant
sudo sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
sudo systemctl restart sshd

执行 vagrant up 命令,按照配置 Vagrantfile 文件遍历创建虚拟机,并执行 shell 脚本去初始化虚拟机

image.png

Vagrant 常用命令

命令作用
vagrant box add添加box的操作
vagrant init初始化box的操作,会生成vagrant的配置文件Vagrantfile
vagrant up启动本地环境
vagrant ssh通过ssh登录本地环境所在虚拟机
vagrant halt关闭本地环境
vagrant suspend暂停本地环境
vagrant resume恢复本地环境
vagrant reload修改了Vagrantfile后,使之生效(相当于先halt,再up)
vagrant destroy彻底移除本地环境
vagrant box list显示当前已经添加的box列表
vagrant box remove删除相应的box
vagrant package打包命令,可以把当前的运行的虚拟机环境进行打包
vagrant plugin用于安装卸载插件
vagrant status获取当前虚拟机的状态
vagrant global-status显示当前用户Vagrant的所有环境状态