How to Map Port in Docker: Simple Guide with Examples
To map a port in Docker, use the
-p option with docker run like -p hostPort:containerPort. This connects a port on your computer to a port inside the container, allowing access to container services from outside.Syntax
The basic syntax to map ports in Docker is:
docker run -p hostPort:containerPort imageName
Here, hostPort is the port on your computer, and containerPort is the port inside the Docker container.
bash
docker run -p 8080:80 nginx
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
a1b2c3d4e5f6g7h8i9j0
# Container runs in detached mode with port 8080 mapped to 80
Common Pitfalls
Common mistakes when mapping ports include:
- Using the same
hostPortfor multiple containers causes conflicts. - Forgetting to expose the correct
containerPortinside the container. - Not using
-pbut onlyEXPOSEin Dockerfile, which does not publish ports to the host.
Always check if the host port is free and correctly map ports to avoid access issues.
bash
docker run -p 80:80 nginx # This may fail if port 80 is already used on host docker run -p 8080:80 nginx # Correct way if port 80 is busy on host
Quick Reference
| Option | Description | Example |
|---|---|---|
| -p hostPort:containerPort | Maps host port to container port | -p 8080:80 |
| -d | Runs container in background (detached) | -d |
| EXPOSE port | Declares port inside Dockerfile (not published) | EXPOSE 80 |
Key Takeaways
Use
-p hostPort:containerPort with docker run to map ports.Host port must be free and not used by other services or containers.
EXPOSE in Dockerfile only documents ports; it does not publish them to host.
Use different host ports to run multiple containers simultaneously.
Check container logs or browser to verify port mapping works.