Ubuntu 24.04 LXC Basic's: Difference between revisions

From CompleteNoobs
Jump to navigation Jump to search
(Created page with "= Quick Start Guide: Ubuntu LXC Containers for CompleteNoobs = NOTES - lost all notes on localwiki when i did bad backup before nuke and pave, starting again. == Introduction == This guide will help you get started with LXC (Linux Containers) on Ubuntu. We'll cover how to login to a container, run commands from the host on the container, and move files between the host and container. == Prerequisites == * Ubuntu system with LXC installed * Basic knowledge of terminal...")
 
Line 364: Line 364:


This creates a compressed tarball of the snapshot that you can store elsewhere.
This creates a compressed tarball of the snapshot that you can store elsewhere.
===Clone/Copy a Snapshot===
This section describes how to create an Ubuntu 18.04 build container using LXD, install dependencies, snapshot it, and clone the snapshot into a new container.
* Create the Build Container 
Launch an Ubuntu 18.04 container named `1804build`:  <br>
<code>lxc launch ubuntu:18.04 1804build</code>
* Install Dependencies
Access the container and install required packages:  <br>
<code>lxc exec 1804build bash</code>  <br>
Inside, run:  <br>
<code>apt update && apt install build-essential</code>  <br>
Install all other packages and exit when done.
* Stop the Container to prepare for snapshotting
<code>lxc stop 1804build</code>
* Create a Snapshot named `one`
<code>lxc snapshot 1804build one</code>
* Clone the Snapshot - Copy the snapshot `one` to a new container called `newbuild1`
<code>lxc copy 1804build/one newbuild1</code>
* Start and Verify
Start the new container:  <br>
<code>lxc start newbuild1</code> 
Check it’s running and has the dependencies: <br>
<code>lxc exec newbuild1 bash</code>
The new container `newbuild1` is now a fully independent copy of the `1804build` state at the `one` snapshot, ready for builds.


===Compare the snapshots and see what has changed between them===
===Compare the snapshots and see what has changed between them===

Revision as of 09:44, 2 April 2025

Quick Start Guide: Ubuntu LXC Containers for CompleteNoobs

NOTES - lost all notes on localwiki when i did bad backup before nuke and pave, starting again.

Introduction

This guide will help you get started with LXC (Linux Containers) on Ubuntu. We'll cover how to login to a container, run commands from the host on the container, and move files between the host and container.

Prerequisites

  • Ubuntu system with LXC installed
  • Basic knowledge of terminal commands

Installing LXD

lxd comes preinstalled with ubuntu 24.04

  • check current version

sudo lxd --version
Output:

root@lxd-test:~# lxd --version
5.21.2 LTS
  • update snap package info

sudo snap refresh --list

  • check if updated version avalible.

snap search

root@lxd-test:~# snap search lxd
Name                      Version         Publisher       Notes    Summary
lxd                       5.21.2-34459c8  canonical✓      -        LXD - container and VM manager
lxd-bgp                   0+git.a39f061   stgraber        -        BGP server that exposes LXD routes
lxd-demo-server           0+git.6d54658   tomparrott      -        Online software demo sessions using LXD
lxd-imagebuilder          git-22d1484     tomparrott      classic  System container and VM image builder for LXD
lxdmosaic                 0+git.c6f53f3f  turtle0x1       -        A web interface to manage multiple instances of LXD
lxd-gitlab-runner         0.1             alexclewontin   -        GitLab CI/CD runner with built in LXD executor
microcloud                1.1-04a1c49     canonical✓      -        Automated small-scale cloud deployment
prometheus-juju-exporter  3.1.0           canonical✓      -        Prometheus exporter for Juju machine statuses
ghvmctl                   0.4.1           snapcrafters✪   -        A utility for manipulating virtual machines during snap testing.
fabrica                   1.1.0           ogra            -        Build snaps by simply pointing a web form to a git tree
pluto                     0.1.0           nuccitheboss    -        A swiss-army knife for managing HPC clusters built with Ubuntu
hon-lxd-toolbox           0.7.40.21-b     h350730         -        Swiss knife of shell tools
distrobuilder             3.0             stgraber        classic  Image builder for LXC and LXD
satellite                 0.1.2           alanzanattadev  -        Advanced scalable Open source intelligence platform


All upto date already, but if was not then

  • update lxd

sudo snap refresh lxd

  • check version is

snap info lxd
lxd --version

Upgrading to Specific Channels (Optional):

LXD can be upgraded to specific versions or channels. This allows you to choose between stability and newer features. The available channels are:

  • latest/stable: The most stable release, recommended for production environments
  • latest/candidate: Release candidates, for testing before they become stable
  • latest/beta: Beta versions, may contain bugs but offer newer features
  • latest/edge: The most recent updates, potentially unstable

To upgrade LXD to a specific channel, use the following command:

sudo snap refresh lxd --channel=CHANNEL_NAME

For example, to upgrade to the stable channel:

sudo snap refresh lxd --channel=latest/stable

Or, to switch to the candidate channel:

sudo snap refresh lxd --channel=latest/candidate
  • Restarting LXD After Updates (Optional)

After upgrading LXD, it's sometimes necessary to restart the LXD daemon to apply changes. You can do this with the following command:

sudo systemctl restart snap.lxd.daemon

This ensures that LXD is running the most recently installed version.

Add user to the lxc group

Adding a User to the LXC Group

To manage LXC containers without using `sudo`, add your user to the `lxd` group.

Add the user to the `lxd` group:

sudo adduser $USER lxd

Check user in group Using id Command

You can use the id command, which shows the user's identity and associated groups:

id $USER

This will display something like:

uid=1000(username) gid=1000(username) groups=1000(username),4(adm),27(sudo),109(lxd)

Here, 109(lxd) indicates that the user is part of the lxd group.

LXD Initialization

Its pretty straight forward:
sudo lxd init

Launching First container

lxc launch ubuntu:18.04 cnoobs

  • IF you see:
lxc launch ubuntu:18.04 cnoobs
Error: LXD unix socket "/var/snap/lxd/common/lxd/unix.socket" not accessible: permission denied
  • REBOOT to apply changes
  • OR logout and backin to apply changes

a way to apply group changes without logging out and back in - tip

On Ubuntu 24.04 using Bash, you can use the newgrp command. Here's how you can do it:

  • First, add your user to the lxd group:
sudo adduser $USER lxd

Then, to apply the changes immediately without logging out, use:

newgrp lxd

The newgrp command starts a new shell session with the updated group membership. This allows you to immediately use the permissions granted by the new group without logging out and back in. Alternatively, you can also use:

exec sudo su -l $USER

This command will replace your current shell with a new login shell for your user, which will have the updated group memberships. Both of these methods will apply the group changes immediately, allowing you to use LXD commands without having to log out and back in. Remember, these changes only apply to the current terminal session. If you open a new terminal window, you might need to run the command again or log out and back in for the changes to take effect system-wide.

  • syntax <command> <image> <container_name>

lxc launch ubuntu:18.04 cnoobs - explained

To create and start your first LXC container, use the following command:

lxc launch ubuntu:18.04 cnoobs

This command does the following:

  • lxc launch: Tells LXD to create and start a new container
  • ubuntu:18.04: Specifies the image to use (Ubuntu 18.04 in this case)
  • cnoobs: This is the name you're giving to your new container

After running this command, LXD will download the Ubuntu 18.04 image (if it hasn't already) and create a new container named "cnoobs" based on this image.

To see other available images, you can use:

lxc image list images:

This will show a list of available images from the default remote. You can also specify different versions or distributions, for example:

  • lxc launch ubuntu:20.04 mycontainer for Ubuntu 20.04
  • lxc launch debian:10 mydebian for Debian 10
  • lxc launch centos:8 mycentos for CentOS 8

To get more detailed information about available images, use:

lxc image list images: | grep -i ubuntu

Replace "ubuntu" with any other distribution name to see its available versions.

Remember, the container name (like "cnoobs" in the example) must be unique within your LXD installation.

Logging into the Container

Method 1: Using lxc exec

To log into the container directly:

lxc exec cnoobs -- bash

This command gives you a bash shell inside the container.

Method 2: Using SSH

If you prefer using SSH:

1. Install SSH in the container: lxc exec cnoobs -- apt update lxc exec cnoobs -- apt install openssh-server -y

2. Set a password for the ubuntu user: lxc exec cnoobs -- passwd ubuntu

3. Get the container's IP address: lxc list cnoobs

4. SSH into the container: ssh ubuntu@<container_ip>

Running Commands from Host on Container

To run a command in the container from the host system, use:

lxc exec cnoobs -- <command>

For example, to list files in the container's home directory:

lxc exec cnoobs -- ls /home/ubuntu

Moving Files and Directories

From Host to Container

Use the `lxc file push` command:

lxc file push /path/on/host/file.txt cnoobs/path/in/container/

For example, to copy a file to the ubuntu user's home directory:

lxc file push ~/myfile.txt cnoobs/home/ubuntu/

From Container to Host

Use the `lxc file pull` command:

lxc file pull cnoobs/path/in/container/file.txt /path/on/host/

For example, to copy a file from the container's home directory to the host's current directory:

lxc file pull cnoobs/home/ubuntu/myfile.txt ./

Moving Directories

To move entire directories, add the -r (recursive) flag:

lxc file push -r ~/mydir cnoobs/home/ubuntu/
lxc file pull -r cnoobs/home/ubuntu/mydir ./

Snapshot and restore containers

If ZFS as the underlying storage driver

Snapshot a Container

To create a snapshot of a container, use the following command: lxc snapshot <container_name> <snapshot_name>

  • <container_name>: Replace this with the name of the container you want to snapshot.
  • <snapshot_name>: Replace this with a descriptive name for the snapshot.

Example:

lxc snapshot cnoobs snapshot1

This command creates a snapshot named snapshot1 of the container cnoobs.

List Snapshots

To view the snapshots for a specific container, you can use:

lxc info <container_name>

or more specifically for snapshots:

lxc snapshot list <container_name>


Restore a Snapshot

If you need to restore a container to a previous state using a snapshot, use the following command:

lxc restore <container_name> <snapshot_name>

  • <container_name>: The name of the container you want to restore.
  • <snapshot_name>: The name of the snapshot to which you want to revert.

Example:

lxc restore cnoobs snapshot1 This command will revert the container cnoobs to the state it was in when the snapshot1 snapshot was taken.


Delete a Snapshot

Once you no longer need a snapshot, you can delete it to free up space:

lxc delete <container_name>/<snapshot_name> Example:

lxc delete cnoobs/snapshot1

This command deletes the snapshot1 snapshot of the cnoobs container.

Backing Up a Snapshot

If you want to create a backup of the snapshot outside of LXD (for example, to transfer to another system), you can export it:

lxc export <container_name> --instance-only --snapshot <snapshot_name> <output_file.tar.gz>

Example:

lxc export mycontainer --instance-only --snapshot snapshot1 mycontainer-snapshot1.tar.gz

This creates a compressed tarball of the snapshot that you can store elsewhere.

Clone/Copy a Snapshot

This section describes how to create an Ubuntu 18.04 build container using LXD, install dependencies, snapshot it, and clone the snapshot into a new container.

  • Create the Build Container

Launch an Ubuntu 18.04 container named `1804build`:
lxc launch ubuntu:18.04 1804build

  • Install Dependencies

Access the container and install required packages:
lxc exec 1804build bash
Inside, run:
apt update && apt install build-essential
Install all other packages and exit when done.

  • Stop the Container to prepare for snapshotting

lxc stop 1804build

  • Create a Snapshot named `one`

lxc snapshot 1804build one

  • Clone the Snapshot - Copy the snapshot `one` to a new container called `newbuild1`

lxc copy 1804build/one newbuild1

  • Start and Verify

Start the new container:
lxc start newbuild1 Check it’s running and has the dependencies:
lxc exec newbuild1 bash

The new container `newbuild1` is now a fully independent copy of the `1804build` state at the `one` snapshot, ready for builds.

Compare the snapshots and see what has changed between them

On host zfsutils-linux required

sudo apt install zfsutils-linux

Get the ZFS Dataset Names for the Snapshots

LXD snapshots are stored as ZFS datasets. First, you need to identify the ZFS dataset names associated with your LXD container snapshots.

zfs list -t snapshot | grep <container_name>

This will list all ZFS snapshots related to your container.

Diff the Snapshots Using ZFS

Once you have the snapshot names, you can use zfs diff to see the differences between two snapshots. The zfs diff command shows changes such as file creations, deletions, and modifications between two snapshots.

zfs diff <snapshot1> <snapshot2>

Example Workflow

Let's assume your container is named mycontainer, and you have two snapshots snapshot1 and snapshot2. Here's how you would do it:

  • List the ZFS Snapshots:

zfs list -t snapshot | grep mycontainer

You might see output like this:

tank/containers/mycontainer@snapshot1
tank/containers/mycontainer@snapshot2

Diff the Snapshots:

zfs diff tank/containers/mycontainer@snapshot1 tank/containers/mycontainer@snapshot2

This command will output the differences between the two snapshots. The output might look like this:

M   /path/to/modified/file
-   /path/to/deleted/file
+   /path/to/added/file
R   /path/to/renamed/file -> /path/to/newname/file
M: Modified files
-: Deleted files
+: Added files
R: Renamed files

Interpreting the Output

The output will show you which files have been added, removed, or modified between the two snapshots. If you're comparing entire directories or larger datasets, this can give you a quick overview of what's changed.

Notes:

  • ZFS Tools Required: The zfs diff command is a ZFS feature, so you need to have ZFS installed and configured.
  • Permissions: Ensure you have sufficient permissions to view and compare the datasets.
  • Efficiency: zfs diff is generally efficient but might take time depending on the size and number of changes between the snapshots.

Limit CPU and RAM per container can use

In Ubuntu 24.04, you can limit the CPU and RAM usage of an LXC (Linux Containers) container using the built-in resource control features provided by LXC.

Limiting CPU Usage

You can limit the CPU usage of an LXC container in two ways: by specifying the number of CPU cores the container can use, and by setting a CPU usage limit as a percentage of the host's total CPU resources.

  • Limit CPU Cores:

You can assign specific CPU cores to a container by editing the container's configuration file.


lxc-cgroup -n <container-name> cpuset.cpus <cpu-cores>


For example, to assign CPU cores 0 and 1 to a container:


lxc-cgroup -n my-container cpuset.cpus 0,1


Alternatively, you can add the following line to the container’s configuration file (usually found in /var/lib/lxc/<container-name>/config):

lxc.cgroup.cpuset.cpus = 0,1

  • Limit CPU Usage

You can limit the CPU usage as a percentage of the host’s total CPU time.

lxc-cgroup -n <container-name> cpu.shares <value>

For example, to limit the CPU usage to 20%:

lxc.cgroup.cpu.shares = 204

This value is relative to the CPU shares of other containers. The default value is 1024, so 204 is about 20% of one CPU.

Limiting RAM Usage

You can also limit the amount of RAM a container can use.

  • Limit Memory:

To set a hard limit on the maximum amount of RAM a container can use, add the following line to the container’s configuration file:

lxc.cgroup.memory.limit_in_bytes = 512M


This example limits the container to 512 MB of RAM.

  • Limit Swap Usage:

You can also limit the amount of swap memory a container can use:

lxc.cgroup.memory.memsw.limit_in_bytes = 1G


This example limits the total memory usage (RAM + swap) to 1 GB.

Applying the Changes

After editing the configuration file, restart the container to apply the changes:

lxc-stop -n <container-name>
lxc-start -n <container-name>

References

This wiki-formatted tutorial provides a quick start guide for CompleteNoobs to work with LXC containers on Ubuntu. It covers the basics of logging in, running commands, and moving files, which are essential operations for beginners working with containers.