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)