Tips for LXC 2: unprivileged containers

2016-08-19
#lxc #server #howto #ubuntu

LXC containers are great for application isolation and safe deployment. Running unprivileged containers is the safest way to run containers in a production environment. This note contains enough information to create your own safe container.

Install LXC:

1apt-get install -y lxc

Now create a non-root system user for lxc:

1useradd --home-dir /srv/lxc --create-home lxc
2echo "lxc veth lxcbr0 2" | sudo tee -a /etc/lxc/lxc-usernet
3passwd lxc <type password>

I recommend adding autostart as the default behavior:

1su lxcusr

and add lines

1# Autostart
2lxc.start.auto = 1
3lxc.start.delay = 5

to file ~/.config/lxc/default.conf

Add uid mappings in ~/.config/lxc/default.conf:

1# UID mappings
2lxc.include = /etc/lxc/default.conf
3lxc.id_map = u 0 100000 65536
4lxc.id_map = g 0 100000 65536

Before container creation, you must log in as the lxc user directly (like ssh lxc@server.name), or you will get an error.

Create the first container:

1lxc-create -t download -n sample.dima.io -- -d ubuntu -r xenial -a amd64
2lxc-start -d -n sample.dima.io
3lxc-attach -n sample.dima.io

Do not forget to delete the default user in the container:

1userdel ubuntu && rm -rf /home/ubuntu