当需要给容器分配指定 ip ,为避免ip 冲突,指定容器子网处理
- 创建
subnet
子网
docker network create --subnet 10.0.0.0/24 --gateway 10.0.0.1 subnet-testdocker network ls
NETWORK ID NAME DRIVER SCOPE
...
f582ecf297bc subnet-test bridge local
- 给
busybox
容器指定子网
docker run -d --name busybox --net=subnet-test -it busybox:latest sleep infinitedocker network inspect subnet-test
[{"Name": "subnet-test","Id": "f582ecf297bc589ef16e598c0fc2f0c5e69853d6741e63ccb2f49668aafb26c8","Created": "2024-03-09T15:35:39.639503096+08:00","Scope": "local","Driver": "bridge","EnableIPv6": false,"IPAM": {"Driver": "default","Options": {},"Config": [{"Subnet": "10.0.0.0/24","Gateway": "10.0.0.1"}]},"Internal": false,"Attachable": false,"Ingress": false,"ConfigFrom": {"Network": ""},"ConfigOnly": false,"Containers": {"42d36208b6f4f8d6dce04b8686407ec1162cf0f678a42db9b29ffe325993a7d8": {"Name": "busybox","EndpointID": "df945142982aa559fc9094d22fdcdf4a6fb04c141db61070cdda202d90615ce0","MacAddress": "02:42:0a:00:00:02","IPv4Address": "10.0.0.2/24","IPv6Address": ""}},"Options": {},"Labels": {}}
]
- 给容器指定 ip
docker run -d --name busybox-01 --net subnet-test --ip 10.0.0.5 -it busybox:latest sleep infinite
- 断开容器网络
docker network disconnect subnet-test busybox-01
- 恢复容器网络
docker network connect subnet-test busybox-01
注意:busybox-01 ip 变为了:10.0.0.3
- 恢复容器网络并指定 ip
docker network connect --ip 10.0.0.5 subnet-test busybox-01
- 获取容器 ip
docker inspect --format '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' busybox-01
10.0.0.5