SkillSprout
Chapter 1 · Lesson 12
Intermediate
2 min read

Container Communication and Port Mapping

Overview

A port is a numbered communication endpoint used by a process. A container has its own network interface and can listen on ports inside its private network. A host port may be mapped to a container port so clients outside Docker can reach it.

Containers on the same user-defined bridge network can discover one another by container name. Docker provides DNS for the network. Names are more reliable than IP addresses because container IP addresses can change.

Detailed Notes

Create a network

bash
docker network create my-network
docker network ls

Run two containers:

bash
docker run -d --name backend --network my-network nginx
docker run -d --name frontend --network my-network nginx

Because both use my-network, frontend can reach backend with http://backend. Docker DNS resolves backend to its current container IP.

Test from a container:

bash
docker run --rm --network my-network curlimages/curl:8.10.1 curl http://backend

This starts a temporary curl container on the network and removes it after the command exits.

Port mapping

text
Browser -> localhost:8080 -> Docker host -> container:80

Container-to-container traffic can use container ports directly and does not require publishing those ports with -p.

Troubleshooting

bash
docker network inspect my-network
docker inspect backend
docker logs backend
docker exec backend sh -c "wget -qO- http://frontend"

Check the network names, listening port, process status and firewall rules when communication fails.

Bridge network communication
Architecture
frontendname: frontendbackendname: backendPostgreSQLport 5432http://backend
Key point. Frontend sends a request using the backend name.

Containers on one network can resolve names and communicate directly.

Common Interview Questions

Finished this lesson?

0 of 27 lessons done · 0% of the course