Docker Tip #29: Containers Can't Access the Internet? Check iptables
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.
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.
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