Search code examples
linuxdockernetwork-programmingiptables

How to configure docker's iptables rule DOCKER-USER to restrict output?


I'm running a container, and I want to only allow it to access specific ips. In other words, I want to reject most of the destination ips.

I have tried the following:

iptables -I DOCKER-USER -o custom-interface ! -d xxx.xxx.xxx.xxx -j REJECT

But it rejects all the connection, I can't ping xxx.xxx.xxx.xxx.

It's really strange, I think I just block the output packets through custom-interface which would not reach xxx.xxx.xxx.xxx. So all the incoming packets and output packets which would reach xxx.xxx.xxx.xxx are accept.

But it seems I'm wrong. Why? Any help is appreciate.

Edit

The accepted answer shows how to configure incoming restriction, and then I have learned how to configure outgoing restriction.

Create a BEFORE_DOCKER table

iptables -N BEFORE_DOCKER

Default

iptables -I BEFORE_DOCKER -j DROP

Docker Containers Public Admin access (insert all your allowed IPs here)

iptables -I BEFORE_DOCKER -o eth0 -d 172.114.1.23 -j ACCEPT
iptables -I BEFORE_DOCKER -o eth0 -d 10.129.172.12 -j ACCEPT

Docker Containers Restricted LAN Access (insert your LAN IP range or multiple IPs here)

iptables -I BEFORE_DOCKER -o eth1 -d 192.168.10.1 -j ACCEPT
iptables -I BEFORE_DOCKER -o eth1 -d 192.168.10.2 -j ACCEPT

Last step is to insert this as the first table on the FORWARD chain.

iptables -I FORWARD -i docker0 -j BEFORE_DOCKER

Solution

  • Create a BEFORE_DOCKER table with a default rule of REJECT, next step is to insert this as the 1st table on the FORWARD chain.

    Create a BEFORE_DOCKER table

    iptables -N BEFORE_DOCKER
    

    Default

    iptables -I BEFORE_DOCKER -j DROP
    

    Docker Containers Public Admin access (insert all your allowed IPs here)

    iptables -I BEFORE_DOCKER -i eth0 -s 172.114.1.23 -j ACCEPT
    iptables -I BEFORE_DOCKER -i eth0 -s 10.129.172.12 -j ACCEPT
    

    Docker Containers Restricted LAN Access (insert your LAN IP range or multiple IPs here)

    iptables -I BEFORE_DOCKER -i eth1 -s 192.168.10.1 -j ACCEPT
    iptables -I BEFORE_DOCKER -i eth1 -s 192.168.10.2 -j ACCEPT
    

    Last step is to insert this as the first table on the FORWARD chain.

    iptables -I FORWARD -o docker0 -j BEFORE_DOCKER
    

    HOPE it will help !!