Add new iptables rules to Docker

Hello,
Docker has its own iptables rules. I want to add the following rules to iptables:

-A INPUT -i lo -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type 8 -m limit --limit 2/sec -j ACCEPT
-A INPUT -p icmp -m icmp --icmp-type 8 -j DROP
-A INPUT -m state --state INVALID -j DROP
-A INPUT -p icmp -j ACCEPT
-A INPUT -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p tcp -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 80 -j ACCEPT
-A INPUT -p tcp -m tcp --dport 443 -j ACCEPT
-A INPUT -j DROP

I save the above rules in a file and use the following script to restore it when the system reboots:

#!/bin/sh
iptables-restore < /etc/File

Will my iptables rules be deleted after the system is booted and the docker service is running?

Thank you.

Hi,
I tested it and Docker clears my iptables rules. How to solve it?

Thanks.

It is explained here:

https://docs.docker.com/network/packet-filtering-firewalls/#add-iptables-policies-before-dockers-rules

And I summarized the options for a similar issue here:

The DOCKER-USER chain can be changed. But as far as I know, iptables-restore restores all rules removing the existing rules so you will need to use the iptables commands in a script to insert new rules.

1 Like

Hi,
Thank you so much for your reply.
I take a look at the URL and the following example caught my attention:

sudo iptables -I DOCKER-USER -p tcp -m conntrack --ctstate ESTABLISHED,RELATED -j ACCEPT
sudo iptables -I DOCKER-USER -p tcp -m conntrack --ctorigsrc 1.2.3.4 --ctorigdstport 80 -j ACCEPT

I want only port 80 to be open on the host. I know iptables rules normally, but I donā€™t know docker structure. Can you write it for me with docker structure?

There is no Docker structure. iptables is iptables and Iā€™m not good at writing it.

1 Like

Hi all,
Can someone write an iptables rule for Docker so that only ports 80, 443 and 22 are open on the host?

Thank you.