Module 10 Lesson 2: External Access and Port Mapping
Bridge the gap between your container and the world. Learn the intricacies of port publishing, IP binding, and how to troubleshoot connectivity issues from outside the host.
Module 10 Lesson 2: External Access and Port Mapping
By default, everything in Docker stays in Docker. To make your app accessible to users, you have to "Publish" your ports. But there's more to it than just -p 80:80.
1. The Anatomy of a Port Map
docker run -p [Host_IP]:[Host_Port]:[Container_Port]
A. Simple Mapping
docker run -p 8080:80 nginx
- Listens on every network interface (WiFi, Ethernet, Localhost) on port 8080.
B. Specific IP Binding
docker run -p 127.0.0.1:8080:80 nginx
- Listens only on Localhost. This is a crucial security step if you want to test an app without exposing it to the whole office WiFi.
C. Random Host Port
docker run -p 80 nginx
- Docker will pick a random high-numbered port (e.g., 32768) on your host and map it to 80. (Use
docker psto see which one it picked).
2. Publishing All Exposed Ports (-P)
If a Dockerfile has multiple EXPOSE instructions (e.g., 80, 443, 8080), you can map them all to random ports at once:
docker run -P nginx
3. How Docker Changes your Firewall (IPTables)
This is a "Gotcha" for Linux users.
- When you map a port with
-p, Docker automatically adds a rule to your Linux firewall (iptables). - The Danger: These rules often bypass standard firewall tools like
ufw. Even if you think your firewall is closed, a-pcommand can open a hole to the internet.
4. Troubleshooting Connectivity
If you can't hit your app at localhost:8080:
- Is the app listening inside?:
docker exec my-app netstat -tuln. - Is the port mapped?:
docker port my-app. - Is the firewall blocking the host port?: Check
ufw statusor Windows Firewall settings. - Is it a container-to-container problem?: Remember that
localhostinside a container refers to the container, not your laptop!
Exercise: The Port Experiment
- Run three instances of
nginx, each mapped to a different host port:8081,8082, and8083. - Verify you can see all three in your browser.
- Stop all three.
- Now, run one instance using the Specific IP Binding for
127.0.0.1. - Try to visit the page using your computer's Local IP Address (e.g.,
192.168.x.x:8080). It should fail! - Why is "Localhost Binding" important for development databases?
Summary
Port mapping is the Gateway of your application. By understanding how to bind to specific IPs and how Docker interacts with your system firewall, you can ensure that your apps are reachable by the right people and hidden from everyone else.
Next Lesson: Automatic naming: DNS and service discovery.