Adding FIREWALL to Docker

This is going to solve problems of many Devops engineers looking for Firewall Security for their containers.

Following are my previous articles on Docker Security:

and

Docker does not prevent one from doing Host Firewall implementation; rather, it adds to the complexity. This guide is indented to add host firewall to docker.

STEP 1

(a)Navigate to /etc/systemd/system/ and create a directory named docker.service.d
(b) create a file noiptables.conf and add the following content:

[Service]
ExecStart=
ExecStart=/usr/bin/docker daemon -H fd:// --iptables=false

STEP 2

(a) Restart Docker
(b) check iptables -L -n -v (If everything Okay you will not see any rules :) )

STEP 3

(a) RUN apt-get install iptables-persistent

After running this, you will be prompted to save your IPv4, and then your IPv6 rules to two files, /etc/iptables/rules.v4 and /etc/iptables/rules.v6 respectively.

In order to give IPv4 Internet Access to all the containers, the server must perform NAT.To do that, in the beginning of the rules.v4 file, add the following:

*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING -o eth0 -j masquerade
COMMIT
And then below it,

After you’re finished, your rules.v4 / rules.v6 file will look something like this:

*nat
:PREROUTING ACCEPT [0:0]
:INPUT ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]
:POSTROUTING ACCEPT [0:0]

-A POSTROUTING -o eth0 -j MASQUERADE

COMMIT

*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [0:0]

# Allow localhost
-A INPUT -i lo -j ACCEPT
-A OUTPUT -o lo -j ACCEPT

# ICMP
-A INPUT -p icmp -j ACCEPT

# Docker
-A FORWARD -i docker0 -o eth0 -j ACCEPT
-A FORWARD -i eth0 -o docker0 -j ACCEPT

# Incoming
-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

# Outgoing
-A OUTPUT -j ACCEPT

# Routing
-A FORWARD -j DROP

COMMIT

Of course, you must replace eth0 with your outbound network interface if it is different than eth0.
After you complete that, restart the firewall via netfilter-persistent reload, and you’re good to go!

Read More here

34