Solving UFW and Docker iptables Conflicts on Ubuntu

By Alexander Eriksson · · Updated


I ran into a surprise when Docker completely ignored my UFW rules, leaving my containers exposed. Here’s how to fix it by adjusting UFW’s forwarding policy and adding proper routing rules to protect your data.

The Problem: Why UFW and Docker Don't Work Together

When you set up UFW (Uncomplicated Firewall), you expect it to protect your server by blocking unwanted network traffic. However, if you're also using Docker, you may find that your Dockerized applications are still publicly accessible, even on ports you've blocked with UFW.

This happens because Docker doesn't use UFW's rules for forwarding network traffic. Instead, it creates its own iptables rules that bypass UFW entirely. These rules take precedence and allow traffic to reach your containers, regardless of what your UFW rules say.


The Solution: Make UFW and Docker Play Nice

To fix this, you need to configure UFW to properly process forwarded packets, which involves two steps:

  1. Changing UFW's forwarding policy to "ACCEPT" instead of "DROP".
  2. Creating explicit ufw route rules to allow the specific traffic you want.

Change the Forwarding Policy

By default, UFW's forwarding policy is set to DROP, which means it won't inspect or filter any traffic being forwarded through your server. By changing this to ACCEPT, you're telling UFW to start applying its rules to that traffic.

sudo sed -i -e 's/DEFAULT_FORWARD_POLICY="DROP"/DEFAULT_FORWARD_POLICY="ACCEPT"/g' /etc/default/ufw

Add UFW Routing Rules

Now that UFW is ready to filter forwarded traffic, you need to create rules for it. The ufw route command allows you to define specific rules for traffic that is being forwarded to your containers.

For example, to allow incoming traffic on ports 80 and 443, you would simply

sudo ufw route allow proto tcp from any to any port 80
sudo ufw route allow proto tcp from any to any port 443

You can of course customize these rules to be as specific (and safe) as you need. For instance, you could restrict access to a single IP address or an entire network.

Once you've made these changes, simply reload UFW to apply your new rules

sudo ufw reload

This new configuration ensures that both Docker and UFW are working together, giving you full control over which services on your server are accessible from the outside.

Back to Blog