How to Use docker run -p to Map Ports Easily
Use
docker run -p hostPort:containerPort to map a port from your computer (host) to the Docker container. This lets you access services inside the container through your computer's port.Syntax
The -p option in docker run maps a port on your host machine to a port inside the container.
Format:
-p hostPort:containerPort- Maps a specific port on your computer to a port inside the container.hostPort- The port number on your computer.containerPort- The port number inside the container where the app listens.
bash
docker run -p <hostPort>:<containerPort> <image-name>
Example
This example runs an Nginx web server container and maps port 8080 on your computer to port 80 inside the container. You can then open http://localhost:8080 in your browser to see the Nginx welcome page.
bash
docker run -d -p 8080:80 nginx
Output
Unable to find image 'nginx:latest' locally
latest: Pulling from library/nginx
...
Digest: sha256:...
Status: Downloaded newer image for nginx:latest
<container_id>
Common Pitfalls
1. Port conflicts: If the host port is already in use by another app, Docker will fail to start the container.
2. Forgetting to map ports: Without -p, the container ports are isolated and not accessible from your host.
3. Using the same port on host and container: This is common but you can map different ports if needed.
bash
docker run -p 80:80 nginx # May fail if port 80 is busy docker run -p 8080:80 nginx # Maps host 8080 to container 80, avoids conflict
Quick Reference
| Option | Description | Example |
|---|---|---|
| -p hostPort:containerPort | Map host port to container port | -p 8080:80 |
| -p 5000:5000 | Map port 5000 on host to 5000 in container | docker run -p 5000:5000 myapp |
| -p 80:80 | Map port 80 on host to 80 in container | docker run -p 80:80 nginx |
Key Takeaways
Use
-p hostPort:containerPort to connect container ports to your computer.Make sure the host port is free before mapping to avoid conflicts.
Without
-p, container ports are not accessible from your host.You can map different host and container ports if needed.
Check your container logs if the port mapping does not work as expected.