Custom Networks
We can create custom bridge networks so that containers can communicate with each other, but still remain isolated from the outside host network.
This is a very common setup in backend architecture: The load balancer is exposed to the public internet, but the application servers are placed on an internal network and are only accessible via the load balancer.
Creating a Bridge Network
Let’s create a custom network called caddytest:
docker network create caddytest
You can verify it was created by listing your networks:
docker network ls
Internal DNS Resolution
When you place containers on the same custom bridge network and give them names, Docker automatically sets up internal DNS resolution. The container names will resolve to the individual containers.
-
Spin up the application servers on the
caddytestnetwork. Note that we do not use-pto expose ports, as we want them hidden from the host machine:docker run -d --name caddy1 --network caddytest -v $PWD/index1.html:/usr/share/caddy/index.html caddy docker run -d --name caddy2 --network caddytest -v $PWD/index2.html:/usr/share/caddy/index.html caddy -
Start a shell session in a new container on the same network to test connectivity:
docker run -it --network caddytest docker/getting-started /bin/sh -
From within that shell, use
curlto reach the servers by their container names:curl caddy1 # (Outputs the HTML for server 1) curl caddy2 # (Outputs the HTML for server 2)
This proves that containers on the same network can communicate with each other using their names!