Learn Docker With My Newest Course

Dive into Docker takes you from "What is Docker?" to confidently applying Docker to your own projects. It's packed with best practices and examples. Start Learning Docker →

Docker Tip #29: Containers Can't Access the Internet? Check iptables

docker-tips-and-tricks.jpg

There's a few reasons why a container might fail to access the internet but we're going to talk about iptables in production here.

Quick Jump:

Docker can run on most major platforms but this tip is focused on running Docker on a Linux host, and will most likely only apply to production (as opposed to development).

If you happen to write out your own iptables rules you may accidentally override what Docker placed and that’s going to break networking inside of your containers.

Docker will append to your iptables rules when the Docker daemon is started as well as when containers are running.

You can verify this by running sudo iptables -L on your Docker host. If you have Docker installed you should see all sorts of Docker specific rules. If you do not see those rules then chances are you overwrote them by accident.

A quick fix would be to restart the Docker daemon. You can do that by running sudo service docker restart or sudo systemctl restart docker depending on what distribution and version of Linux you are running.

Keep in mind, restarting the Docker daemon means your containers will restart too, but if they are not responding due to network issues then it’s likely not the end of the world.

In the future, if you’re setting your own iptables rules from a static rules file then make sure those rules are applied before Docker is started. If you’re using systemd you could set up a 1 shot service to run before the network stack which in turn will happen before Docker starts.

An example of writing the iptables rules before the network stack comes up:
[Unit]
Description=Restore iptables firewall rules
Before=network.target
Conflicts=shutdown.target

[Service]
Type=oneshot
ExecStart=/sbin/iptables-restore /var/lib/iptables/rules-save

[Install]
WantedBy=basic.target

Free Intro to Docker Email Course

Over 5 days you'll get 1 email per day that includes video and text from the premium Dive Into Docker course. By the end of the 5 days you'll have hands on experience using Docker to serve a website.



Comments