Port forwarding (also called port mapping) in Docker allows you to make a service running inside a container accessible from outside the container by linking a port on your host machine to a port inside the container. This is essential because containers are isolated by default and do not expose their services to the outside world unless you explicitly map their ports.
List all running containers with their port mappings
docker ps
CONTAINER ID IMAGE ... PORTS
b650456536c7 busybox ... 0.0.0.0:1234->9876/tcp, 0.0.0.0:4321->7890/tcp
Show all mapped ports for a specific container
docker port <container_name_or_id>
docker port b650456536c7
9876/tcp -> 0.0.0.0:1234
7890/tcp -> 0.0.0.0:4321
List all containers with their ports in a table
docker container ls --format "table {{.ID}}\t{{.Names}}\t{{.Ports}}"
How Port Forwarding Works
Host Port
: The port on your local machine (host) that you want to use to access the service.
Container Por
t: The port inside the container where the application is listening.
When you use port forwarding, Docker listens on the specified host port and forwards traffic to the specified container port.
docker run -p <host_port>:<container_port> <image_name>
Examples
- Simple Web Server Example Suppose you have a web server running on port 80 inside the container, and you want to access it on port 8080 on your host:
docker run -p 8080:80 nginx
Access the web server at http://localhost:8080 on your host.
- Mapping Multiple Ports If your container needs to expose multiple ports (e.g., HTTP and HTTPS):
docker run -p 8080:80 -p 8443:443 my_web_server
Maps host port 8080 to container port 80 (HTTP).
Maps host port 8443 to container port 443 (HTTPS).
- Let Docker Choose the Host Port If you don’t care which host port is used, let Docker pick one:
docker run -p 80 nginx
Docker will assign a random available host port to container port 80. Check the mapping with docker ps.
- Mapping a Range of Ports You can map a range of ports if your application needs several:
docker run -p 7000-7010:7000-7010 my_app
Maps host ports 7000–7010 to container ports 7000–7010.
- Mapping to a Specific Host Interface To restrict access to localhost only (not accessible from other machines):
docker run -p 127.0.0.1:8080:80 nginx
Only connections from the local machine can access the service.
- Using Docker Compose In docker-compose.yml:
services:
web:
image: nginx
ports:
- "8080:80"
This maps host port 8080 to container port 80 for the web service.
Top comments (0)