Ubuntu has a great firewall called the 'Uncomplicated Firewall' or UFW for short. This is a great option if you want to secure your system.
Docker, by default, will update your iptables and punch holes in your firewall. This guide will show you how to constrain Docker behind UFW, providing consistent system firewall security.
sudo ufw allow ssh
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw enable
sudo nano /etc/default/ufw
Edit Line:
DEFAULT_FORWARD_POLICY="ACCEPT"
Reload UFW
sudo ufw reload
sudo ufw allow 2375
sudo mkdir -p /lib/systemd/system/docker.service.d
sudo nano /lib/systemd/system/docker.service.d/override.conf
Set Content:
[Service]
ExecStart=
ExecStart=/usr/bin/dockerd
sudo nano /etc/docker/daemon.json
Set Content:
{
"hosts": ["fd://"],
"dns": ["8.8.8.8", "8.8.4.4"],
"iptables": false
}
sudo systemctl daemon-reload
sudo systemctl restart docker
sudo nano /etc/ufw/before.rules
Add lines before "filter"*
*nat
:POSTROUTING ACCEPT [0:0]
-A POSTROUTING ! -o docker0 -s 172.17.0.0/16 -j MASQUERADE
COMMIT
sudo reboot now
Now ports exposed by docker have to explicitly be enabled in UFW