Port Mapping
πͺ Docker Port Mapping = Connecting Your App to the Outside World
π‘ Think of a Docker container like a house π and ports as doors πͺ.
You need to open a door in the container AND connect it to your host so people can visit. π§βπ»π
π― Syntax
docker run -p <hostPort>:<containerPort> <image>
| Element | Description | Emoji Analogy |
|---|---|---|
hostPort |
Port on your local machine (PC) | π§βπ» Door outside the house |
containerPort |
Port inside the Docker container | π Door inside the house |
β Common Examples
1. π Same port inside & outside
docker run -p 3000:3000 my-app
- App runs on port 3000 in container.
- Accessible at
http://localhost:3000on host.
π§ You "opened the same door" on both sides.
2. π Different ports (host vs container)
docker run -p 8080:3000 my-app
- App runs on port 3000 inside.
- Accessible at
http://localhost:8080outside.
π§ You redirected visitors from door 8080 to 3000 inside.
3. π’ Multiple ports
docker run -p 8000:8000 -p 5000:5000 my-app
Multiple doors open π for frontend/backend or API/UI separation.
4. π Binding to specific IP (advanced)
docker run -p 127.0.0.1:8080:80 nginx
- Only accessible from localhost, not from other devices.
π§ͺ Testing Port Mappings
| Test Method | Example Command | Purpose |
|---|---|---|
| π Web Browser | http://localhost:8080 |
Access frontend/backend |
π§ͺ curl CLI Tool |
curl localhost:8080 |
API/health check |
| π Docker Inspect | docker container inspect <id> |
See exposed ports inside |
| π¦ Docker PS | docker ps |
Shows active port mappings |
β Common Pitfalls & Fixes
| Problem | Cause | Fix |
|---|---|---|
| β Cannot access app on browser | You forgot -p
|
Always map with -p! |
| π Firewall blocking access | System-level rules | Allow port in your firewall |
| π« Conflicting ports | Same host port already in use | Change host port (e.g., -p 8081:3000) |
π Bonus Tip: EXPOSE in Dockerfile
EXPOSE 3000
π This is for documentation only! It does not publish the port β you still need -p during docker run.
π§ Quick Reference Table
| CLI Option | Meaning | Example |
|---|---|---|
-p 8080:80 |
Host port 8080 β Container port 80 |
localhost:8080 opens NGINX |
-p 127.0.0.1:8000:8000 |
Bind to specific host IP | Secure dev testing |
EXPOSE in Dockerfile |
Internal doc (not binding) | Use for image readability |
π§ Final Analogy: Port Mapping = Mail Forwarding π¬
Imagine:
- π Container address = Internal port (e.g. 3000)
- π§βπ» Public address = Host port (e.g. 8080)
- π Port mapping forwards public requests to the container, like mail forwarding!
β Summary
| Step | What to Do |
|---|---|
| 1οΈβ£ | Decide which port your app runs on inside the container |
| 2οΈβ£ | Map it using -p hostPort:containerPort
|
| 3οΈβ£ | Access it via localhost:hostPort
|
| 4οΈβ£ | Check with docker ps to confirm mapping |
Top comments (0)