6

I never touched the iptables for Docker but now I think I have to. Within a special container, a program/script calls an IP 57.55.10.210 and I cannot change it (another story). I want to redirect the call to this IP to 192.168.38.13. How can do this and does this will have an affect to other containers? Thanks in advance! Frank

Ivan Aracki
  • 4,861
  • 11
  • 59
  • 73
FrankS77
  • 271
  • 4
  • 17

1 Answers1

5

One way would be to get iptables installed within your container image and assign your container the kernel capability(7) NET_ADMIN.

docker run --cap-add=NET_ADMIN ...

See the docker run reference and/or the docker-compose file reference

Then you could add either a entrypoint script, a cmd or a .rules file from which you load a rule-set when starting the container. Or you directly embed the rules into the image. In your case the contents of an entrypoint script would look like:

iptables -t nat -A PREROUTING -d 57.55.10.210 -j DNAT --to-destination 192.168.38.13
iptables -t nat -A POSTROUTING -s 192.168.38.13 -j SNAT --to-source 57.55.10.210

Or with the .rules file, in your entrypoint script do:

/sbin/iptables-restore /some-mounted-volume-or-file

In order to get a rules file you could invoke a single run of your container:

docker run --cap-add=NET_ADMIN --rm somethingwith/iptables /bin/bash -c "iptables -t nat -A PREROUTING -d 57.55.10.210 -j DNAT --to-destination 192.168.38.13; iptables -t nat -A POSTROUTING -s 192.168.38.13 -j SNAT --to-source 57.55.10.210; /sbin/iptables-save" > outside-of-container.rules

Which will get you something like:

# Generated by iptables-save v1.6.1 on Fri Feb  8 14:42:52 2019
*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A PREROUTING -d 57.55.10.210/32 -j DNAT --to-destination 192.168.38.13
-A POSTROUTING -s 192.168.38.13/32 -j SNAT --to-source 57.55.10.210
COMMIT
# Completed on Fri Feb  8 14:42:52 2019

As far as I know this approach should not interfere with other containers on the host.