Connecting a container to the Internet

Submitted by olaf on 2016-06-26

Yesterday, I wrote about connecting several containers via a bridge. But this keeps the containers confined to the bridge and itself.

This time, I want to allow a container to access the Internet.


Same setting as last time, I start the container with

systemctl start systemd-nspawn@host1

In the container, I assign an IP address and bring up the interface

ip addr add dev host0
ip link set dev host0 up

With only an address (basically a point to point connection), I must add a routing entry to the host manually plus a default route

ip route add dev host0
ip route add default via dev host0


On the host side, I do the same

ip addr add dev ve-host1
ip link set dev ve-host1 up

and again setting a route to the container

ip route add dev ve-host1

In order for the host to push network packets back and forth, we must enable IP forwarding

echo 1 >/proc/sys/net/ipv4/ip_forward

or permanently

sysctl -w net.ipv4.ip_forward=1

And finally activate masquerading, because neither the LAN hosts nor the Internet know about the local container

iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE


Testing connectivity with a ping to the container, the host, and the internet gateway (e.g. or

ping -c 1
ping -c 1
ping -c 1

A ping to an Internet server, e.g. ping works too, but to ping, you must first setup DNS in the container, of course.

Post a comment

All comments are held for moderation; Markdown and basic HTML formatting accepted. If you want to stay anonymous, leave name, e-mail and website empty.