There are a lot of good guides online that show some facets of letting docker work nicely with ufw as firewall. Unfortunately they all miss some small details that I needed to find out myself.
Notably I want to give some credits to this post which helped me the most.
https://www.mkubaczyk.com/2017/09/05/force-docker-not-bypass-ufw-rules-ubuntu-16-04/
But now what I missed. Those instructions do not persist over reboots of the server.
Lets start with the setup I have:
- Ubuntu server 18.04
- Docker
Now, in my case I have some services in docker, some as services as regular linux services. Some of those services need to be accessible from an internal VPN network, others may be publically accessible. I want UFW to controll what is accessible from where.
So lets start with docker. Docker controlls the iptables directly. I don’t want that. So lets disable that now.
# sudo nano /etc/docker/daemon.json
Disable the iptables manipulation in this config file.
{
"iptables": false
}
This has the side effect that containers cannot communicate with the world anymore. So lets fix that.
Other guides will tell you to input some iptable commands. I want those rules to be applies on startup.
We need some additional packages.
# sudo apt install iptables-persistent
During the installation it will ask if you want to save the current iptables rules. We do not want that, so decline those options. What we want is to set a specific rule that is applied at boot time.
# sudo nano /etc/iptables/rules.v4
And fill it with:
*nat
-A POSTROUTING -s 172.17.0.0/16 ! -o docker0 -j MASQUERADE
COMMIT
UFW
Now it is time to play with UFW, assuming it is already installed.
First thing if that we have to change a little bit of configuration with a command.
$ sudo sed -i -e
s/DEFAULT_FORWARD_POLICY="DROP"/DEFAULT_FORWARD_POLICY="ACCEPT"/g' /etc/default/ufw
$ sudo ufw reload
Now we can apply our ufw rules, for example:
- Allow SSH from any outside connection
- Allow MySQL only from my internal VPN connections
$ sudo ufw allow ssh
$ sudo ufw allow from 10.0.0.0/24 to any port 3306
$ sudo ufw enable
Now it should be fine to reboot the server, and all firewall rules should be controlled by UFW while docker still works.
1 thought on “Let docker and ufw work nicely”
Comments are closed.