How port mapping works
A containerized application listens on a port inside the container (the container port). To make that application reachable from outside the Docker host, Docker can publish a container port on a host port. When a host port is published, traffic arriving at the Docker host IP and that host port is forwarded into the container port. Two IPs to understand:- Container IP: Docker assigns an internal IP to each container. This IP is only reachable from the Docker host and other containers on the same Docker network. If you open a browser on the Docker host itself, you can use the container IP and container port to access the app.
- Docker host IP: When you publish a host port, clients outside the Docker host connect to the Docker host IP and the published host port; Docker forwards that traffic into the container.
Example: publish a web app on port 80
Suppose the app inside the container listens on container port 5000. To make it available on port 80 of the Docker host, run:Run multiple instances or different services
You can run multiple instances of the same image and publish each one to a different host port:Examples at a glance
Important behavior and best practices
By default, published host ports are bound to
0.0.0.0 on the Docker host, making them reachable on any network interface of the host. Use -p <host_ip>:<host_port>:<container_port> if you need to bind to a specific host IP.You cannot publish the same host port to multiple containers at the same time. Host ports must be unique. If a port is already in use on the host, Docker will fail to publish that port for a new container.
Quick reference
- Syntax:
-p <host_port>:<container_port> - To bind to a specific host IP:
-p <host_ip>:<host_port>:<container_port> - Container IPs are internal; publishing on the host lets external clients reach the container.
- Multiple container ports can be published to distinct host ports, but a single host port cannot be reused.