Vagrant工具

:::warning
参考大神文章:https://zhuanlan.zhihu.com/p/259833884
:::

Vagrant介绍

搭建 Linux 虚拟机,别再用 VirtualBox 从 .iso 文件安装了。

概述

2020 年了,也许你已经习惯了 docker,习惯了在 XX 云上快速创建云主机,但是如果你想在个人电脑上安装虚拟机来搭建开发/测试环境,Vagrant 仍然不失高效之选。
:::tips
现在很多人刚认识到 Vagrant 之后都会问,Vagrant 和 Docker 的区别是什么?
在容器流行之前,Vagrant 就是用来编排虚机和自动部署开发环境的,有了 Docker/Kubernetes 之后,直接用容器来编排应用确实更香。但是还有一些工作,例如容器平台自身的安装,多节点集群的部署测试等,更方便用虚机解决。
:::

安装Vagrant

:::warning
官方网站下载:https://www.vagrantup.com/
:::

Vagrant 的安装程序会自动把安装路径加入到 PATH 环境变量,所以,这时候可以通过命令行执行 vagrant version 检查是否安装成功:

vagrant version

image.png

配置 Vagrant

通过 Vagrant 创建虚机需要先导入镜像文件,也就是 box,它们默认存储的位置在用户目录下的 .vagrant.d 目录下,对于 Windows 系统来说,就是 C:\Users\用户名.vagrant.d。

如果后续可能会用到较多镜像,或者你的 C 盘空间比较紧缺,可以通过设置环境变量 VAGRANT_HOME 来设置该目录。
:::info
在 Windows 系统中,可以这样操作:新建系统环境变量,环境变量名为 VAGRANT_HOME,变量值为 D:\VirtualBox.vagrant.d
:::

注意,最后这个 .vagrant.d 目录名称不是必须的,但是建议保持一致,这样一眼看上去就能知道这个目录是做什么用处的了。

下载虚机镜像

使用 Vagrant 创建虚机时,需要指定一个镜像,也就是 box。开始这个 box 不存在,所以 Vagrant 会先从网上下载,然后缓存在本地目录中。
:::warning
Vagrant 有一个镜像网站,里面列出了都有哪些镜像可以用,并且提供了操作文档。
自己挑选合适的镜像,我使用的是ubuntu/bionic64
:::
image.png
image.png
:::info
可以直接在自己的命令行上输入:vagrant box add ubuntu/bionic64。它会自己在网上下载,当然速度会稍微慢一点
:::
image.png
下面我会介绍如何在其它地方下载到基础镜像,然后按照自己的需要重置。如果网速较好,下载顺利的朋友可以选择性地跳过部分内容。
下面我给出最常用的两个 Linux 操作系统镜像的下载地址:
CentOS
:::warning
CentOS 的镜像下载网站是: http://cloud.centos.org/centos/
:::
在其中选择自己想要下载的版本,列表中有一个 vagrant 目录,里面是专门为 vagrant 构建的镜像。选择其中的 .box 后缀的文件下载即可。这里可以使用下载工具,以较快的速度下载下来。
Ubuntu
:::warning
Ubuntu 的镜像下载网站是: http://cloud-images.ubuntu.com/
:::
同样先选择想要的版本,然后选择针对 vagrant 的 .box 文件即可。

添加 box

接下来我们需要将下载后的 .box 文件添加到 vagrant 中。
Vagrant 没有 GUI,只能从命令行访问,先启动一个命令行,然后执行:,我已经安装了一个Box

$ vagrant box list
ubuntu/bionic64 (virtualbox, 20230607.0.0)

像我这个是直接是命令行输入,自己网上下载的,所以默认就保存在C盘下,系统默认就找到了。如果是自己在镜像网站上下载的,那么首次查找Box可能报错。

$ vagrant box list
There are no installed boxes! Use `vagrant box add` to add some.

提示现在还没有 box。如果这是第一次运行,此时 VAGRANT_HOME 目录下会自动生成若干的文件和文件夹,其中有一个 boxes 文件夹,这就是要存放 box 文件的地方。
再执行 vagrant box add 命令添加 box:

$ vagrant box add e:\Downloads\CentOS-7.box --name centos-7
==> 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:///e:/Downloads/CentOS-7.box
    box:
==> box: Successfully added box 'centos-7' (v0) for 'virtualbox'!

命令后面跟着的是下载的文件路径,并且通过 --name centos-7 为这个 box 指定一个名字。
再次查询,就会找到这个Box了。

Vagrant 基本操作

新建虚机

创建一个目录,先执行 vagrant init:

 vagrant init ubuntu/bionic64

image.png
在当前目录下,会生成一个Vagrantfile文件
image.pngimage.png
image.png
这个命令只是为我们生成一个 Vagrantfile,所以,这里的名字没指定或者写错了都没关系,后面会介绍如何编辑这个 Vagrantfile 来修改。

启动虚机

$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Importing base box 'ubuntu/bionic64'...
==> default: Matching MAC address for NAT networking...
==> default: Checking if box 'ubuntu/bionic64' version '20230607.0.0' is up to date...
==> default: Setting the name of the VM: Vagrant_Vitual_default_1691123284133_65026
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: Running 'pre-boot' VM customizations...
==> 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: Warning: Connection reset. Retrying...
    default: Warning: Connection aborted. Retrying...
    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: 5.2.42
    default: VirtualBox Version: 7.0
==> default: Mounting shared folders...
    default: /vagrant => D:/Vagrant_Vitual

正常的情况下,不到一分钟应该就能启动成功了。

注意到这里包含的信息:

  • 虚机名称:demo_default_1588406874156_65036(想改?最后有提)
  • 网卡:Adapter 1: nat,第一块网卡,NAT 模式,这是固定的
  • 端口转发:22 (guest) => 2222 (host) (adapter 1),把虚机的 22 端口,映射到宿主机的 2222 端口上,这样就可以通过 127.0.0.1:2222 访问虚拟机了
  • SSH 用户名:vagrant,这里使用 private key 登录

查看虚机状态

新开一个终端。执行下面的命令可以查看虚机的状态:

vagrant status

image.png

连接虚拟机

默认使用ssh登录

vagrant ssh

image.png
需要我们升级一下,因为我用的版本是20.04的。第一次失败了,说的因为网络问题
image.png
root 用户没有默认密码,也不能直接登录。需要 root 权限的命令可以通过在命令前添加 sudo 来执行,也可以执行 sudo -i 直接切换到 root 用户。
image.png
我们也可以在 VirtualBox 的终端上登录系统,默认的登录用户名和密码都是 vagrant

使用SSH客户端

可以查看ssh的配置信息,查看private-key
image.png
复制到MobaXterm中。
image.png

停止虚机

执行下面的命令可以关闭虚机:

vagrant halt

直接在 VirtualBox 上关闭虚机,或者直接在虚机内部执行 poweroff 命令也都是可以的。

暂停虚机

执行下面的命令可以暂停虚机:

vagrant suspend

恢复虚机

执行下面的命令把暂停状态的虚机恢复运行:

vagrant resume

:::tips
注意: 不管虚机是关闭还是暂停状态,甚至是 error 状态,都可以执行 vagrant up 来让虚机恢复运行。
:::

重载虚机

执行下面的命令会重启虚机,并且重新加载 Vagrantfile 中的配置信息:

vagrant reload

删除虚机

最后,执行下面的命令可以彻底删除虚机,包括整个虚机文件:

vagrant destroy

:::tips
注意: 在当前这个小例子中,上面所有的 vagrant 命令都需要在 Vagrantfile 所在的目录下执行。
:::

初识 Vagrantfile

先来认识一下默认的 Vagrantfile 文件,使用带语法高亮的文本编辑器(例如 VSCode) 打开:

# -*- 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 = "ubuntu/bionic64"

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

  # Disable the default share of the current code directory. Doing this
  # provides improved isolation between the vagrant box and your host
  # by making sure your Vagrantfile isn't accessable to the vagrant box.
  # If you use this you may want to enable additional shared subfolders as
  # shown above.
  # config.vm.synced_folder ".", "/vagrant", disabled: true

  # 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

这是一个 Ruby 语法的文件,因为 Vagrant 就是用 Ruby 编写的。如果编辑器没有语法高亮可以手动设置文件类型为 Ruby。
这个缺省文件内容几乎都是注释,提示有哪些配置项可以修改,我们不需要去学 Ruby 编程也可以照葫芦画瓢的完成基本的配置。
刨除注释,这个文件的实际生效内容实际只有 3 行:

Vagrant.configure("2") do |config|
  config.vm.box = "ubuntu/bionic64"
end

首尾两行组成一个代码块结构,不要去动它,除非你知道自己在干什么。我们平常只需要编辑这其中的配置项。
这里的 config.vm.box 对应的就是虚机的镜像,也就是 box 文件,这是唯一必填的配置项。
特别提醒,Vagrantfile 文件名是固定的写法,大小写也要完全一样,修改了就不认识了。

自定义配置 Vagrantfile

下面将针对这份默认的 Vagrantfile 内容,逐个讲解其中的配置含义和如何根据实际情况修改。

配置端口转发

端口转发(Port forward)又叫端口映射,就是把虚机的某个端口,映射到宿主机的端口上。这样就能在宿主机上访问到虚拟机中的服务。
:::tips
例如启动虚机时,默认的 22 (guest) => 2222 (host) (adapter 1) 就是把虚机的 SSH 服务端口(22)映射到宿主机的 2222 端口,这样直接在宿主机通过 ssh 客户端访问 127.0.0.1:2222 端口就等价于访问虚拟机的 22 端口。
:::
下面这两段配置就是教我们如何配置额外的端口转发规则,例如把 Web 服务也映射出来:

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

实际上设置端口转发这个功能并不实用,一个很明显的问题就是如果启动多个虚机,很容易就出现宿主机上端口冲突的问题。即使没有端口冲突,使用起来也不方便,我个人不推荐使用的,可以把这部分配置直接删掉。直接使用下面的私有网络。
这个功能是虚拟机软件提供的,可以在虚机的网卡设置中展开高级选项,找到相关的配置:

配置私有网络

下面这段配置用来配置私有网络,实际上对应的是 VirtualBox 的主机网络,也就是 HostOnly 网络。

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

如果这个网段的主机网络在 VirtualBox 中不存在,Vagrant 会在启动虚机时自动创建。所以,如果你想要利用已有的网络,请查看现有主机网络配置:


最好这个网络也不要启用 DHCP,完全由自己来分配地址,这样更加清楚。
image.png

config.vm.network "private_network", ip: "192.168.56.1"

修改完成后,执行 vagrant reload 命令重建虚机,就能看到多出来的网卡了。
image.png
私有网络实际也可以直接使用 DHCP,但是并不推荐:

config.vm.network "private_network", type: "dhcp"

配置公共网络

下面这条配置用来配置公共网络:

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

正如注释所说,这里通常对应的就是桥接网络。实际开发场景下,我们极少会需要把虚机暴露到公共网络上,这样既不安全,也没有必要。
默认所起的第 1 个 NAT 网络已经保证了虚机可以上互联网,而私有网络保证了宿主机和虚机,以及虚机和虚机之间的通信。如果有对外暴露服务的需求,还可以使用端口转发。我实在想不出什么情况下是必须要用桥接网络的。
所以这部分配置可以直接删除,如确有使用的,可以参考 官方文档

配置同步文件夹

下面的配置项用来配置同步文件夹:

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

在启动虚机的时候,我们可以看到这样的提示:

==> 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: 5.2.42
    default: VirtualBox Version: 7.0
==> default: Mounting shared folders...
    default: /vagrant => D:/Vagrant_Vitual

先注意最后一行的提示:/vagrant => D:/Vagrant_Vitual
:::info

  • D:/Vagrant_Vitual 这是宿主机的本地目录,也就是 Vagrantfile 所在的目录。
  • /vagrant 是虚拟机内部的路径
    :::
    在参考的大神文章中,他是用的centos-7,所以还是有点区别的,这边也可以看一下,当然原文中讲的更详细。
==> 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: Configuring and enabling network interfaces...
==> default: Rsyncing folder: /cygdrive/c/Users/Davy/demo/ => /vagrant

最后一行的提示:Rsyncing folder: /cygdrive/c/Users/Davy/demo/ => /vagrant
:::info

  • /cygdrive/c/Users/Davy/demo/ 这是宿主机的本地目录,也就是 Vagrantfile 所在的目录。
  • /vagrant 是虚拟机内部的路径
  • Rsyncing 表示同步的方式是 Rsync
    :::

宿主机目录中出现 /cygdrive 是因为 Vagrant 程序用到了 Cygwin,它是在 Windows 系统中兼容 Linux/POSIX 的模拟层。可以把 /cygdrive 看成是虚拟的根目录。

Vagrant 默认的同步文件夹设置,别忘了 Vagrant 的作用是用来搭建开发环境的。所以它假定了当前目录是我们的开发项目所在目录,自动把本地的项目目录同步到虚机中,就可以快速的开始开发调试工作了。
:::danger

  1. 在 Vagrant_Vitual 目录下创建一些文件,例如 hello.c
  2. 执行 vagrant reload,重启虚机
  3. 在虚机启动完成后登录到虚机内,操作如下:
    :::
    因为我的gcc编译器还没安装,所以运行不了,但是效果是一样的。我后面将gcc的安装加到Vagrantfile里,我也是现学现做的。😛
    image.png
    看大佬的。
$ vagrant ssh
Last login: Sat May  2 16:25:00 2020 from 10.0.2.2
[vagrant@localhost ~]$ cd /vagrant/
[vagrant@localhost vagrant]$ ls
hello.py  Vagrantfile
[vagrant@localhost vagrant]$ python hello.py
helloworld

这种同步方式在大多数情况下都能提供便利,不过也有不足之处:
:::tips

  • 同步是一次性的,即只有启动虚机的时候执行,也就是说改了代码必须要重启一次虚机
  • 单向的,即只能从宿主机同步到虚拟机,也就是说在虚机内的改动不会同步到外面
  • 需要拷贝文件,如果要同步的文件数量较多,会占用更多的磁盘空间
    :::
    让我们按照默认配置的提示来新加一条同步文件夹配置试试:
config.vm.synced_folder "../data", "/vagrant_data"

注意,别忘了先在宿主机上创建 data 文件夹,重启虚机可能看到下面的错误提示:
这是因为 Vagrant 提供了多种同步方式,在使用 VirtualBox 的时候,缺省同步类型是 vboxsf 挂载文件系统,它需要在虚拟机内部安装客户机增强包,也就是 VirtualBox Guest Additions(输出信息中也提示了)。

如何在虚机系统中安装 guest additions 要分操作系统而定,有点小坑,后面会细说,现在修改一下配置,明确指定同步类型是 rsync:

config.vm.synced_folder "../data", "/vagrant_data", type: "rsync"

这样表示仍然使用 rsync 来单向同步。

更改虚机规格

VirtualBox 等虚拟机软件在 Vagrant 中被称为 Provider,虚机的规格等配置是和 Provider 相关的。因为 VirtualBox 用的最多,所以默认的配置提示是以 VirtualBox 举例。
把中间那一段取消注释,其它的可以删掉:

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

vb.gui = true 是在虚机启动时自动打开 VirtualBox 的图形界面,这对服务器来说没什么用,可以留也可以直接删掉。
添加 CPU 的配置,同时修改内存大小:这里将内存修改为2048MB,cpus数量是2

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.cpus = 2		
  vb.memory = "2048"
end

注意到,内存的大小单位是 MB,值是数字,默认的示例中有引号,实际也可以不加。
特别提醒一下,在 说明文档 里给的例子,其中的变量名是 v,这其实是在双竖线中定义的,直接拷贝的时候要看清楚。

Provision

Provision 是指在虚机初次创建的时候,Vagrant 自动去执行的构造任务,比如安装软件,更新系统配置等
因为 box 往往只提供基础的系统(虽然我们可以自定义 box,但是并不是每次都要这么做,而且这样做会丧失一部分灵活性),有些东西仍然需要在创建虚机的时候完成。

# 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

因为这部分完全是个开放的内容,所以我们这里不过多讨论,来看一下什么情况下会触发 provision 的操作:
:::danger

  • 某个环境初次执行 vagrant up 的时候
  • 执行 vagrant provision 命令
  • 重启的时候 vagrant reload --provision,带上 --provision 选项
    :::
    现在可以在这里添加GCC的安装的案例了。。。
config.vm.provision "shell", inline: <<-SHELL
  apt-get update
  yes | apt install gcc 
SHELL

image.png
测试:安装Docker

config.vm.provision "shell", inline: <<-SHELL
  apt-get update
  yes | apt-get install ca-certificates curl gnupg
  yes | install -m 0755 -d /etc/apt/keyrings 
  curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
  chmod a+r /etc/apt/keyrings/docker.gpg

  echo \
  "deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
  "$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \
  tee /etc/apt/sources.list.d/docker.list > /dev/null

  apt-get update
  yes | apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

SHELL

image.png

配置如果出现了双引号,就会发现小问题,最好的办法就是把要执行的指令写到一个单独的脚本中,这样的话,后期也方便管理。

  1. 创建shell脚本文件,vagrant_bash.sh
#!/bin/bash

echo "vagrant_bash sh is running...."

apt-get update
apt-get install -y ca-certificates curl gnupg
install -y -m 0755 -d /etc/apt/keyrings 
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
chmod a+r /etc/apt/keyrings/docker.gpg

echo \
"deb [arch="$(dpkg --print-architecture)" signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
"$(. /etc/os-release && echo "$VERSION_CODENAME")" stable" | \
tee /etc/apt/sources.list.d/docker.list > /dev/null

apt-get update
apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

image.png

  1. 在vagrantfile中加上如下的配置:
  config.vm.provision "shell" do |s|
      s.path = "./Script/vagrant_bash.sh"
  end 
  1. vagrant provision更新配置

image.png
除了上面这些默认提示给出的配置项,Vagrantfile 还支持其它很多配置,具体请 查看文档
由于 Vagrantfile 本身是 Ruby 脚本,所以它并不仅仅是静态的配置文件,而且可以包含程序逻辑,例如在 如何创建多个虚机 中就有应用,有兴趣的可以自行研究。

使用模板文件

vagrant init 命令只是用来生成 Vagrantfile 文件,但是默认的配置选项每次都要修改也很麻烦。该命令提供了 --template 选项,可以指定一个模板文件,我们可以在自定义自己的模板文件。

这个模板文件的格式 ERB 是 Ruby 的模板语法。可以从 这里 拷贝一份原文件,还能在 Vagrant 的安装位置 Vagrant\embedded\gems\2.2.7\gems\vagrant-2.2.7\templates\commands\init 底下找到,并且有一个 Vagrantfile.min.erb 是去掉所有注释的:

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 = "<%= box_name %>"
  <% if box_version -%>
  config.vm.box_version = "<%= box_version %>"
  <% end -%>
end

可以看到其中是怎么配置 config.vm.box 的。 像 <% 这样的语法有兴趣可以自己去了解,这里我们只要把自己想要的配置项原样写上去就行了。
下面看一下大神写的:

Vagrant.configure("2") do |config|
  config.vm.box = "<%= box_name %>"
  config.vm.network "forwarded_port", guest: 22, host: 2222, id: "ssh", disabled: "true"
  config.vm.network "forwarded_port", guest: 22, host: 22222

  # config.vm.network "private_network", ip: "192.168.56.10"
  # config.vm.synced_folder "../data", "/data"

  config.vm.provider "virtualbox" do |vb|
    # vb.name = "give me a better name"
    vb.memory = "1024"
  end
end

:::tips
不要有中文,不然会遇到编码的麻烦。
:::
其中像私有网络和同步文件夹配置,几乎每次基本都要,但是又不好固定,所以仍然以注释的形式保留,每次稍微改一下也很方便。
把这个文件找个目录,保存为 vagrant.erb。
接着在使用 vagrant init 的时候通过 --tempate 指定它就可以了,例如:
显然,每次要记住并且输入这个模板文件也很麻烦的。可以通过设置环境变量 VAGRANT_DEFAULT_TEMPLATE 来一劳永逸地解决这个问题。

定制带客户机增强的 box

这个待定吧,看大佬的吧,我自己还没做。。。。

大佬文章:https://zhuanlan.zhihu.com/p/259833884

Vagrant出现的Bug解决

  1. D:/Vagrant/embedded/gems/gems/net-scp-4.0.0/lib/net/scp.rb:398:in `await_response_state’: \x01scp: /tmp/vagrant-network-entry-1691135945: No space left on device (Net::SCP::Error)
    :::danger
    参考文章:https://blog.csdn.net/llb_3601478/article/details/118087732
    :::
    image.png
    此时的虚拟机是已经在运行了,只是无法运行指令,因为没内存了。我查看了以下磁盘空间利用情况,发现,好家伙。dev/sda1炸了。。。
    image.png
    通过命令du -sm * 2> /dev/null | sort -nr | head -5和find . -type f -size +800M找到大目录和大文件,然后做相应的清理即可:
    注意:生产环境清理需谨慎,清理之前最好做一个备份操作。
    image.png
    使用命令vagrant reload重新加载,启动正常:

按照剧情是这么就解决了,但是我试了,查不到大文件。。。。shit.
我直接 😤删除重装个虚拟机。。。简单粗暴
:::danger
vagrant destroy #删除虚拟机😤
:::

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值