How can two Docker containers talk to each other?
Put them on the same user-defined network and call one from the other using its container or service name and the container port. Publishing a port with -p is only needed for access from the host.
Explain it simply
Two friends in the same WhatsApp group can message each other directly. Friends in different groups cannot, unless someone adds them. The Docker network is the group, and the container name is the contact name.
Create a network, attach both containers to it, and use the name and the port the app listens on inside the container. No -p needed between containers; -p exists to let outsiders, such as your browser, in. In Compose, services share a default network automatically, so the api can call http://db:5432 with no extra setup.
If containers are on different networks, they cannot reach each other until you connect one to both with docker network connect.
Example
docker network create app-net
docker run -d --name cache --network app-net redis:7
docker run --rm --network app-net redis:7 redis-cli -h cache ping
# PONGWhat to say in the interview
"I attach both containers to one user-defined network and use the target container's name and internal port. Publishing ports is for host access only. In Compose this works by default using service names."
Common mistakes
- Using the host-published port number between containers instead of the container port.