Docker IPv6

最近在支持 IPv6 的 VPS 上面部署了一些 docker 应用,需要容器内的应用访问外部的 IPv6 地址,结果并不如我所想的那样简单,docker 仍需一些配置才可以。

计算 IPv6 网段

首先确定自己服务器的 IPv6 地址、后缀的大小,划分两个或两个以上的网段。
例如服务器的 IPv6 地址的网段为 fd00::/64,则可以划分 [fd00::/66] [fd00:0:0:4000::/66] [fd00:0:0:8000::/66] [fd00:0:0:c000::/66] 四个子网,具体可以使用 这个页面 来计算网段。

IPv6 配置

/etc/docker/daemon.json文件中添加以下配置项,若文件不存在则需要新建:

{
  "ipv6": true,
  "fixed-cidr-v6": "fd00::/66"
}

其中 IPv6 地址可以使用划分的第一个网段。
再重启 docker 服务:

sudo systemctl restart docker

配置 ip6tables

若系统中启用了 firewalld 则需要先禁用:

sudo systemctl disable firewalld
sudo systemctl stop firewalld

若未安装 iptables,则:

sudo yum install iptables-services -y

启用 iptables 与 ip6tables:

sudo systemctl enable --now iptables
sudo systemctl enable --now ip6tables

添加 IPv6 转发配置:

sudo ip6tables -t nat -I POSTROUTING -j MASQUERADE
sudo service ip6tables save

此时,docker 环境已配置完毕。

使 docker-compose 支持

若想使在 docker-compose.yml 文件中添加的容器支持 IPv6,则需要配置自定义网络:

services:
        web:
                container_name: busybox
                image: busybox
                restart: always
                command: tail -f /dev/null
                networks:
                        - apps

networks:
        apps:
                enable_ipv6: true
                driver: bridge
                ipam:
                        driver: default
                        config:
                                - subnet: 172.16.99.0/24
                                  gateway: 172.16.99.1
                                - subnet: fd00:0:0:4000::/66
                                  gateway: fd00:0:0:4000::1

其中 IPv6 地址可以使用划分的第二个网段或者第三第四个网段。
如此使用 docker-compose 创建的容器便可以使用 IPv6 了。

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注