Programster's Blog

Tutorials focusing on Linux, programming, and open-source

Using Nftables With Docker

If you have used Docker with iptables or UFW in the past, you might have noticed that the two don't generally work together as you might expect. E.g. if you opened up port 3306 on your MySQL/MariaDB database container, and added some rules to UFW to only allow port 3306 from certain source IP addresses, you might then be surprised to find out that you were able to connect on port 3306 from any IP address, and your UFW rule was pretty much useless. This is because docker has to create one or bridge networks, and manages the complicated networking through the manipulation of iptables.

I recently switched over to using the newer nftables for my NAT servers, and when doing this for a client, I realized that they also needed to be able to run a Docker image on it, for it to run Nginx Proxy Manager.

This tutorial outlines how I was able to get the nftables firewall and port forwarding rules working as expected, with the Nginx Proxy manager running on the same server as I would expect.

Steps

I am going to assume that you are starting out with a fresh Debian 12 machine, with nothing having been already installed (e.g. no Docker etc).

Prevent Installation of iptables Module

The first thing we want to do is prevent the installation of iptables module on the server

sudo echo "install ip_tables /bin/false" | sudo tee --append /etc/modprobe.d/noiptables.conf
sudo echo "install ip6_tables /bin/false" | sudo tee --append /etc/modprobe.d/noiptables.conf

Install Docker

Next, we can go ahead and install Docker as my tutorial outlines.

Configure Docker

Now edit the /etc/docker/daemon.json file (you probably need to create it), to disable iptables and ip6tables (for ipv6) like so:

{
  "iptables": false,
  "ip6tables": false
}

Then restart the Docker deaemon for the changes to take effect:

sudo service docker restart

Host Mode Networking

Update your docker run command, or docker-compose.yaml file to ensure that the container(s) are running in "host" mode networking. This is the only major caveat, and is required for this to work.

Apply Nftables Rules

Now we can add/apply our nftables rules, whatever they may be. Teaching you nftables is beyond the scope of this tutorial, but feel free to refer to my Nftables cheatsheet.

Test / Check

I would recommend testing that your firewall is working as you expect. I would make sure to do this after having restarted the docker service (sudo service docker restart), and even rebooting the server. If you configured Docker as I outlined above, it shouldn't be trying to manipulate your iptables/nftables, and hopefully you have configured your server to load your nftables rules on startup.

References

Last updated: 8th August 2024
First published: 7th August 2024