Ubuntu 24.04 LXC Basic's
Please Select a Licence from the LICENCE_HEADERS page |
And place at top of your page |
If no Licence is Selected/Appended, Default will be CC0 Default Licence IF there is no Licence placed below this notice!
When you edit this page, you agree to release your contribution under the CC0 Licence LICENCE:
More information about the cc0 licence can be found here: You can copy, modify, distribute and perform the work, even for commercial purposes, all without asking permission. Licence: Statement of Purpose The laws of most jurisdictions throughout the world automatically confer exclusive Copyright and Related Rights (defined below) upon the creator and subsequent owner(s) (each and all, an "owner") of an original work of authorship and/or a database (each, a "Work"). Certain owners wish to permanently relinquish those rights to a Work for the purpose of contributing to a commons of creative, cultural and scientific works ("Commons") that the public can reliably and without fear of later claims of infringement build upon, modify, incorporate in other works, reuse and redistribute as freely as possible in any form whatsoever and for any purposes, including without limitation commercial purposes. These owners may contribute to the Commons to promote the ideal of a free culture and the further production of creative, cultural and scientific works, or to gain reputation or greater distribution for their Work in part through the use and efforts of others. For these and/or other purposes and motivations, and without any expectation of additional consideration or compensation, the person associating CC0 with a Work (the "Affirmer"), to the extent that he or she is an owner of Copyright and Related Rights in the Work, voluntarily elects to apply CC0 to the Work and publicly distribute the Work under its terms, with knowledge of his or her Copyright and Related Rights in the Work and the meaning and intended legal effect of CC0 on those rights. 1. Copyright and Related Rights. A Work made available under CC0 may be protected by copyright and related or neighboring rights ("Copyright and Related Rights"). Copyright and Related Rights include, but are not limited to, the following: the right to reproduce, adapt, distribute, perform, display, communicate, and translate a Work; moral rights retained by the original author(s) and/or performer(s); publicity and privacy rights pertaining to a person's image or likeness depicted in a Work; rights protecting against unfair competition in regards to a Work, subject to the limitations in paragraph 4(a), below; rights protecting the extraction, dissemination, use and reuse of data in a Work; database rights (such as those arising under Directive 96/9/EC of the European Parliament and of the Council of 11 March 1996 on the legal protection of databases, and under any national implementation thereof, including any amended or successor version of such directive); and other similar, equivalent or corresponding rights throughout the world based on applicable law or treaty, and any national implementations thereof. 2. Waiver. To the greatest extent permitted by, but not in contravention of, applicable law, Affirmer hereby overtly, fully, permanently, irrevocably and unconditionally waives, abandons, and surrenders all of Affirmer's Copyright and Related Rights and associated claims and causes of action, whether now known or unknown (including existing as well as future claims and causes of action), in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each member of the public at large and to the detriment of Affirmer's heirs and successors, fully intending that such Waiver shall not be subject to revocation, rescission, cancellation, termination, or any other legal or equitable action to disrupt the quiet enjoyment of the Work by the public as contemplated by Affirmer's express Statement of Purpose. 3. Public License Fallback. Should any part of the Waiver for any reason be judged legally invalid or ineffective under applicable law, then the Waiver shall be preserved to the maximum extent permitted taking into account Affirmer's express Statement of Purpose. In addition, to the extent the Waiver is so judged Affirmer hereby grants to each affected person a royalty-free, non transferable, non sublicensable, non exclusive, irrevocable and unconditional license to exercise Affirmer's Copyright and Related Rights in the Work (i) in all territories worldwide, (ii) for the maximum duration provided by applicable law or treaty (including future time extensions), (iii) in any current or future medium and for any number of copies, and (iv) for any purpose whatsoever, including without limitation commercial, advertising or promotional purposes (the "License"). The License shall be deemed effective as of the date CC0 was applied by Affirmer to the Work. Should any part of the License for any reason be judged legally invalid or ineffective under applicable law, such partial invalidity or ineffectiveness shall not invalidate the remainder of the License, and in such case Affirmer hereby affirms that he or she will not (i) exercise any of his or her remaining Copyright and Related Rights in the Work or (ii) assert any associated claims and causes of action with respect to the Work, in either case contrary to Affirmer's express Statement of Purpose. 4. Limitations and Disclaimers. No trademark or patent rights held by Affirmer are waived, abandoned, surrendered, licensed or otherwise affected by this document. Affirmer offers the Work as-is and makes no representations or warranties of any kind concerning the Work, express, implied, statutory or otherwise, including without limitation warranties of title, merchantability, fitness for a particular purpose, non infringement, or the absence of latent or other defects, accuracy, or the present or absence of errors, whether or not discoverable, all to the greatest extent permissible under applicable law. Affirmer disclaims responsibility for clearing rights of other persons that may apply to the Work or any use thereof, including without limitation any person's Copyright and Related Rights in the Work. Further, Affirmer disclaims responsibility for obtaining any necessary consents, permissions or other rights required for any use of the Work. Affirmer understands and acknowledges that Creative Commons is not a party to this document and has no duty or obligation with respect to this CC0 or use of the Work. |
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.04lxc launch debian:10 mydebian
for Debian 10lxc 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.
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.