Uncomplicated Firewall (UFW) is not blocking anything when using Docker

The problem was using the -p flag on containers.

It turns out that Docker makes changes directly on your iptables, which are not shown with ufw status.

Possible solutions are:

  1. Stop using the -p flag. Use docker linking or docker networks instead.

  2. Bind containers locally so they are not exposed outside your machine:

    docker run -p 127.0.0.1:8080:8080 ...

  3. If you insist on using the -p flag, tell docker not to touch your iptables by disabling them in /etc/docker/daemon.json and restarting:

    { "iptables" : false }

I recommend option 1 or 2. Beware that option 3 has side-effects, like containers becoming unable to connect to the internet.


16.04 presents new challenges. I did all the steps as shown Running Docker behind the ufw firewall BUT I could NOT get docker plus UFW to work on 16.04. In other words no matter what I did all docker ports became globally exposed to the internet. Until I found this: How to set Docker 1.12+ to NOT interfere with IPTABLES/FirewallD

I had to create the file /etc/docker/daemon.json and put the following in:

{
    "iptables": false
}

I then issued sudo service docker stop then sudo service docker start FINALLY docker is simply following the appropriate rules in UFW.

Additional data: Docker overrules UFW!


If you're using the init system of systemd (Ubuntu 15.10 and later) edit the /etc/docker/daemon.json (might need to create it if it does not exist), make sure it has iptables key configured:

{   "iptables" : false }

EDIT: this might cause you to lose connection to the internet from inside containers

If you have UFW enabled, verify that you can access the internet from inside containers. if not - you must define DEFAULT_FORWARD_POLICY as ACCEPT on /etc/default/ufw and apply the trick described here: https://stackoverflow.com/a/17498195/507564