docker-compose defines a bridge network and configures an IP address pool for the network
If you want to define a bridge network in Docker Compose and configure an IP address pool for the network so that the service automatically assigns IP addresses from it,
You can follow the steps below
- Define the network and specify a subnet range.
- Set the gateway address.
- Enable the function of automatically assigning IP addresses.
Here is an exampleFile, showing how to define a bridged network containing an IP address pool:
version: '3.9' services: web: image: nginx:latest networks: - my-bridge-network db: image: postgres:latest networks: - my-bridge-network networks: my-bridge-network: driver: bridge ipam: config: - subnet: 172.20.0.0/16 gateway: 172.20.0.1
explain
Network definition (networks
):
-
my-bridge-network
: Define a namemy-bridge-network
bridge network. -
driver: bridge
: Specify that the network type is bridged. -
ipam
: Defines the IP address manager. -
config
: Configure subnet and gateway information.-
subnet
: Set the network subnet range, here is172.20.0.0/16
。 -
gateway
: Set the gateway address of the network, here is172.20.0.1
。
-
Service definition (services
):
-
web
: Use Nginx mirroring. -
db
: Use Postgres mirroring. -
networks
: Every service has been addedmy-bridge-network
network.
When Docker Compose starts a service, it automatically assigns an unused IP address to each service from the defined subnet range.
This means that the service will get a dynamically assigned IP address, rather than a fixed IP address.
Things to note
- Make sure that the IP address assigned to the service is within the defined subnet range.
- If you need more services or different subnets, please extend the configuration accordingly.
- When the service starts, Docker Compose automatically selects the available IP address from the defined subnet to assign to the service.
- Make sure that the selected subnet does not overlap with the existing network to avoid conflict.
Summarize
The above is personal experience. I hope you can give you a reference and I hope you can support me more.