马春杰杰 Exit Reader Mode

全流程:Linux系统安装LXD容器,并利用宿主机的网卡配置单网卡双IP

我们想要的就是让 LXD 容器通过宿主机的物理网卡(而不是默认的 lxdbr0 NAT 桥)直接接入局域网,这样容器可以获得和宿主机同网段的 IP 地址,并且支持单网卡双IP(动态+静态)

实现方式就是基于宿主机网卡创建 LXD 网桥,然后把容器绑定到这个桥,这里LXD的版本是5.21.0

1、安装LXD容器

sudo apt install snapd -y
sudo snap install lxd --channel=5.21/stable
sudo usermod -aG lxd $USER

2、配置宿主机网卡

主要是创建br0网桥,以netplan模式举例,打开以下文件:

sudo vi /etc/netplan/01-network-manager-all.yaml

填入:

network:
  version: 2
  renderer: networkd
  ethernets:
    enp109s0:
      dhcp4: no
  bridges:
    br0:
      interfaces: [enp109s0]
      dhcp4: true
      parameters:
        stp: false
        forward-delay: 0

注意,这里的网卡enp109s0根据自己电脑的网卡名字确定,别选错了。保存之后,依次进行下面的操作:

sudo chmod 600 /etc/netplan/01-network-manager-all.yaml
sudo systemctl enable systemd-networkd
sudo systemctl start systemd-networkd
sudo systemctl enable systemd-resolved
sudo systemctl start systemd-resolved
sudo netplan generate
sudo netplan apply # 注意,这一步之后有可能动态IP会变

到这里,宿主机的网络配置就好了,可以看下IP,此时这台电脑的IP出口已经由br0管理了。

3、创建LXD容器

先创建一个存储池:lxc storage create vpms-pool dir source=/lxd-pool

然后进行LXD容器初始化:lxd init,按下面的选项即可:

Would you like to use LXD clustering? (yes/no) [default=no]:
Do you want to configure a new storage pool? (yes/no) [default=yes]: no
Would you like to connect to a MAAS server? (yes/no) [default=no]:
Would you like to create a new local network bridge? (yes/no) [default=yes]: no
Would you like to configure LXD to use an existing bridge or host interface? (yes/no) [default=no]: yes
Name of the existing bridge or host interface: br0
Would you like the LXD server to be available over the network? (yes/no) [default=no]: yes
Address to bind LXD to (not including port) [default=all]:
Port to bind LXD to [default=8443]:
Would you like stale cached images to be updated automatically? (yes/no) [default=yes]:
Would you like a YAML "lxd init" preseed to be printed? (yes/no) [default=no]: yes
config:
  core.https_address: '[::]:8443'
networks: []
storage_pools: []
storage_volumes: []
profiles:
- config: {}
  description: ""
  devices:
    eth0:
      name: eth0
      nictype: bridged
      parent: br0
      type: nic
  name: default
projects: []
cluster: null

lxc profile device add default root disk path=/ pool=vpms-pool
lxc launch ubuntu:22.04

4、配置容器网络

lxc exec large-pheasant bash
vi /etc/netplan/50-cloud-init.yaml

填入:

network:
  version: 2
  ethernets:
    eth0:
      dhcp4: true
      addresses:
        - 192.168.1.200/24
      nameservers:
        addresses:
          - 114.114.114.114
          - 119.29.29.29

注意其中的静态IP根据本地环境设置~

到这里,所有配置都好了,只需要重启容器:lxc restart large-pheasant 就可以看到两个IP了,而且跟宿主机是同网段的,同网段下面的机器都可以ping通。

注:

如果在此之前已经lxd init进行网桥的设置了,此时默认一般是lxdbr0,绑定的是eth0,此时我们可以手动指定eth1br0

lxc config device add autodl eth1 nic nictype=bridged parent=br0 name=eth1