Search code examples
dockernetwork-programmingiptables

Restrict connections to the Docker host for several subnets


I need to restrict connections to a docker container. The docker documentation states the following:

iptables -I DOCKER-USER -i ext_if ! -s 192.168.1.0/24 -j DROP

After this the DOCKER-USER chain starts looking like this:

Chain DOCKER-USER (1 references)
target     prot opt source               destination         
DROP       all  -- !192.168.1.0/24       anywhere            
RETURN     all  --  anywhere             anywhere

This works fine, there is access from 192.168.1.0/24 subnet and none from the rest. But my problem is that I need to add several subnets. I tried replacing this one line with several lines but without success

iptables -I DOCKER-USER 1 -i ext_if -s 192.168.1.0/24 -j RETURN
iptables -I DOCKER-USER 2 -i ext_if -s 10.0.0.0/24 -j RETURN
iptables -I DOCKER-USER 3 -j DROP

The chain starts to look like this:

Chain DOCKER-USER (1 references)
target     prot opt source               destination         
RETURN     all  --  192.168.1.0/24       anywhere            
RETURN     all  --  10.0.0.0/24          anywhere            
DROP       all  --  anywhere             anywhere            
RETURN     all  --  anywhere             anywhere

Also tried ACCEPT instead of RETURN but the result was the same - everything gets dropped, regardless of the subnet it comes from.

Is there a way to split the working one line into several?

P.S. I know that I can list the subnets separated by comma, but it's undesirable because I need to add about 15 of them with a comment for each.


Solution

  • Found a solution here. The interface should be specified in the DROP line.

    iptables -I DOCKER-USER 1 -i ext_if -s 192.168.1.0/24 -j RETURN
    iptables -I DOCKER-USER 2 -i ext_if -s 10.0.0.0/24 -j RETURN
    iptables -I DOCKER-USER 3 -i ext_if -j DROP