Connecting a container to the Internet
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 10.0.0.1 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 10.0.0.10 dev host0 ip route add default via 10.0.0.10 dev host0
On the host side, I do the same
ip addr add 10.0.0.10 dev ve-host1 ip link set dev ve-host1 up
and again setting a route to the container
ip route add 10.0.0.1 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
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. 192.168.1.1 or 192.168.0.1)
ping -c 1 10.0.0.1 ping -c 1 10.0.0.10 ping -c 1 192.168.1.1
A ping to an Internet server, e.g.
ping 188.8.131.52 works too, but to
ping www.google.com, you must first setup DNS in the container, of