Assigning Specific Subnets to Docker Containers via Compose
When using docker-compose, containers may encounter IP conflicts with the host's internal network, particularly if both use similar address renges like 192.x.x.x. To avoid such issues, you can define custom subnets for container networks in your YAML configuration.
In the example below, a custom bridge network is created with a specific subnet (172.28.0.0/16) to ensure no overlap with the host’s network:
version: '3.9'
services:
coredns:
image: coredns/coredns:1.10.0
container_name: coredns
ports:
- 53:53/udp
networks:
mynetwork:
ipv4_address: 172.28.0.4
volumes:
- ./coredns/hostsfile:/etc/coredns/hostsfile
- ./coredns/Corefile:/Corefile
networks:
mynetwork:
driver: bridge
ipam:
driver: default
config:
- subnet: 172.28.0.0/16
gateway: 172.28.0.1
Another example demonstrates assigning an explicit IP address within a defined subnet:
version: '3'
services:
myservice:
image: <image>
networks:
mynetwork:
ipv4_address: 192.168.0.2
networks:
mynetwork:
driver: bridge
ipam:
config:
- subnet: 192.168.0.0/16
Creating Custom Networks with Specific Subnets
To assign a particular subnet when running containers manually, first create a custom network:
docker network create --subnet=172.18.0.0/16 shadownet
Then launch a container using that network:
docker run --net shadownet -p 6008:6008 registry.cn-hangzhou.aliyuncs.com/fastgpt_docker/m3e-large-api
Inspect the container to confirm it received an IP from the specified subnet:
docker inspect <container_id>
Using Comppose with Custom Subnets
The same network setup can be expressed in a docker-compose.yml file:
version: '3'
services:
myservice:
image: registry.cn-hangzhou.aliyuncs.com/fastgpt_docker/m3e-large-api
ports:
- 6008:6008
networks:
- shadownet
networks:
shadownet:
driver: bridge
ipam:
config:
- subnet: 172.18.0.0/16
Before running this configurasion, remove any conflicting networks:
docker network rm shadownet
Launch the stack using:
docker-compose -f /path/to/subnet.yml up
Disabling Auto-Restart for Docker Containers
To prevent a container from restarting automatically, modify its restart policy:
docker update --restart=no <container_name_or_id>
Verify the change:
docker inspect -f '{{.HostConfig.RestartPolicy.Name}}' <container_name_or_id>