现象:
宿主机和docker内部能互相访问非常正常,但docker内部访问外部网络内网其中一个网段172.18.0.x则无法访问。
排查
由于docker是精简过的系统,需另外安装网络相关命令
首先更新apt-get,否则在apt-get install 命令时会报E: Unable to locate package xx错误
apt-get update
安装网络工具
apt-get install -y net-tools
安装ping和telnet
apt-get install -y iputils-ping
apt-get install -y telnet
查看本机ip和网关,可用ifconfig和hostname -i命令
ifconfig
eth0: flags=4163<UP,BROADCAST,RUNNING,MULTICAST> mtu 1500inet 172.18.1.2 netmask 255.255.255.0 broadcast 172.18.1.255ether 02:42:ac:14:01:02 txqueuelen 0 (Ethernet)RX packets 224 bytes 20754 (20.2 KiB)RX errors 0 dropped 0 overruns 0 frame 0TX packets 226 bytes 1617336 (1.5 MiB)TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0lo: flags=73<UP,LOOPBACK,RUNNING> mtu 65536inet 127.0.0.1 netmask 255.0.0.0loop txqueuelen 1000 (Local Loopback)RX packets 0 bytes 0 (0.0 B)RX errors 0 dropped 0 overruns 0 frame 0TX packets 0 bytes 0 (0.0 B)TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
果然ip为172.18.0.x,与现在外部内网其中一段Ip重复了,但是并没有看到网关,再在cmd里通过docker network命令确认一下
docker network ls
NETWORK ID NAME DRIVER SCOPE
f2d743a9d1d7 bridge bridge local
aa072983972b host host local
3689e62360ba none null local
0c92c70dfedd webcloudapi_default bridge local
然后查询该网络详细
docker network inspect webcloudapi_default
[{"Name": "webcloudapi_default","Id": "0c92c70dfeddaca8722c5278831f07cb1555be23fdc74b8536ad2017eeb4ca3e","Created": "2023-08-31T01:23:30.156696Z","Scope": "local","Driver": "bridge","EnableIPv6": false,"IPAM": {"Driver": "default","Options": null,"Config": [{"Subnet": "172.18.0.0/16","Gateway": "172.18.0.1"}]},"Internal": false,"Attachable": false,"Ingress": false,"ConfigFrom": {"Network": ""},"ConfigOnly": false,"Containers": {},"Options": {},"Labels": {"com.docker.compose.network": "default","com.docker.compose.project": "webcloudapi","com.docker.compose.version": "2.20.2"}}
]
看到ip和网关都为172.18.0.x的,这时候确认问题,可以着手调整了。
解决方案
通过docker compose在部署的时候更改默认ip和网关即可。
webapi-compose.yml
version: '3'
networks:test-net:ipam:config:- subnet: 172.20.1.0/24gateway: 172.20.1.1
services:webcloudapi:image: webcloudapicontainer_name: webcloudapihostname: webcloudapiports:- 20020:80restart: alwaysnetworks:test-net:ipv4_address: 172.20.1.2
重新运行部署此yml文件(注意,这个操作会将原容器更改过的内容,包括新下载的命令软件全部重置)
docker compose -p webcloudapi -f webapi-compose.yml up -d
这时候再用api-get重新按上述步骤下载网络相关命令查看,ip和网关都变成172.20.1.x网段了,说明设置成功,但ping 172.18.0.x仍然无法连通,奇怪,后来终于发现问题所在,是之前部署的docker network配置还存在导致的问题
docker network ls
NETWORK ID NAME DRIVER SCOPE
f2d743a9d1d7 bridge bridge local
aa072983972b host host local
3689e62360ba none null local
0c92c70dfedd webcloudapi_default bridge local
d0916e722225 webcloudapi_test-net bridge local
上面的webcloudapi_default是原来的,webcloudapi_test-net是新建的,因此只要删除原来的即可。
docker network rm webcloudapi_default
重启容器后,终于ping通了,至此问题解决。