You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Docker:为两个容器创建网络的正确方式及静态IP配置方法

How to Specify Subnet and Assign Static IPs in Docker Custom Networks

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 default bridge network 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:37:57