Search code examples
dockeriptables

What is the best way to limit the IP addresses which can be access from within a docker container?


I have an answer which will limit docker containers to only be able to access a single IP address outside the host. Using this iptables rule on the host:

# iptables -I FORWARD -i docker0  ! -d 8.8.8.8 -j DROP

means that from inside any docker containers it is only possible to access the IP address 8.8.8.8.

This is fairly drastic - basically, if the destination is NOT 8.8.8.8 then drop the packet.

What is the best way that I can set up rules which would allow me limit the containers to a certain number of IP addresses?


Solution

  • If you have a list of specific addresses to which you want to permit access, you may want to investigate the ipset command, which allows you to maintain a list of ip addresses in the kernel that can be used by iptables rules. This may drastically simplify your ruleset.

    Create a new ipset:

    ipset create dockerdests hash:ip
    

    Add some addresses to the set:

    ipset add dockerdests 8.8.8.8
    ipset add dockerdests 162.13.208.130
    

    Create an iptables rule referencing the set:

    iptables -I FORWARD 1 -i docker0 -m set --match-set dockerdests dst -j ACCEPT
    iptables -I FORWARD 2 -i docker0 -j DROP
    

    These commands insert two rules at the top of the FORWARD chain; the first will accept packets going to or from anything listed in the named ip set, and the second rule will drop anything coming in on docker0 that was not accepted by the previous rule.

    If you go this route, you would need to arrange to load your ipset configuration when the system boots.

    More information about ipset can be found here.