Search code examples
dockernetwork-programmingportubuntu-16.04iptables

port forwarding using iptables inside docker container


I am running two services (A & B) on one container. One service mocks a dependency that is required by the other.

Service A is a black-box and makes a call to an IP 169.254.169.254. I want to forward that call using iptables to Service B.

I am starting the container like this so it can have its own iptables,

docker run -it --cap-add=NET_ADMIN --sysctl net.ipv4.conf.eth0.route_localnet=1 <name> bash

Once in bash, i configure iptables to forward the call,

iptables -t nat -I PREROUTING -p tcp -d 169.254.169.254 --dport 80 -j DNAT --to-destination "127.0.0.1:8099" -i eth0

However the call doesn't get routed to 127.0.0.1. The same set of steps work if done in a Ubuntu Xenial VM.


Solution

  • You can run the below

    iptables -t nat -A OUTPUT -p tcp --dport 80 -d 169.254.169.254 -j DNAT --to-destination 127.0.0.1:8099
    

    I did a simple test on my container using below and it worked great

    root@a09ced7f6961:/# iptables -t nat -A OUTPUT -p tcp --dport 8080 -d 123.45.67.89 -j DNAT --to-destination 127.0.0.1:80
    
    root@a09ced7f6961:/# curl 123.45.67.89:8080
    <!DOCTYPE html>
    <html>
    <head>
    <title>Welcome to nginx!</title>