I am running a node server inside a docker container on port 8080 and i can access it via (container ip) now i want to access this ip from localhost:9099.

I have tried using iptables to redirect this traffic coming at localhost:9099 to but all measures are in vain.

This is the command i was using. Please correct me where i am going wrong. Thanks in advance.

sudo iptables -t nat -A PREROUTING -p tcp --dport 9099 -j DNAT --to-destination

I took help from this ans but didn't work.


There are few issues with your attempt:

  • using localhost means connections are initiated from the host, not routed from an other host. Thus it requires the OUTPUT chain, not the PREROUTING chain since routing was not initially involved.
  • the source IP, which would be has to be changed too once the destination is changed. This requires an additional POSTROUTING rule. An optional -m conntrack --ctstate DNAT match will check that the first OUTPUT did match first and it's not some spoofing attempt.
  • At least on Linux is handled specially in the routing stack, and the packet will be dropped before the POSTROUTING rule triggers. To remove the special handling and allow routing "outside" of the block, the interface on which the redirection will happen must have the flag route_localnet set to 1, or none of the above will be enough.

Since the interface is not known from the Question, the interface name is retrieved from the route and put in a variable. Adapt it if needed. You can also use the all pseudo-interface instead to set the flag globally.

So in the end this boils down to (as root or using sudo):

iptables -t nat -A OUTPUT -p tcp --dport 9099 -j DNAT --to-destination
iptables -t nat -A POSTROUTING -s -d -m conntrack --ctstate DNAT -j MASQUERADE
interface=$(ip -o route get | grep -o 'dev [^ ][^ ]*'|sed 's/^dev //')
echo 1 > /proc/sys/net/ipv4/conf/$(interface)/route_localnet

Once all that is said, you should try using a non- address, still local to the host. This could simplify things, not requiring route_localnet (and possibly sometimes not requiring the additional POSTROUTING rule).

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.