Incus网络配置指北

我是来结束这个教程的!

Incus与Macvtap

什么是Macvtap?自己查,总之就是快速将虚拟机/容器暴露给主机所在的网络的功能。

需要注意,Macvtap能实现与局域网内其他主机的通信,但唯独不能实现与主机的通信!如果有和主机通信的需要,建议为虚拟机配置一块额外的网卡,或使用传统的Bridge网络。

1
2
3
4
5
6
7
8
9
10
11
# 创建一个配置文件
# macvlan-enp4s0是配置文件名称
# eth0是虚拟机中这个macvtap网卡的名称
# enp4s0是想要连接到的主机网卡名称
incus profile device add macvlan-enp4s0 eth0 nic nictype=macvlan parent=enp4s0

# 以该配置创建一个新容器
incus init images:debian/12 my-debian --profile default --profile macvlan-enp4s0

# 或是为虚拟机设置配置文件
incus profile add my-debian macvtap-enp4s0

Incus端口发布

在Docker中,我们可能已经习惯了采用-p 10086:80这样的命令,将容器的一个端口映射到主机上另一个端口。

这一目标在Incus中,需要借助Proxy这一设备类型实现,不过会稍显复杂。

Network Forward转发与Proxy有什么区别?

参考:Difference between network forward and proxy device

The proxy device is instance specific and can forward connections in either direction, between protocols, and when operating in non Nat mode doesn’t require a network connection between host and instance.

A forward on the other hand is more like a proxy device operating in Nat mode. But its defined at the network level rather than instance level and allows sharing an ip between multiple instances because it can forward different ports to different ips.

首先,如果是绑定到普通用户默认Project的容器实例,我们要先解除该Project禁止设置Proxy设备的限制。

1
sudo incus project edit user-1000

是的,sudo,除非账户在incus-admin用户组里,否则请用sudo

config下添加一行:

1
2
3
config:
# ......
restricted.devices.proxy: allow

保存。现在我们就可以向容器示例添加proxy设备了。

假设在容器my-http里,有一个Nginx正在监听80端口,我们现在希望将容器的80端口映射到主机的10086端口,以实现访问主机的10086端口,就能访问到容器的80端口。那么,命令如下:

1
incus config device add my-http port10086to80 proxy connect="tcp:127.0.0.1:80" listen="tcp:0.0.0.0:10086"

完成以后,可以在主机运行curl http://127.0.0.1:10086命令,查看绑定是否成功。

如果计划使用反向代理将外部的请求转发到容器,同时禁止外部网络直接通过访问端口号访问到容器内服务,那么可以将最后的listen字段中IP,改成127.0.0.1