It has been a long time since I wanted to control connections from/to Docker containers but I could never find a simple enough solutions. We can control reverse proxy settings (Traefik) using labels but we can’t apply iptables rules with them? Nonsense. If you add to this that every container lives in a namespace, and namespaces can have their iptables rules, you have there an easy solution.

So I wrote a Bash script that listen to Docker events. It filters on container starts which have the label firewall.enable=true, so it does not wake up often.

Then it processes the firewall.rules.<id>, by alphanumerical order. It tries to make sure rules are valid and apply them in the container network namespace.

When the container is removed, the namespace is removed too and the firewall rules with it. Simple. Clean.

Configure a systemd unit to run the script after the Docker daemon and you’re set.

The project is here: https://github.com/ftoppi/docker-firewall

Of course, I asked my friends ChatGPT and Mistral for some help. Some suggestions about what to improve and most of all for jq filters (this is black magic). I could have done it with pipe grep sed and all, but I wanted a cleaner approach.