I’m trying to model an API container sending traffic through a separate NAT gateway container. The gateway has a private and a public network, IPv4 forwarding is enabled, and I added a POSTROUTING MASQUERADE rule. But packet captures still show the API’s address on outgoing traffic. What should I check first?
Why isn’t my Compose NAT gateway rewriting the source address?
Answers
First check the interface in the rule. Your script says “on eth1” in its status message, but the actual rule matches traffic leaving eth0. In Compose, interface names depend on network attachment order, so don’t assume which one is public. Run ip -br addr and ip route inside the gateway, then match the actual egress interface.
Also inspect the rule counter while generating traffic. If it stays at zero, the rule is not matching, or the packet is not traversing that network namespace. If it increments, check the packet capture point and conntrack behavior before changing more rules.
Reply to this answer
The bigger issue may be the network layout. network_mode: service:nat-gateway makes the API share the gateway’s network namespace. It does not give the API its own private-side address and route traffic through the gateway like a separate machine. If you want to test a NAT gateway, the API needs its own network namespace on the private network, with the gateway configured as its route out.
Keep the gateway attached to both networks, enable forwarding, and add a masquerade rule for packets leaving the public-facing interface. Then verify the route from the API and the forwarding policy on the gateway. A Compose bridge network may already apply host-side NAT for outbound access, but that is a different layer from the gateway behavior you’re trying to simulate.
Reply to this answer
Check the forwarding path as well as NAT. MASQUERADE changes the source address in POSTROUTING, but it does not by itself enable packets to pass through the gateway. Confirm IPv4 forwarding is actually on in the running container, and inspect the FORWARD chain for a policy or rule that drops the traffic.
Then test in small steps: confirm the API’s default route points to the gateway’s private address, confirm the gateway can reach the destination, and watch the NAT rule counter during a test request. That narrows down whether this is routing, filtering, or a rule-interface mismatch.
Reply to this answer
Add your answer
Answers are reviewed before publication.
Lemur+~7:
That distinction helps. I had assumed sharing the service network namespace would make the API sit behind the gateway, so I’ll revisit the topology.