Docker and Ubuntu UFW

I was playing with Docker last week and wanted to add a firewall in front of it. This was to allow me to expose some docker containers so they could only be accessed from a restricted set of IP addresses. There are quite a few posts around that that outlines some of the deficiencies of Docker with UFW and make partial suggestions to work around this.

The main issue is that by default Docker will add iptables rules to allow external access to any ports that are exposed on docker containers. Most information I found focuses on adding –iptables=false to the docker daemon which stops Docker from allowing access to all ports through iptables. This is only half the story as there is then no info on how to enable access on a case-by-case basis. The most useful piece of information I found is a comment in an issue raised against Docker which is what the instructions below are based on.


  • Secure Docker behind Ubuntu’s Uncomplicated Firewall (UFW)
  • Avoid directly using iptables (iptables make my head hurt)


  • Basic understanding of Ubuntu UFW (this link is useful too)
  • Basic understanding of Docker (all info here relates to Docker 1.8)
  • Basic Linux skills
  • Docker containers live on the subnet (this is the default)


1. start docker with –iptables=false (edit DOCKER_OPTS within /etc/default/docker – on Ubuntu and add –iptables=false)
2. reboot the server to pick up the Docker changes
3. Enable UFW and configure rules:

<p>ufw allow ssh/tcp<br>
ufw allow from # allow containers to talk to each other through exposed ports on the main server<br>
ufw enable<br>
sudo ufw status</p>

4. add the following iptables rules to ufw and change the default forward policy for ufw

<p>#if running at the command line<br>
iptables -P FORWARD ACCEPT # allow containers to talk to each other directly<br>
iptables -t nat -A POSTROUTING ! -o docker0 -s -j MASQUERADE # allow outbound connections to the internet from containers</p>
<p># otherwise<br>
## add the following to /etc/ufw/after.rules :<br>
# NAT table rules<br>
-A POSTROUTING ! -o docker0 -s -j MASQUERADE # allow outbound connections to the internet from containers</p>
<p>## add (actually, change DROP to ACCEPT) the following to /etc/default/ufw<br>

5. reload ufw to capture the iptables rules
6. start any docker containers
7. add rules to UFW to allow access to the ports if appropriate (ufw allow 8080; ufw reload)

That’s it, your firewall configuration will persist between restarts keeping your docker host and containers secure.

Photo by Sigmund on Unsplash

3 thoughts on “Docker and Ubuntu UFW”

  1. Hey, this is a awesome tutorial! The only problem I noticed is that the IP addresses connecting to your applications are always from the Docker network, which breaks things like rate limiting. Do you have a idea on how to fix that? I didn’t find anything usable when I searched.

Comments are closed.