Docker:为两个容器创建网络的正确方式及静态IP配置方法
Great question! When you want more control over the IP addressing of your Docker containers (instead of letting Docker auto-assign everything), specifying a custom subnet and static IPs is straightforward with custom networks. Here's how to do it properly:
1. Create a Custom Network with a Defined Subnet
First, when creating your custom network, use the --subnet flag to define your desired IP range. You can also optionally set a gateway with --gateway if you need to override the default one Docker would pick.
For example, let's create a network with a subnet 192.168.50.0/24 and gateway 192.168.50.1:
docker network create --subnet=192.168.50.0/24 --gateway=192.168.50.1 my_network
2. Assign Static IPs to Containers on the Network
When launching your containers, use the --ip flag to specify a static IP address that falls within the subnet you defined. Make sure the IP isn't already in use (by the gateway or another container) and is within the subnet's range.
Example for container1:
docker run --name container1 --network my_network --ip=192.168.50.10 -d iamsecret -p 1234:1234
Example for container2:
docker run --name container2 --network my_network --ip=192.168.50.20 -d iamawebserver -p 80:80
3. Verify the Setup
To confirm everything worked, you can inspect the network to see all connected containers and their IPs:
docker network inspect my_network
Or check a specific container's IP directly:
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container1
Key Notes:
- Static IPs must be within the subnet you defined when creating the network. If you pick an IP outside this range, Docker will throw an error.
- This only works with custom bridge networks (the kind you create with
docker network create). The defaultbridgenetwork doesn't support static IP assignment this way. - Once assigned, the static IP will persist across container restarts, which is useful for services that rely on consistent addressing.
内容的提问来源于stack exchange,提问作者JoeSlav

