Using LXD

Posted on: by

Whether to use LXD or Docker is like asking if you should use spaces or tabs. For me, I find LXD easier to wrap my head around in order to spin up a quick container. If you are using Ubuntu server 20.04 LXD comes pre-installed which makes it an easy choice.

Spinning up a new instance is simple three step process. First, initialize lxd and, unless you know you need something different, just accept the defaults.

#lxd init

Second, decide what Linux flavor you want to run in the container – in this example I will spin up an Ubuntu 20.04 container.

#lxc launch ubuntu:20.04 [<container name>]

The container name is optional. If it isn’t specified the container will have a random name assigned to it.

Finally, start the container and get a bash shell to run commands in.

#lxc exec <container name> -- /bin/bash

LXD is incredibly lightweight and you can run many LXD containers without impacting your system.

At this point you can provision your system to run whatever application you want. It can be configured by hand or you can use Ansible, etc. to provision it. The next step is to connect to the container from the network. By default, LXD containers are accessible from the localhost only. All that needs to happen is to configure a proxy between the host OS and the container.

In this example I will assume you want to connect to the container on port 80.

#lxc config device add <container name> <proxy name> proxy listen tcp: connect=tcp:

To start and stop the container is fairly simple:

#lxc start <container name>
#lxc stop <container name>

One of the benefits of a container, besides the obvious containment advantage, is that it is pretty easy to constrain the resources that the container has access to. For instance, to limit a container to 1GB of RAM:

#lxc config set <containter name> limits.memory 1024MB

Limiting CPU is just as simple but you have 4 different ways to do this and I have found this article that does a good job of going through each different option very well.

One of the other common things you might like to do with a container is share a folder between the host and container. This is done using this command:

#lxc config device add <container name> <share name> disk source=<host path> path=<container path>

If you are looking for a simple way to get started with containers LXD is a good starting point.