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

  1. Create a network: docker network create mynet.
  2. Start containers with --network mynet.
  3. Use container names as hostnames in application connection strings.
  4. 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 --link flag; use custom networks instead.
  • Multiple networks can be attached to a single container for layered isolation.
  • Use --network-alias to 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.