玩转Vagrant教程

发布时间 2023-03-29 16:27:51作者: gwy195600

Vagrant 简介

Vagrant 是一款用来构建虚拟开发环境的工具,非常适合 php/python/ruby/java 这类语言开发 web 应用,“代码在我机子上运行没有问题”这种说辞将成为历史。
我们可以通过 Vagrant 封装一个 Linux 的开发环境,分发给团队成员。成员可以在自己喜欢的桌面系统(Mac/Windows/Linux)上开发程序,代码却能统一在封装好的环境里运行,非常霸气。
当然啦,如果你和我一样有系统洁癖的话,也非常推荐使用 Vagrant 。毕竟电脑上经常莫名其妙会安装各种环境,导致有时候开发项目并不清楚究竟项目的依赖环境具体有哪些,使用 Vagrant 是一个很有逼格的解决方案。我自己的 Surface 和 Mac 都搭建了各种 Vagrant 的虚拟环境,如kingbase、mysql、postgresql、oracle、oceanbase、tidb等测试学习环境
当然如果你用各种虚拟机如 VirtualBox、VMware、AWS、Parallels Desktop 来搭建虚拟开发环境也没有什么不可以。但是我这里还是安利一下 Vagrant 。用 Vagrant 来装,不仅安装起来更方便快捷,而且后面真正开发中也会有很多好处。

Vargant的优点

1、 统一开发环境。一次配置打包,统一分发给团队成员,统一团队开发环境,解决诸如“编码问题”,“缺少模块”,“配置文件不同”带来的问题;
2、 避免重复搭建开发环境。新员工加入,不用浪费时间搭建开发环境,快速加入开发,减少时间成本的浪费;
3、 多个相互隔离开发环境。可以在不用box里跑不同的语言,或者编译安装同一语言不同版本,搭建多个相互隔离的开发环境,卸载清除时也很快捷轻松。

关于如何在Mac安装VirtualBox、Vagrant、Ruby网上有很多,当然建议还是参考官方文档:https://developer.hashicorp.com/vagrant/docs/installation

开篇之前,先介绍一下此文所使用的测试环境,其他版本总体流程类似,具体细节参考vagrant的CHANGELOG

https://github.com/hashicorp/vagrant/blob/v2.3.4/CHANGELOG.md

~ sw_vers
ProductName:	Mac OS X
ProductVersion:	10.15.7
BuildVersion:	19H2026
~ vagrant --version
Vagrant 2.3.4
~ vboxmanage --version
6.1.40r154048
~ vagrant plugin update
Updating installed plugins...
All plugins are up to date.
# 存放virtualbox虚机的位置
/Users/kevinge/VirtualBox\ VMs
# 存放vagrant开发环境的位置
/Users/kevinge/vm

如何初始化一个测试环境

从 vagrantcloud 上下载box镜像并添加 https://app.vagrantup.com/boxes/search

~ vagrant box add CentOS7U9 /Users/kevinge/Downloads/6a87c1da-35b9-408c-bbcd-eaf2519cd04a
~ vagrant box list
CentOS7U9        (virtualbox, 0)
# 如初始化一个mysql开发测试环境
~ mkdir -p /Users/kevinge/vm/mysql
~ cd /Users/kevinge/vm/mysql
~ vagrant init CentOS7U9
# 可以根据需求具体修改里面的内容
cat 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://vagrantcloud.com/search.
  config.vm.box = "Kevin/kingbase"

  # 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.
  # NOTE: This will enable public access to the opened port
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access
  # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

  # 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"
  config.vm.network "private_network", ip: "192.168.56.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.

  # Enable provisioning with a shell script. Additional provisioners such as
  # Ansible, Chef, Docker, Puppet and Salt 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
end
~ vagrant up --provision
~ vagrant ssh-config
Host default
  HostName 127.0.0.1
  User vagrant
  Port 2222
  UserKnownHostsFile /dev/null
  StrictHostKeyChecking no
  PasswordAuthentication no
  IdentityFile /Users/kevinge/vm/kingbase/.vagrant/machines/default/virtualbox/private_key
  IdentitiesOnly yes
  LogLevel FATAL
~ vagrant ssh
Last login: Wed Mar 29 06:09:51 2023 from 10.0.2.2
[vagrant@kes01 ~]$ sudo -i
[root@kes01 ~]# 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
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:b2:67:d0 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 81880sec preferred_lft 81880sec
3: eth1: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP group default qlen 1000
    link/ether 08:00:27:da:4b:73 brd ff:ff:ff:ff:ff:ff
    inet 192.168.56.10/24 brd 192.168.56.255 scope global noprefixroute eth1
       valid_lft forever preferred_lft forever
    inet6 fe80::a00:27ff:feda:4b73/64 scope link
       valid_lft forever preferred_lft forever
 [root@kes01 ~]# yum install -y mysql

vbox的导出导入

# 列出已安装的虚拟机
~ vboxmanage list vms
"kingbase_default_1680070081390_71513" {891e10ce-a7e6-4847-91e6-a2bf7d004d18}
"postgres_default_1680070266846_84831" {b0403e30-2175-4945-b47f-e9e5c079db6e}
"kfs_default_1680070848283_65448" {06fa775d-6cfc-49b8-90f8-aca3453251c5}
"gbase8a_default_1680071041601_23098" {24e1eb1a-92d4-4122-ac41-0112a0f20d83}
"almalinux8_default_1680071224157_156" {908c6433-edc4-45c8-a1fd-2dc20f20d9dc}
# 导出
~ vagrant package --base kingbase_default_1669114722176_72778 --output kingbase_default_1669114722176_72778
# 导入
~ vagrant box add Kevin/kingbase /Users/kevinge/vm/kingbase_default_1669114722176_72778
# 查询已存在的box
~ vagrant box list
CentOS7U9        (virtualbox, 0)
Kevin/kingbase   (virtualbox, 0)
~ mkdir -p /Users/kevinge/vm/kingbase
~ cd /Users/kevinge/vm/kingbase
~ vagrant init Kevin/kingbase
#需要注意的是,我们自己打包的vbox环境中,没有设置密钥方式,添加使用密码方式,其他根据自己需求修改
  config.ssh.username = "vagrant"
  config.ssh.password = "vagrant"
~ cat 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://vagrantcloud.com/search.
  config.vm.box = "Kevin/kingbase"
  config.ssh.username = "vagrant"
  config.ssh.password = "vagrant"
  
  # 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.
  # NOTE: This will enable public access to the opened port
  # config.vm.network "forwarded_port", guest: 80, host: 8080

  # Create a forwarded port mapping which allows access to a specific port
  # within the machine from a port on the host machine and only allow access
  # via 127.0.0.1 to disable public access
  # config.vm.network "forwarded_port", guest: 80, host: 8080, host_ip: "127.0.0.1"

  # 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"
  config.vm.network "private_network", ip: "192.168.56.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.

  # Enable provisioning with a shell script. Additional provisioners such as
  # Ansible, Chef, Docker, Puppet and Salt 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
end
~ vagrant up --provision
# 等vbox起来后,将刚才添加到Vagrantfile文件的使用密码方式的配置去掉
~ vagrant reload
# 这样就可以继续使用免密的方式,登录vbox环境了。

日常运维命令

~ vagrant box list   --列出vbox镜像
Almalinux8U7     (virtualbox, 0)
CentOS7U9        (virtualbox, 0)
Kevin/almalinux8 (virtualbox, 0)
Kevin/gbase8a    (virtualbox, 0)
Kevin/kfs        (virtualbox, 0)
Kevin/kingbase   (virtualbox, 0)
Kevin/postgres   (virtualbox, 0)
~ vagrant global-status  --查看vbox虚机运行状态
id       name    provider   state   directory
------------------------------------------------------------------------
c489bd9  default virtualbox running /Users/kevinge/vm/kingbase
e902bbb  default virtualbox running /Users/kevinge/vm/postgres
963dad8  default virtualbox running /Users/kevinge/vm/kfs
878c656  default virtualbox running /Users/kevinge/vm/gbase8a
830b1d2  default virtualbox saved   /Users/kevinge/vm/almalinux8

The above shows information about all known Vagrant environments
on this machine. This data is cached and may not be completely
up-to-date (use "vagrant global-status --prune" to prune invalid
entries). To interact with any of the machines, you can go to that
directory and run Vagrant, or you can use the ID directly with
Vagrant commands from any directory. For example:
"vagrant destroy 1a2b3c4d" --销毁一个vbox虚机
~ vagrant suspend 878c656  --挂起一个vbox虚机
==> default: Saving VM state and suspending execution...
~ vagrant resume 878c656
~ cd vm/kingbase
kingbase vagrant status
Current machine states:

default                   running (virtualbox)

The VM is running. To stop this VM, you can run `vagrant halt` to
shut it down forcefully, or you can run `vagrant suspend` to simply
suspend the virtual machine. In either case, to restart it again,
simply run `vagrant up`.
~ vagrant validate   --验证Vagrantfile文件
Vagrantfile validated successfully.
~ vagrant --help  --更多请查看帮助文档或官方文档
Usage: vagrant [options] <command> [<args>]

    -h, --help                       Print this help.

Common commands:
     autocomplete    manages autocomplete installation on host
     box             manages boxes: installation, removal, etc.
     cloud           manages everything related to Vagrant Cloud
     destroy         stops and deletes all traces of the vagrant machine
     global-status   outputs status Vagrant environments for this user
     halt            stops the vagrant machine
     help            shows the help for a subcommand
     init            initializes a new Vagrant environment by creating a Vagrantfile
     login
     package         packages a running vagrant environment into a box
     plugin          manages plugins: install, uninstall, update, etc.
     port            displays information about guest port mappings
     powershell      connects to machine via powershell remoting
     provision       provisions the vagrant machine
     push            deploys code in this environment to a configured destination
     rdp             connects to machine via RDP
     reload          restarts vagrant machine, loads new Vagrantfile configuration
     resume          resume a suspended vagrant machine
     serve           start Vagrant server
     snapshot        manages snapshots: saving, restoring, etc.
     ssh             connects to machine via SSH
     ssh-config      outputs OpenSSH valid configuration to connect to the machine
     status          outputs status of the vagrant machine
     suspend         suspends the machine
     up              starts and provisions the vagrant environment
     upload          upload to machine via communicator
     validate        validates the Vagrantfile
     version         prints current and latest Vagrant version
     winrm           executes commands on a machine via WinRM
     winrm-config    outputs WinRM configuration to connect to the machine

For help on any individual command run `vagrant COMMAND -h`

Additional subcommands are available, but are either more advanced
or not commonly used. To see all subcommands, run the command
`vagrant list-commands`.
        --[no-]color                 Enable or disable color output
        --machine-readable           Enable machine readable output
    -v, --version                    Display Vagrant version
        --debug                      Enable debug output
        --timestamp                  Enable timestamps on log output
        --debug-timestamp            Enable debug output with timestamps
        --no-tty                     Enable non-interactive output