前言
Varangt可以配置私有网络,有多种方式,其中静态IP是我常用的一种。本文介绍如何为虚拟机指定静态IP。
设置静态IP
当你为虚拟机指定静态 IP后,主机就可以通过指定的静态 IP 访问虚拟机。如,以下是Vagrantfile文件中的某一行
config.vm.network "private_network", ip: "192.168.33.22"
表示虚拟机的静态IP为192.168.33.22。那么运行vagrant up启动虚拟机后,主机可ping通192.168.33.22
C:\Users\bin9w>ping 192.168.33.22
正在 Ping 192.168.33.22 具有 32 字节的数据:
来自 192.168.33.22 的回复: 字节=32 时间<1ms TTL=64
来自 192.168.33.22 的回复: 字节=32 时间<1ms TTL=64
来自 192.168.33.22 的回复: 字节=32 时间<1ms TTL=64
来自 192.168.33.22 的回复: 字节=32 时间<1ms TTL=64
192.168.33.22 的 Ping 统计信息:
数据包: 已发送 = 4,已接收 = 4,丢失 = 0 (0% 丢失),
往返行程的估计时间(以毫秒为单位):
最短 = 0ms,最长 = 0ms,平均 = 0ms
注意,静态IP要使用保留的私有地址空间的IP。这些 IP 不会被公网访问到。
遇到的问题
设置静态IP后运行vagrant up曾遇到过如下错误。
$ vagrant up
Bringing machine 'default' up with 'virtualbox' provider...
==> default: Checking if box 'bento/centos-7.2' is up to date...
==> default: Clearing any previously set network interfaces...
There was an error while executing VBoxManage, a CLI used by Vagrant
for controlling VirtualBox. The command and stderr is shown below.
Command: ["hostonlyif", "create"]
Stderr: 0%...
Progress state: E_FAIL
VBoxManage.exe: error: Failed to create the host-only adapter
VBoxManage.exe: error: Querying NetCfgInstanceId failed (0x00000002)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component HostNetworkInterfaceWrap, interface IHostNetworkInterface
VBoxManage.exe: error: Context: "enum RTEXITCODE __cdecl handleCreate(struct HandlerArg *)" at line 94 of file VBoxManageHostonly.cpp
我的解决方法是重装virtualbox,原因不明。
virtualbox版本:6.1.28
vagrant版本:2.2.18