Iptables for Docker in an internet exposed server

Today I have a little guide for you for those of you who want to install Docker in a server which interface is exposed to the internet. Due to the iptables rules Docker creates by default when we use the -p option to forward a port without specifying the interface we will find out that this port is also being exposed to the internet, something we don’t want in most of the cases.

The solution is to tell Docker to not touch our iptables. In systems like Debian that use systemd we can achieve this by using the following commands:

mkdir /etc/systemd/system/docker.service.d
cat << EOF > /etc/systemd/system/docker.service.d/noiptables.conf
ExecStart=/usr/bin/docker daemon -H fd:// --iptables=false
systemctl daemon-reload


We restore our iptables using iptables-restore for example, also restart Docker and we will see that it doesn’t generate the Docker table or any other rule. But, as always there is a but, this has left our containers without internet access.

The first step to fix this is to enable forwarding in our system if we don’t have it already:


sysctl -w net.ipv4.ip_forward=1

And then we add the following lines:

iptables -A FORWARD -i docker0 -o eth0 -j ACCEPT
iptables -A FORWARD -i eth0 -o docker0 -j ACCEPT

This will allow the traffic to reach the containers but the problem will be that it will not know what to do with the response, for this we need to add a MASQUERADE rule, if you use the default Docker range the rule will look like this:

iptables -t nat -A POSTROUTING -s -o eth0 -j MASQUERADE

You should do this for each segment in your Docker network that you want it to have internet access.

With this you can open and close port in your server the usual way without Docker opening them by itself.


I found this issue while checking my Wazuh installation, the problem was that after applying the above changes my clients weren’t able to connect to Wazuh anymore.

The problem comes from Wazuh that is seeing the server instead of the client ip due to the MASQUERADE rule and as it didn’t match any the client’s ip it rejected the packets.

The only option I could find so far was to remove the clients and register them again using any as the ip in a way that Wazuh will accept any origin ip for the clients.

Remenber that for the containers to have internet, if you have used docker-compose, you will need to add a MASQUERADE rule for that specific network, in my case

Hope you have enjoyed the post and saves you from unwanted surprises like mine finding out my containers exposed to the internet even after spending hours crafting my iptables so that didn’t happen, but we can always learn.

Best regards, and as always, thanks for  your visit!

This entry was posted in docker, tutorial, wazuh. Bookmark the permalink.

Leave a Reply