🎓 A1Learner
🔍
0 of 50 lessons completed

Connect Two Containers

Two containers connect by joining one user-defined network and calling each other by name. No IP address is needed, and no port is published to the host.

Create the network

This command creates a network for the two containers.

docker network create g5-net

Fetch by name

curl inside one container reaches the other by name.

docker exec g5-client sh -c "wget -qO- http://g5-web/ | head -1"

Example

docker network create g5-net
docker run -d --name g5-web --network g5-net nginx:1.27-alpine >/dev/null
docker run -d --name g5-client --network g5-net alpine:3.20 sleep 600 >/dev/null
docker exec g5-client sh -c "wget -qO- http://g5-web/ | head -3"

Key points

  • Create a network with docker network create.
  • Join it with --network when the containers start.
  • Call the other container by its name, like a host name.
  • Use curl inside one container to fetch a page from the other.
  • The containers stay apart from the host. No -p flag is needed.

In this example, nginx and a client join one network. The client fetches the welcome page from g5-web by name. The page proves the containers reach each other by name, with no host port involved.

Note

A container name on the network is its address. Rename the container, and the address changes.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Rust Playground

Exercise

How does one container reach another on the same network?