First, install ipset if needed. Please refer to your distribution to know how to do it. As an example, here is the command for Debian-like distributions.
$ apt-get update $ apt-get install ipset
Then create a configuration file to define an ipset containing the IPs for which you want to open access to your Docker containers.
$ vi /etc/ipfriends.conf # Recreate the ipset if needed, and flush all entries create -exist ipfriends hash:ip family inet hashsize 1024 maxelem 65536 flush # Give access to specific ips add ipfriends XXX.XXX.XXX.XXX add ipfriends YYY.YYY.YYY.YYY
Load this ipset.
$ ipset restore < /etc/ipfriends.conf
Be sure that your Docker daemon is running : no error should be shown after entering the following command.
$ docker ps
You are ready to insert your iptables rules. You must respect the order.
// All requests of src ips not matching the ones from ipset ipfriends will be dropped. $ iptables -I DOCKER -i ext_if -m set ! --match-set ipfriends src -j DROP // Except for requests coming from a connection already established. $ iptables -I DOCKER -i ext_if -m state --state ESTABLISHED,RELATED -j ACCEPT
If you want to create new rules, you will need to remove all custom rules you've added before inserting the new ones.
$ iptables -D DOCKER -i ext_if -m set ! --match-set ipfriends src -j DROP $ iptables -D DOCKER -i ext_if -m state --state ESTABLISHED,RELATED -j ACCEPT