Docker容器网络更改

6kGfRc

最近踩了一个坑,阿里云通过云企业网(腾讯云叫云联网)专线网关接入腾讯云,实现多云内网互联,本来这是个很普通的事情,腾云侧的IP段是172.16.19.9/20,阿里云侧网段是172.16.18.0/20,但是经测试双向网络无法互通,腾讯云侧在专线网关无法往下路由,阿里云侧压根就没跳出vpc网络,tracetoute发现网络在本地出不去了~最后排查发现是本地的Docker桥接网络IP段是172.16.19.0/16,跟腾讯侧的望断冲突突突突突了~,SO~就需要考虑如何在不停止Docker容器的情况下修改网络,观靡了一下Docker的文档,发现可以实现这个骚(普通)操作!过程如下:

1.更改网络

###解除容器绑定的网络 网络名词root_default 容器名称root_redis_1
[root@ecs-test-01 ~]# docker network disconnect root_default root_redis_1
##删除原先的网络
[root@ecs-test-01 ~]# docker network rm root_default
##重新创建容器网络
[root@ecs-test-01 ~]# docker network create --subnet=172.22.16.0/24 root_default
7d40e0be1fcade91f8109a54a05bf0f012584e0bbb9449bec5335db247efd0be
##为容器重新指定网络
[root@ecs-test-01 ~]# docker network connect root_default root_redis_1
##重新启动容器
[root@ecs-test-01 ~]# docker container restart root_redis_1

2.查看效果

# 查看容器信息
[root@ecs-test-01 ~]# docker inspect root_mysql_1

省略部分输出,内容如下:

"NetworkSettings": {
            "Bridge": "",
            "SandboxID": "91dccf255b8aa18584aa40d7295cb0f19da8a770628ab918cbb5fa53f9d8cb18",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "3306/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "3306"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/91dccf255b8a",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "",
            "Gateway": "",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "",
            "IPPrefixLen": 0,
            "IPv6Gateway": "",
            "MacAddress": "",
            "Networks": {
                "root_default": {
                    "IPAMConfig": {},
                    "Links": null,
                    "Aliases": [
                        "b0efc877eee7"
                    ],
                    "NetworkID": "99da51f11fb7c61e6638f9bd420ddd278e13e05b364b304413115f447c9ae582",
                    "EndpointID": "ba5d1d152d63f059c3ac61cdcf95e0c75ee2b826b2dd92fdb9c10a0a5fb6b246",
                    "Gateway": "172.22.16.1",
                    "IPAddress": "172.22.16.5",
                    "IPPrefixLen": 24,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:16:10:05",
                    "DriverOpts": {}
                }
            }
        }

再次测试云联网的网络,发现网络通了~搞定,打完收工!