Docker · Containers in practice

How does port mapping work in Docker?

EasyportsnetworkingexposureUpdated Oct 2026
Quiz this track

Short answer

Publishing with -p maps a host port to a container port through the host's NAT rules. EXPOSE only documents intent and does not make the port reachable.

A container has its own network namespace, so a process listening on port 3000 is not reachable from the host until the port is published. The syntax is hostPort:containerPort, and Docker installs forwarding rules to send traffic to the container IP.

sh
docker run -d -p 8080:3000 api:1.0.0
docker run -d -p 127.0.0.1:8080:3000 api:1.0.0
docker port api-1
The second form binds only to loopback, so the service is not exposed on every interface.

What to watch

  • Publishing on 0.0.0.0 exposes the port on all host interfaces
  • Bind to 127.0.0.1 when only a local proxy should reach the container
  • Port collisions fail at start time, not at build time
  • Docker can allocate a random host port when you publish only the container port

In a cluster, publishing host ports is usually replaced by a service or ingress abstraction. Direct host port mapping limits you to one instance per port per node and complicates scheduling.

EXPOSE 3000 in a Dockerfile is metadata for humans and tooling. It does not publish the port, and omitting it does not prevent -p from working.

Follow-ups you should expect

Interviewers use these to check whether the first answer was understanding or memorisation.

  1. 1What is the difference between EXPOSE and -p?
  2. 2Why might you bind a published port to 127.0.0.1?
  3. 3What happens if two containers publish the same host port?
  4. 4How does port publishing differ in Kubernetes?

Say it in the interview

Publishing a port with -p maps a host port to a container port using the host's forwarding rules. EXPOSE is only documentation, so it does not make anything reachable. I bind to 127.0.0.1 when a local reverse proxy should be the only entry point, and in a cluster I usually avoid host ports and use a service or ingress instead.

Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.

Related questions

Reading is step one

Now say it out loud.

Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Docker mock interview and get scored feedback on depth, clarity and confidence.