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:

apt-get install -y lxc

Now create non-root system user for lxc:

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

I recommend to add autostart as default behaviour:

su lxcusr

and add lines

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

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

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

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

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

Create first container:

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

Don not forget to delete default user in container:

userdel ubuntu && rm -rf /home/ubuntu