Make Docker play nicely with UFW

I’ve been spending a lot of time working with Docker over the last year, primarily in Ubuntu environments. So long in fact, that I seem to have forgotten this blog exists 🙂

Something it took me a while to figure out was how to stop Docker from bypassing UFW and exposing mapped ports to the world (due to specifying its own iptables chain). More often than not, I want containers to be restricted to private network access only. One option is to specify an ip address when mapping ports, but that’s a bit clunky and doesn’t work so well when you want to be able access the ports via multiple private ip addresses.

The challenge was making sure not to block outbound or inter-container connectivity in the process.

Having had to set up a number of servers and keep finding myself forgetting one of the steps, I figured it was about time I put this blog to good use and list the necessary commands here:

sudo ufw allow in on docker0
sudo ufw enable
iptables -t nat -A POSTROUTING ! -o docker0 -s -j MASQUERADE
This entry was posted in Fixes and tagged , , . Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.


  1. Juan
    Posted May 17, 2016 at 10:13 pm | Permalink

    thank you! This is just what I needed.

  2. Brandon
    Posted December 30, 2016 at 8:32 pm | Permalink

    Thanks Luke, this did the trick!

12 Trackbacks

Leave a Reply