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

Viewed 9457

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
2 Answers

As per [1], you should use the DOCKER-USER chain:

All of Docker’s iptables rules are added to the DOCKER chain. Do not manipulate this chain manually. If you need to add rules which load before Docker’s rules, add them to the DOCKER-USER chain. These rules are applied before any rules Docker creates automatically.

for example, if you want to block all containers within the docker0 interface from accessing example.com - you'd do something like:

iptables -I DOCKER-USER -d example.com -i docker0 -j REJECT

[1] https://docs.docker.com/network/iptables/#add-iptables-policies-before-dockers-rules

Related