Fix
Can't reach a Docker container's port from another machine
Nothing forwards the host's port to the container: publishing a port is a DNAT rule on the host. Check it exists and points at the right container.
Likely causes
- The port was never published (no
-p), so no DNAT rule exists. - The rule sends the port to the wrong container address, where nothing listens.
- The service in the container listens on
127.0.0.1only.
Diagnose
Run these in order. The output is what each printed on a lab's real Linux machines.
-
visitor:~# curl -sS -m 3 http://172.17.0.2/ - From another machine the container's own address can't be reached: it's a private block inside the host.
curl: (7) Failed to connect to 172.17.0.2 port 80 after 0 ms: Could not connect to server
-
visitor:~# curl -sS -m 3 http://203.0.113.10:8080/ - The host's port 8080 is refused: nothing forwards it to the container yet.
curl: (7) Failed to connect to 203.0.113.10 port 8080 after 0 ms: Could not connect to server
Fix
-
box:~# iptables -v -t nat -A PREROUTING -p tcp --dport 8080 -j DNAT --to-destination 172.17.0.2:80 - Send the host's port 8080 to the container's port 80, as
docker run -p 8080:80does.DNAT tcp opt -- in * out * 0.0.0.0/0 -> 0.0.0.0/0 tcp dpt:8080 to:172.17.0.2:80
-
visitor:~# curl -sS -m 3 http://203.0.113.10:8080/ - The visitor gets the container's page through the host.
Juniper Bakery shop: sourdough 6.50, rye 5.00, order by noon
-
iptables -t nat -A PREROUTING -p tcp --dport 8081 -j DNAT --to-destination 172.17.0.3:80 - A rule that sends the port to a container port nothing listens on goes nowhere: point it at the port the container serves. Check with
iptables -t nat -S PREROUTING.
Break it and fix it yourself
Each lab is a small network of real Linux machines in your browser, where this fault happens.
- Container networks: give every container a network of its own : its challenge "The blog's door leads nowhere" set the fault for you to find and fix.
Open Container networks: give every container a network of its own