使用 VirtualBox + Vagrant 快速构建适合你的开发环境!

1、Vagrant 简介

Vagrant 是一个用来构建和管理虚拟机环境的工具。Vagrant 有着易于使用的工作流,并且专注于自动化,降低了开发者搭建环境的时间,提高了生产力。解决了“在我的机器上可以工作”的问题。

Vagrant 是为了方便的实现虚拟化环境而设计的,使用 Ruby 开发,基于 VirtualBox 等虚拟机管理软件的接口,提供了一个可配置、轻量级的便携式虚拟开发环境。使用 Vagrant 可以很方便的就建立起来一个虚拟环境,而且可以模拟多台虚拟机,这样我们平时还可以在开发机模拟分布式系统。

团队新员工加入,常常会遇到花一天甚至更多时间来从头搭建完整的开发环境,而有了Vagrant,只需要直接将已经打包好的 package(里面包括开发工具,代码库,配置好的服务器等)拿过来就可以工作了,这对于提升工作效率非常有帮助。

2、为什么选择 Vagrant?

Vagrant 提供了一个易于配置,可重复使用,兼容的环境,通过一个单一的工作流程来控制,帮助你和团队最大化生产力和灵活性。 为了实现 Vagrant 的魔力,Vagrant 站在了巨人的肩膀上。虚拟机的配置基于 VirtualBox、VMware、AWS 或者其他提供商。然后一些配置工具,比如 shell 脚本,Chef 或者 Puppet 可以自动化地在虚拟机安装并配置软件。

对于开发者人员

如果你是一个开发者,Vagrant 将在一个一次性的、一致的环境中隔离依赖项及其配置,而不会影响你习惯使用的任何工具(编辑器、浏览器、调试器等)。一旦你或者其他人创建了一个 Vagrantfile,你只需要执行 vagrant up 所有的东西就自动安装和配置了。你团队中的其他成员使用同一个配置文件来创建开发环境,因此不管你工作在 Windows、Linux还是MacOS X, 所有团队的成员都可以在统一的环境环境中运行代码,这样就可以避免“在我的机器上可以工作”的问题。

对于运维人员

如果你是一个运维工程师或者 DevOps 工程师,Vagrant 给予你一个一次性的环境来开发和测试基础架构管理脚本。你可以使用本地虚拟机(比如 VirtualBox 或者 VMware)马上测试一些东西,比如 shell 脚本,Chef cookbooks,Puppet 模块等。然后,你可以用同样的配置在远程云上,比如 AWS 或者 RackSpace,来测试这些脚本。抛弃之前自定义脚本来回收 EC2 实例吧,停止使用 SSH 在各种机器之间跳来跳去,请开始使用 Vagrant 来给你的工作带来更多便利。

3、VirtualBox 安装

VirtualBox 是 Oracle 开源的虚拟化系统,和 VMware 是同类产品,支持多个平台,可以到官方站:https://www.virtualbox.org/wiki/Downloads 下载适合你平台的 VirtualBox 最新版本并安装。具体安装步骤,本教程不在赘述!

4、Vagrant 安装

到官方网站下载相应系统平台的安装包:http://www.vagrantup.com/downloads.html
直接根据向导进行操作即可完成安装,安装完后就可以在终端输入 vagrant 命令了。

提示:尽量下载最新的程序,因为 VirtualBox 经常升级,升级后有些接口会变化,旧版本的 Vagrant 可能无法使用。

4.1、检查 Vagrant 是否安装成功。

Microsoft Windows [版本 10.0.19042.685]
(c) 2020 Microsoft Corporation. 保留所有权利。

C:\Users\bood>vagrant -v
Vagrant 2.2.10

5、使用 Vagrant 构建 Linux 开发环境

提示:部分设备虚拟化(VT-X)技术默认处于关闭状态,需要在主板 BIOS 中开启 CPU虚拟化技术。

5.1、修改 Vagrant 默认目录

5.1.1、更改 VirtualBox 虚拟机映像文件的位置。

  • 打开 VirtualBox 程序,点击 管理/全局设定 菜单项, 将 常规 栏里的 默认虚拟电脑位置(M) 改为其他磁盘下的路径。

5.1.2、更改 vagrant 配置文件的位置。

  • C:\Users\bood\.vagrant.d 移动到新的位置。
  • 新建环境变量 VAGRANT_HOME ,并指向新路径。
  • 务必重启电脑,否则部分设备可能不会生效。

5.2、使用 Vagrant 命令拉取远程镜像(国内用户不推荐)

5.2.1、使用 https://app.vagrantup.com/boxes/search 中的镜像。(必须开启 VirtualBox)

使用 VirtualBox + Vagrant 快速构建适合你的开发环境!_第1张图片

拉取远程镜像命令:vagrant box add 镜像名

校验是否成功命令:vagrant box list

Microsoft Windows [版本 10.0.19042.685]
(c) 2020 Microsoft Corporation. 保留所有权利。

C:\Users\bood>D:

D:\>cd D:\Virtual

D:\Virtual>vagrant box add centos/7

...

D:\Virtual>vagrant box list
centos/7 (virtualbox, 0)

5.3、使用官方镜像离线安装(推荐)

5.3.1、(以 CentOS 为例)下载 CentOS 的 Vagrant 版镜像。

http://cloud.centos.org/centos/7/vagrant/x86_64/images

5.3.2、添加本地 centos/7 镜像(必须开启 VirtualBox)

CentOS-7-x86_64-Vagrant-2004_01.VirtualBox.box 移至工作文件目录。

1)、使用 vagrant box add <本地 box 名称> ,即 vagrant box add centos/7 D:\Virtual\Image\CentOS-7-x86_64-Vagrant-2004_01.VirtualBox.box 添加 vagrant 镜像。

2)、使用 vagrant box list 查询镜像。

3)、使用 vagrant init <本地 box 名称> ,即 vagrant init centos/7 命令,初始化 Box。

Microsoft Windows [版本 10.0.19042.685]
(c) 2020 Microsoft Corporation. 保留所有权利。

C:\Users\bood>vagrant box add centos/7 D:\Virtual\Image\CentOS-7-x86_64-Vagrant-2004_01.VirtualBox.box
==> box: Box file was not detected as metadata. Adding it directly...
==> box: Adding box 'centos/7' (v0) for provider:
    box: Unpacking necessary files from: file:///D:/Virtual/Image/CentOS-7-x86_64-Vagrant-2004_01.VirtualBox.box
    box:
==> box: Successfully added box 'centos/7' (v0) for 'virtualbox'!

C:\Users\bood>vagrant box list
centos/7 (virtualbox, 0)

C:\Users\bood>vagrant init centos/7
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.

5.3.3、设置 Vagrantfile 文件。

打开 C:\Users\bood 目录,设置 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 = "centos/7"

  # 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"

  # 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

1)、网络设置

config.vm.network “private_network”, ip: “192.168.33.10”

Vagrant 有两种方式来进行网络连接,一种是 host-only (主机模式),这种模式下所有的虚拟系统 是可以互相通信的,但虚拟系统和真实的网络是被隔离开的,虚拟机和宿主机是可以互相通信的,相当于两台机器通过双绞线互联。另一种是Bridge(桥接模式),该模式下的 VM 就像是局域网中的一台独立的主机,可以和局域网中的任何一台机器通信,这种情况下需要手动给 VM 配 IP 地址,子网掩码等。我们一般选择 host-only 模式。使用 ipconfig 命令,修改 vm 的 ip 地址。

2)、目录共享

/vagrant 目录默认就是当前的开发目录,这是在虚拟机开启的时候默认挂载同步的。我们还可以通过配置来设置额外的同步目录:

#第一个参数是主机的目录,第二个参数是虚拟机挂载的目录
config.vm.synced_folder “D:\Virtual\Share”, “/vagrant_data”

3)、端口转发

对宿主机器上 8080 端口的访问请求 forward 到虚拟机的 80 端口的服务上:

config.vm.network :forwarded_port, guest: 80, host: 8080

修改完毕后,使用 vagrant reload 命令,重新启动虚拟机,重新载入配置文件。

5.3.4、启动虚拟机。

虚拟机启动命令:vagrant up
启动虚拟机时会自动将当前目录(即 Vagrantfile 文件所在目录),和虚拟机的 /vagrant 目录共享。

Microsoft Windows [版本 10.0.19042.685]
(c) 2020 Microsoft Corporation. 保留所有权利。

C:\Users\bood>vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'centos/7'...
==> default: Matching MAC address for NAT networking...
==> default: Setting the name of the VM: bood_default_1608190392252_56486
==> 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: No guest additions were detected on the base box for this VM! Guest
    default: additions are required for forwarded ports, shared folders, host only
    default: networking, and more. If SSH fails on this machine, please install
    default: the guest additions and repackage the box to continue.
    default:
    default: This is not an error message; everything may continue to work properly,
    default: in which case you may ignore this message.
==> default: Rsyncing folder: /cygdrive/c/Users/bood/ => /vagrant

使用 CtrL + C 命令,强制退出当前执行命令行。

使用 vagrant ssh 命令连接新创建的虚拟机。

vagrant ssh-config 输出用于 ssh 连接的一些信息。

Microsoft Windows [版本 10.0.19042.685]
(c) 2020 Microsoft Corporation. 保留所有权利。

C:\Users\bood>vagrant up

...

C:\Users\bood>==> default: Waiting for cleanup before exiting...
vagrant ssh
[vagrant@localhost ~]$ whoami
vagrant
[vagrant@localhost ~]$ exit;
logout
Connection to 127.0.0.1 closed.

至此,使用 Vagrant 构建 Linux 开发环境完毕。

Vagrant 默认账号密码均为:vagrant , root 用户默认密码同为 vagrant

5.3.5、SSH 连接 Vagrant 虚拟机

首先确保 Vagrantfile 文件中 config.vm.network "private_network", ip: "192.168.33.10" ,与本地 ip 处于同一网段。

1)、使用 vagrant ssh 命令进入系统后。

2)、修改配置文件信息 vi /etc/ssh/sshd_config

修改 passwordAuthentication no 改为 yes

3)、重启 ssh 服务 systemctl restart sshd.service

5.3.6、删除相应的 box

使用 vagrant box remove <本地 box 名称> ,即 vagrant box remove centos/7。同时清理 C:\Users\bood 目录下的 .vagrant 文件夹和 Vagrantfile 文件。

5.3.7、销毁所有创建的资源

使用vagrant destroy,即所有创建的资源都会被销毁(谨慎操作)。

Vagrant 常用命令清单

  • vagrant box add 添加 box
  • vagrant init 初始化 box
  • vagrant up 启动虚拟机
  • vagrant ssh 登录虚拟机
  • vagrant box list 列出 Vagrant 当前 box 列表
  • vagrant box remove 删除相应的 box
  • vagrant destroy 停止当前正在运行的虚拟机,并销毁所有创建的资源
  • vagrant halt 关机
  • vagrant package 把当前的运行的虚拟机环境进行打包为 box 文件
  • vagrant plugin 安装卸载插件
  • vagrant reload 重新启动虚拟机,重新载入配置文件
  • vagrant resume 恢复被挂起的状态
  • vagrant status 获取当前虚拟机的状态
  • vagrant suspend 挂起当前的虚拟机
  • vagrant global-status 查看当前 vagrant 管理的所有 vm 信息

6、Vagrant 启动虚拟机集群

前面我们都是通过一个 Vagrantfile 配置启动单台机器,如果我们要启动一个集群,那么可以把需要的节点在一个 Vagrantfile 写好,然后直接就可以通过 vagrant up 同时启动多个 VM 组成一个集群。

1)、将 C:\Users\bood 下的 Vagrantfile 文件拷贝到工作目录下。编辑 Vagrantfile 文件。下面将模拟创建三个虚拟机。

Vagrant.configure("2") do |config|
 
    (1..3).each do |i|
 
        config.vm.define "node#{i}" do |node|
 
        # 设置虚拟机的Box
        node.vm.box = "centos/7"
 
        # 设置虚拟机的主机名
        node.vm.hostname="node#{i}"
 
        # 设置虚拟机的IP
        node.vm.network "private_network", ip: "192.168.56.#{100+i}"
 
        # 设置主机与虚拟机的共享目录
        # node.vm.synced_folder "~/Desktop/share", "/vagrant_data"
 
        # VirtaulBox相关配置
        node.vm.provider "virtualbox" do |v|
 
            # 设置虚拟机的名称
            v.name = "node#{i}"
 
            # 设置虚拟机的内存大小  
            v.memory = 1024
 
            # 设置虚拟机的CPU个数
            v.cpus = 1
        end
 
        end
    end
end
Microsoft Windows [版本 10.0.19042.685]
(c) 2020 Microsoft Corporation. 保留所有权利。

C:\Users\bood>D:

D:\>cd D:\Virtual\Node\node1

D:\Virtual\Node\node1>vagrant up
Bringing machine 'node1' up with 'virtualbox' provider...
Bringing machine 'node2' up with 'virtualbox' provider...
Bringing machine 'node3' up with 'virtualbox' provider...
==> node1: Importing base box 'centos/7'...
==> node1: Matching MAC address for NAT networking...
==> node1: Setting the name of the VM: node1
==> node1: Fixed port collision for 22 => 2222. Now on port 2200.
==> node1: Clearing any previously set network interfaces...
==> node1: Preparing network interfaces based on configuration...
    node1: Adapter 1: nat
    node1: Adapter 2: hostonly
==> node1: Forwarding ports...
    node1: 22 (guest) => 2200 (host) (adapter 1)
==> node1: Running 'pre-boot' VM customizations...
==> node1: Booting VM...
==> node1: Waiting for machine to boot. This may take a few minutes...
    node1: SSH address: 127.0.0.1:2200
    node1: SSH username: vagrant
    node1: SSH auth method: private key
    node1:
    node1: Vagrant insecure key detected. Vagrant will automatically replace
    node1: this with a newly generated keypair for better security.
    node1:
    node1: Inserting generated public key within guest...
    node1: Removing insecure key from the guest if it's present...
    node1: Key inserted! Disconnecting and reconnecting using new SSH key...
==> node1: Machine booted and ready!
==> node1: Checking for guest additions in VM...
    node1: No guest additions were detected on the base box for this VM! Guest
    node1: additions are required for forwarded ports, shared folders, host only
    node1: networking, and more. If SSH fails on this machine, please install
    node1: the guest additions and repackage the box to continue.
    node1:
    node1: This is not an error message; everything may continue to work properly,
    node1: in which case you may ignore this message.
==> node1: Setting hostname...
==> node1: Configuring and enabling network interfaces...
==> node1: Rsyncing folder: /cygdrive/d/Virtual/Node/node1/ => /vagrant
==> node2: Importing base box 'centos/7'...
==> node2: Matching MAC address for NAT networking...
==> node2: Setting the name of the VM: node2
==> node2: Clearing any previously set network interfaces...
==> node2: Preparing network interfaces based on configuration...
    node2: Adapter 1: nat
    node2: Adapter 2: hostonly
==> node2: Forwarding ports...
    node2: 22 (guest) => 2222 (host) (adapter 1)
==> node2: Running 'pre-boot' VM customizations...
==> node2: Booting VM...
==> node2: Waiting for machine to boot. This may take a few minutes...
    node2: SSH address: 127.0.0.1:2222
    node2: SSH username: vagrant
    node2: SSH auth method: private key
    node2:
    node2: Vagrant insecure key detected. Vagrant will automatically replace
    node2: this with a newly generated keypair for better security.
    node2:
    node2: Inserting generated public key within guest...
    node2: Removing insecure key from the guest if it's present...
    node2: Key inserted! Disconnecting and reconnecting using new SSH key...
==> node2: Machine booted and ready!
==> node2: Checking for guest additions in VM...
    node2: No guest additions were detected on the base box for this VM! Guest
    node2: additions are required for forwarded ports, shared folders, host only
    node2: networking, and more. If SSH fails on this machine, please install
    node2: the guest additions and repackage the box to continue.
    node2:
    node2: This is not an error message; everything may continue to work properly,
    node2: in which case you may ignore this message.
==> node2: Setting hostname...
==> node2: Configuring and enabling network interfaces...
==> node2: Rsyncing folder: /cygdrive/d/Virtual/Node/node1/ => /vagrant
==> node3: Importing base box 'centos/7'...
==> node3: Matching MAC address for NAT networking...
==> node3: Setting the name of the VM: node3
==> node3: Fixed port collision for 22 => 2222. Now on port 2201.
==> node3: Clearing any previously set network interfaces...
==> node3: Preparing network interfaces based on configuration...
    node3: Adapter 1: nat
    node3: Adapter 2: hostonly
==> node3: Forwarding ports...
    node3: 22 (guest) => 2201 (host) (adapter 1)
==> node3: Running 'pre-boot' VM customizations...
==> node3: Booting VM...
==> node3: Waiting for machine to boot. This may take a few minutes...
    node3: SSH address: 127.0.0.1:2201
    node3: SSH username: vagrant
    node3: SSH auth method: private key
    node3:
    node3: Vagrant insecure key detected. Vagrant will automatically replace
    node3: this with a newly generated keypair for better security.
    node3:
    node3: Inserting generated public key within guest...
    node3: Removing insecure key from the guest if it's present...
    node3: Key inserted! Disconnecting and reconnecting using new SSH key...
==> node3: Machine booted and ready!
==> node3: Checking for guest additions in VM...
    node3: No guest additions were detected on the base box for this VM! Guest
    node3: additions are required for forwarded ports, shared folders, host only
    node3: networking, and more. If SSH fails on this machine, please install
    node3: the guest additions and repackage the box to continue.
    node3:
    node3: This is not an error message; everything may continue to work properly,
    node3: in which case you may ignore this message.
==> node3: Setting hostname...
==> node3: Configuring and enabling network interfaces...
==> node3: Rsyncing folder: /cygdrive/d/Virtual/Node/node1/ => /vagrant

D:\Virtual\Node\node1>

至此,集群环境搭建完毕。集群环境下的 Vagrant 默认账号密码均为:vagrant , root 用户默认密码同为 vagrant

你可能感兴趣的:(服务器,virtualbox,vagrant,linux)