6.3.2 Container Port Publishing
A focused guide to Container Port Publishing, connecting core concepts with practical Docker and container operations.
Container port publishing is the act of explicitly mapping a container's internal port to a port on the host machine, using the -p flag at run time, making a service running inside the container reachable from outside it.
Basic Port Publishing
The -p flag specifies a host port and a container port, connecting the two.
docker run -d -p 8080:80 nginx:alpine
This makes the container's internal port 80 (where nginx listens by default) reachable on the host at port 8080.
Publishing to a Specific Host Interface
By default, a published port is reachable on all of the host's network interfaces; this can be restricted to a specific interface if needed.
docker run -d -p 127.0.0.1:8080:80 nginx:alpine
This makes the port reachable only via the host's loopback interface, not from other machines on the network.
Publishing Multiple Ports
Several ports can be published in a single command, each with its own mapping.
docker run -d -p 8080:80 -p 8443:443 myapp:1.0
Letting Docker Choose an Available Host Port
Specifying only the container port, without a corresponding host port, lets Docker automatically assign an available host port.
docker run -d -p 80 nginx:alpine
docker port $(docker ps -lq)
The second command reveals exactly which host port was automatically assigned.
Why Container Port Publishing Matters
Port publishing is the fundamental mechanism that makes a containerized service actually reachable from outside its own isolated network namespace, making it an essential, everyday part of running any container that needs to serve external traffic.