How to connect containers with user-defined networks?
· Category: Docker
Short answer
User-defined bridge networks provide automatic DNS resolution so containers can communicate using container names. They also isolate traffic from containers on other networks.
Steps
- Create a network:
docker network create mynet. - Start containers with
--network mynet. - Use container names as hostnames in application connection strings.
- Optionally use aliases for service discovery.
Example
docker network create appnet
docker run -d --name redis --network appnet redis:7
docker run -d --name web --network appnet -p 8080:8080 myapp
Inside the web container, connect to Redis using the hostname redis:
redis_client = redis.Redis(host='redis', port=6379)
Connect an existing container:
docker network connect appnet mycontainer
Tips
- Avoid the legacy
--linkflag; use custom networks instead. - Multiple networks can be attached to a single container for layered isolation.
- Use
--network-aliasto assign multiple resolvable names.
Common issues
- The default bridge network does not support DNS resolution between containers.
- Firewall rules on the host may block inter-container traffic.
- Container names must be unique within a network for DNS to resolve correctly.