In Docker Compose, you can assign static IP addresses to your containers within a custom network. This ensures consistent communication between services, especially when specific IP addresses are required. Docker Compose Network
💡 Tip:
Use a unique subnet (e.g., 172.99.0.0/24) to avoid conflicts with existing networks. Verify active Docker networks by running:
Terminal window
dockernetworkls
Example with Static IPs
version: '3.9'
services:
app:
image: your-app-image
container_name: app_service
...
networks:
example_network:
ipv4_address: 172.99.0.10
db:
image: your-db-image
container_name: db_service
...
networks:
example_network:
ipv4_address: 172.99.0.2
nginx:
image: nginx:latest
container_name: nginx_service
...
networks:
example_network:
ipv4_address: 172.99.0.3
networks:
example_network:
driver: bridge
ipam:
config:
- subnet: 172.99.0.0/24
external: false
Inspect the created network to verify assignments:
Terminal window
dockernetworkinspectexample_network
Set Multiple Subnets
Defining multiple subnets in a single Docker network allows you to:
1. Separate groups of services (e.g., databases in one subnet, caches in another).
2. Use different routing or gateways for different traffic flows.
3. Allocate different IP address spaces for legacy services vs dynamic ones.
version: '3.9'
services:
app:
image: your-app
networks:
example_network:
ipv4_address: 172.99.0.10
cache:
image: redis:7
networks:
example_network:
ipv4_address: 172.99.1.5
networks:
example_network:
driver: bridge
ipam:
config:
- subnet: 172.99.0.0/24
- subnet: 172.99.1.0/24
Set IP Range
What it is / When to use?
The ip_range option restricts the pool of IP addresses Docker can dynamically assign within a subnet.
This is useful when:
1. You want to reserve a portion of the subnet for static IP assignments.
2. You need stricter control over which addresses Docker is allowed to allocate.
3. You’re mixing static and dynamic IPs in the same subnet.
version: '3.9'
services:
app1:
image: your-app
networks:
example_network: {}
app2:
image: your-app
networks:
example_network: {}
db:
image: postgres:16
networks:
example_network:
ipv4_address: 172.99.0.5# static, outside the dynamic range
networks:
example_network:
driver: bridge
ipam:
config:
- subnet: 172.99.0.0/24
ip_range: 172.99.0.128/25
Add Healthcheck to Service
Ensure containers are only marked as healthy when their core functionality is available and responsive.