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.
Default UFW settings
sudo ufw allow ssh
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw enable
Configure default forward policy
sudo nano /etc/default/ufw
Edit Line:
DEFAULT_FORWARD_POLICY="ACCEPT"
Reload UFW
sudo ufw reload
Allow docker port (default: 2375)
sudo ufw allow 2375
Enable daemon.json
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
Setup daemon.json
sudo nano /etc/docker/daemon.json
Set Content:
{
"hosts": ["fd://"],
"dns": ["8.8.8.8", "8.8.4.4"],
"iptables": false
}
Restart Docker
sudo systemctl daemon-reload
sudo systemctl restart docker
Configure NAT
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
Reboot system
sudo reboot now
Now ports exposed by docker have to explicitly be enabled in UFW