Linux Containers (LXC) tutorial

Docker is a big deal these days. However, it is not the only game in town. Today, we are going to take a look at Linux containers, which is one alternative to Docker.

LXC homepage: https://linuxcontainers.org/lxc/introduction/

This tutorial has been composed with Debian 10. Notice that I am not using systemd(no systemctl commands).

#Installation of the needed software:

sudo apt-get install lxc lxc-templates bridge-utils debootstrap libvirt0 libpam-cgroup libpam-cgfs apparmor apparmor-profiles dnsmasq-base -y

#Add user line to /etc/subuild and /etc/subgid (if it is not already in there).

#Replace username with your username.

sudo su

echo “username:100000:65536” >> /etc/subuild

echo “username:100000:65536” >> /etc/subgid

#Prepare network bridge

sudo su
echo ‘USE_LXC_BRIDGE=”true”‘ > /etc/default/lxc-net
sudo service lxc-net restart
sudo service lxc-net status

#Configure the usernet.

sudo nano /etc/lxc/lxc-usernet

veth lxcbr0 10

#Create LXC configuration(be a normal user here)

mkdir -p ~/.config/lxc
cp /etc/lxc/default.conf ~/.config/lxc/default.conf

#As an example, here is my default.conf file, which you can copy and paste:

lxc.net.0.type = veth
lxc.net.0.link = lxcbr0
lxc.net.0.flags = up
lxc.net.0.hwaddr = 00:16:3e:xx:xx:xx

#I also placed the above configuration entries to /etc/lxc/default.conf (sudo nano /etc/lxc/default.conf)

#Restart LXC networking.

sudo service lxc-net restart

#Check that configuration is valid

sudo lxc-checkconfig

#Create image – using Ubuntu as an example-

sudo lxc-create -t ubuntu -n ubuntu

#man lxc-create – for more flags and options.

#See created containers:

sudo lxc-ls

#Start the ubuntu container

sudo lxc-start -n ubuntu

#Get container info

sudo lxc-info -n ubuntu

………….

Name: ubuntu
State: RUNNING
PID: 30030
IP: 10.0.3.71
CPU use: 0.35 seconds
BlkIO use: 4.00 KiB
Memory use: 18.74 MiB
KMem use: 5.92 MiB
Link: veth2VQ0YW
TX bytes: 1.35 KiB
RX bytes: 1.53 KiB
Total bytes: 2.88 KiB

………….

#Get inside the container.

sudo lxc-attach -n ubuntu

………….

[email protected]:/# apt-get update
Löytyi:1 http://security.ubuntu.com/ubuntu xenial-security InRelease
Löytyi:2 http://archive.ubuntu.com/ubuntu xenial InRelease
Löytyi:3 http://archive.ubuntu.com/ubuntu xenial-updates InRelease
Nouda:4 http://archive.ubuntu.com/ubuntu xenial/main Translation-fi [106 kB]
Nouda:5 http://archive.ubuntu.com/ubuntu xenial/restricted Translation-fi [956 B]
………….

#Stop the container (within another terminal window).

sudo lxc-stop -n ubuntu

#Destroy the container

sudo lxc-destroy -n ubuntu

………….

lxc-destroy: ubuntu: tools/lxc_destroy.c: main: 271 Destroyed container ubuntu