Guide Docker Beginner

8. Networking and Ports

Distinguish host ports, container ports, and container-to-container networking.

1 min read

Publishing a Port

docker run -d --name docker-course-network-web -p 127.0.0.1:8082:80 nginx:alpine
docker port docker-course-network-web

The host listens on loopback port 8082 and forwards traffic to port 80 in the container. Open http://localhost:8082.

Container-to-Container Communication

Containers on a user-defined bridge network can resolve each other’s names:

docker network create docker-course-net
docker network connect docker-course-net docker-course-network-web
docker run --rm --network docker-course-net busybox:1.37 wget -qO- http://docker-course-network-web

The second container uses the server’s container port, 80, rather than host port 8082. Inside a container, localhost refers to that container’s own network namespace.

Cleanup

docker stop docker-course-network-web
docker rm docker-course-network-web
docker network rm docker-course-net

Practice

Explain why the browser uses localhost:8082 while the client container uses docker-course-network-web:80.

Quick Interview Answer

Publishing connects a host port to a container port. Containers on the same user-defined network can communicate through container names without publishing their ports to the host.

Reference: Docker port publishing.


Previous: 7. Build Context and Cache | Next: 9. Volumes and Bind Mounts

Add More Questions to This Guide

Know a question that should be here? Share it and help the community!

Open Google Form