>_ IzzyLab

Hands-on task

This task is step 13 of the course “Docker networking”

Port forwarding from the inside: DNAT in iptables

hard~20 min

The payment gateway pay (izzylab/minihttp:1) is published on the server's port 9443 (docker port pay). The container is alive and answers inside, but curl http://127.0.0.1:9443/ and a request to the server's external address (eth0) hang until timeout.

After the move from the old server, hand-written rules were left in the nat table. Use iptables -t nat to work out where packets to 9443 really go, and fix it:

  • remove the extra rules; don't touch Docker's rules, don't recreate or restart pay;
  • pay answers both on 127.0.0.1:9443 and on the server's external address;
  • write to /root/dnat.txt, as IP:port, where Docker actually forwards port 9443.

The lab has its own Docker with no internet access; the images are already loaded: izzylab/minihttp:1, alpine:3.21, busybox:1.36, nginx:1.27-alpine. izzylab/minihttp is a tiny HTTP service on port 8080: GET / answers <NAME> ok, GET /call itself goes to http://<UPSTREAM>/ and answers <NAME> -> <the neighbor's reply> (or 502), GET /env shows its settings. It is configured with the environment variables NAME, PORT, BIND (the address it listens on) and UPSTREAM.

What you'll practise:
  • iptables nat
  • DNAT
  • docker port publishing

Topic breakdown

Port publishing in Docker is NAT. For -p 9443:8080 Docker adds a rule to its own DOCKER chain in the nat table: -p tcp --dport 9443 -j DNAT --to-destination <container IP>:8080. Jumps into the DOCKER chain come from PREROUTING (packets arriving from outside) and from OUTPUT (connections from the server itself to its own addresses). Replies are rewritten back automatically — the kernel remembers the connection in conntrack. If a foreign DNAT rule for the same port sits above the jump, it fires first and sends the connection to the old address, and Docker's rule isn't even checked. The counters (-v) show which rule actually catches the packets.

What's checked

  1. pay is running, not recreated or restarted
  2. pay answers on 127.0.0.1:9443
  3. pay answers on the server's external address
  4. No manual rules for 9443 left in PREROUTING and OUTPUT
  5. Docker's jumps from PREROUTING and OUTPUT to the DOCKER chain are in place
  6. Docker's rule for 9443 is in place
  7. /root/dnat.txt says where Docker forwards 9443

What it looks like