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

下载并且安装软件

https://www.virtualbox.org/wiki/Downloads
https://www.vagrantup.com/downloads
https://app.vagrantup.com/centos/boxes/7

添加虚拟机

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

image.png

新建配置文件

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

Vagrantfile

  1. # -*- mode: ruby -*-
  2. # vi: set ft=ruby :
  3. Vagrant.require_version ">= 1.6.0"
  4. boxes = [
  5. {
  6. :name => "manager",
  7. :eth1 => "192.168.31.160",
  8. :mem => "1024",
  9. :cpu => "1"
  10. },
  11. {
  12. :name => "worker1",
  13. :eth1 => "192.168.31.161",
  14. :mem => "1024",
  15. :cpu => "1"
  16. },
  17. {
  18. :name => "worker2",
  19. :eth1 => "192.168.31.162",
  20. :mem => "1024",
  21. :cpu => "1"
  22. }
  23. ]
  24. Vagrant.configure(2) do |config|
  25. config.vm.box = "centos7"
  26. config.ssh.username = 'root'
  27. config.ssh.password = 'vagrant'
  28. config.ssh.insert_key = 'true'
  29. boxes.each do |opts|
  30. config.vm.define opts[:name] do |config|
  31. config.vm.hostname = opts[:name]
  32. config.vm.provider "vmware_fusion" do |v|
  33. v.vmx["memsize"] = opts[:mem]
  34. v.vmx["numvcpus"] = opts[:cpu]
  35. end
  36. config.vm.provider "virtualbox" do |v|
  37. v.customize ["modifyvm", :id, "--memory", opts[:mem]]
  38. v.customize ["modifyvm", :id, "--cpus", opts[:cpu]]
  39. end
  40. config.vm.network :private_network, ip: opts[:eth1]
  41. end
  42. end
  43. config.vm.synced_folder ".", "/home/vagrant"
  44. config.vm.provision "shell", privileged: true, path: "./setup.sh"
  45. end

setup.sh

  1. #/bin/sh
  2. # install some tools
  3. sudo yum install -y git vim gcc glibc-static telnet psmisc
  4. # install docker
  5. curl -fsSL get.docker.com -o get-docker.sh
  6. sh get-docker.sh
  7. if [ ! $(getent group docker) ]; then
  8. sudo groupadd docker
  9. else
  10. echo "docker user group already exists"
  11. fi
  12. sudo gpasswd -a $USER docker
  13. sudo systemctl start docker
  14. rm -rf get-docker.sh
  15. # open password auth for backup if ssh key doesn't work, bydefault, username=vagrant password=vagrant
  16. sudo sed -i 's/PasswordAuthentication no/PasswordAuthentication yes/g' /etc/ssh/sshd_config
  17. 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的所有环境状态

[

](https://blog.csdn.net/weixin_52678046/article/details/112002314)