Lessons

LXD System Containers

Level: Advanced Module: Virtualization & Containers 11 min read Lesson 57 of 66

Overview

  • What you’ll learn: How to run full Linux system containers using LXD, including initialization, launching and managing containers, configuring profiles, networking, storage, and creating snapshots for lightweight virtualization.
  • Prerequisites: Virtualization Concepts (Lesson 54), basic Linux command-line skills
  • Estimated reading time: 20 minutes

Introduction

LXD (pronounced “lex-dee”) is a system container manager that provides a user experience similar to virtual machines but with the performance characteristics of containers. Unlike application containers (such as Docker), LXD runs full Linux operating system images complete with init systems, system services, and multiple processes — behaving much like a lightweight virtual machine but sharing the host kernel.

System containers bridge the gap between traditional VMs and application containers. They boot a complete Linux distribution with systemd or another init system, can run multiple services simultaneously, support user management, and behave like independent machines. However, because they share the host kernel and avoid hardware emulation overhead, they start in seconds and consume far fewer resources than full VMs.

In this lesson, you will initialize LXD, launch and manage system containers, configure profiles for consistent container settings, set up networking and storage backends, and use snapshots for backup and cloning workflows.

Installing and Initializing LXD

LXD is distributed as a snap package on Ubuntu, ensuring you always get the latest stable version with automatic updates. The initialization process configures the storage backend, networking, and default settings for your LXD environment.

# Install LXD via snap
$ sudo snap install lxd

# Add your user to the lxd group
$ sudo usermod -aG lxd $USER
$ newgrp lxd

# Initialize LXD interactively
$ lxd init
Would you like to use LXD clustering? (yes/no) [default=no]:
Do you want to configure a new storage pool? (yes/no) [default=yes]:
Name of the new storage pool [default=default]:
Name of the storage backend to use (dir, btrfs, lvm, zfs) [default=zfs]:
Would you like to create a new zfs dataset? (yes/no) [default=yes]:
Would you like to connect to a MAAS server? (yes/no) [default=no]:
Would you like to create a new local network bridge? (yes/no) [default=yes]:
What IPv4 address should be used? (CIDR subnet notation) [default=10.10.10.1/24]:
Would you like LXD to be available over the network? (yes/no) [default=no]:

# Or use preseed for non-interactive setup
$ cat <<EOF | lxd init --preseed
storage_pools:
  - name: default
    driver: zfs
networks:
  - name: lxdbr0
    type: bridge
    config:
      ipv4.address: 10.10.10.1/24
      ipv4.nat: "true"
      ipv6.address: none
profiles:
  - name: default
    devices:
      root:
        path: /
        pool: default
        type: disk
      eth0:
        name: eth0
        network: lxdbr0
        type: nic
EOF

# Verify the installation
$ lxc version
Client version: 5.20
Server version: 5.20

The lxd init command configures the essential infrastructure: a storage pool (ZFS is recommended for its snapshot and copy-on-write capabilities), a network bridge with NAT for container internet access, and the default profile that new containers inherit. The preseed approach is ideal for automated deployments.

Launching and Managing Containers

LXD uses the lxc command-line client to interact with containers. You launch containers from images hosted on remote image servers. The default remote, images:, provides official images for most major Linux distributions.

# List available images from the default remote
$ lxc image list images: ubuntu/22.04 architecture=amd64
+---------------------+--------------+--------+---------------------------+
|        ALIAS        | FINGERPRINT  |  SIZE  |       UPLOAD DATE         |
+---------------------+--------------+--------+---------------------------+
| ubuntu/22.04        | a1b2c3d4e5f6 | 128MB  | Dec 1, 2025 00:00 UTC    |
| ubuntu/22.04/cloud  | f6e5d4c3b2a1 | 150MB  | Dec 1, 2025 00:00 UTC    |
+---------------------+--------------+--------+---------------------------+

# Launch a container
$ lxc launch images:ubuntu/22.04 web-server
Creating web-server
Starting web-server

# List running containers
$ lxc list
+------------+---------+---------------------+------+-----------+
|    NAME    |  STATE  |        IPV4         | TYPE | SNAPSHOTS |
+------------+---------+---------------------+------+-----------+
| web-server | RUNNING | 10.10.10.100 (eth0) | CT   | 0         |
+------------+---------+---------------------+------+-----------+

# Execute commands inside a container
$ lxc exec web-server -- bash
root@web-server:~# cat /etc/os-release
PRETTY_NAME="Ubuntu 22.04 LTS"
root@web-server:~# systemctl status
root@web-server:~# exit

# Execute a single command
$ lxc exec web-server -- apt update
$ lxc exec web-server -- apt install -y nginx

# Push and pull files
$ lxc file push local-config.conf web-server/etc/nginx/conf.d/
$ lxc file pull web-server/var/log/nginx/access.log .

# Stop, start, restart, and delete containers
$ lxc stop web-server
$ lxc start web-server
$ lxc restart web-server
$ lxc delete web-server --force

# View container details
$ lxc info web-server
Name: web-server
Status: RUNNING
Type: container
Architecture: x86_64
PID: 12345
Created: 2025/12/01 10:00 UTC
Processes: 32
Memory (current): 128.50MiB
Memory (peak): 256.00MiB

The lxc launch command downloads the image (if not already cached), creates a container, and starts it in one step. The lxc exec command runs processes inside the container’s namespaces, similar to SSH but without requiring network configuration. File operations with lxc file push/pull transfer files directly between the host and container filesystem.

Profiles and Configuration

Profiles in LXD define reusable sets of configuration options and devices that can be applied to containers. Every container inherits from the default profile, and you can create custom profiles for different workload types.

# View the default profile
$ lxc profile show default
config: {}
description: Default LXD profile
devices:
  eth0:
    name: eth0
    network: lxdbr0
    type: nic
  root:
    path: /
    pool: default
    type: disk
name: default

# Create a custom profile for web servers
$ lxc profile create webserver
$ lxc profile edit webserver
config:
  limits.cpu: "2"
  limits.memory: 1GB
  limits.memory.swap: "false"
  security.nesting: "false"
description: Web server profile
devices:
  root:
    path: /
    pool: default
    size: 10GB
    type: disk
  eth0:
    name: eth0
    network: lxdbr0
    type: nic

# Launch a container with a custom profile
$ lxc launch images:ubuntu/22.04 nginx-01 --profile default --profile webserver

# Apply a profile to an existing container
$ lxc profile add web-server webserver

# Set individual configuration on a container
$ lxc config set web-server limits.cpu 4
$ lxc config set web-server limits.memory 2GB

# View container configuration
$ lxc config show web-server

Profiles are applied in order, with later profiles overriding earlier ones. This layering approach allows you to compose configurations: a default profile provides basic networking and storage, while workload-specific profiles add resource limits and security settings. Individual lxc config set commands override profile values for specific containers.

Networking

LXD provides flexible networking options. The default bridge network gives containers NAT-based internet access. For more advanced setups, you can create multiple networks, use macvlan for direct physical network access, or configure proxy devices for port forwarding.

# List networks
$ lxc network list
+---------+----------+---------+-------------------+---------+
|  NAME   |   TYPE   | MANAGED |   IPV4            |  USED   |
+---------+----------+---------+-------------------+---------+
| lxdbr0  | bridge   | YES     | 10.10.10.1/24     |    3    |
+---------+----------+---------+-------------------+---------+

# View network details
$ lxc network show lxdbr0

# Create an additional bridge network
$ lxc network create internal 
    ipv4.address=172.16.0.1/24 
    ipv4.nat=false 
    ipv6.address=none

# Attach a container to a network
$ lxc network attach internal web-server eth1

# Set up port forwarding with proxy devices
$ lxc config device add web-server http proxy 
    listen=tcp:0.0.0.0:80 
    connect=tcp:127.0.0.1:80

# Assign a static IP to a container
$ lxc config device set web-server eth0 ipv4.address=10.10.10.50

Proxy devices are a powerful feature that forwards traffic from the host to a container without requiring iptables rules. The listen address specifies where to accept connections on the host, and connect specifies where to forward them inside the container.

Snapshots and Backup

LXD supports container snapshots for point-in-time backups and cloning. When using a copy-on-write storage backend like ZFS or btrfs, snapshots are nearly instantaneous and space-efficient.

# Create a snapshot
$ lxc snapshot web-server clean-install
$ lxc snapshot web-server configured --stateful  # includes memory state

# List snapshots
$ lxc info web-server
Snapshots:
  clean-install (taken at 2025/12/01 10:00 UTC) (stateless)
  configured (taken at 2025/12/01 11:00 UTC) (stateful)

# Restore from snapshot
$ lxc restore web-server clean-install

# Create a new container from a snapshot
$ lxc copy web-server/clean-install web-server-clone
$ lxc start web-server-clone

# Export a container for backup
$ lxc export web-server web-server-backup.tar.gz --optimized-storage

# Import from backup
$ lxc import web-server-backup.tar.gz web-server-restored

# Copy a container to a remote LXD server
$ lxc remote add production 192.168.1.100
$ lxc copy web-server production:web-server

Stateful snapshots capture the container’s memory state in addition to the filesystem, allowing you to resume the container exactly where it left off. The lxc copy command creates independent clones, while lxc export/import creates portable backup archives. Remote operations enable migration between LXD hosts.

Key Takeaways

  • LXD provides system containers that run full Linux distributions with init systems and multiple services, offering a VM-like experience with container-level performance and resource efficiency.
  • The lxc command-line client manages the complete container lifecycle: launch, exec, file transfer, stop, delete, and snapshot operations are all straightforward single commands.
  • Profiles define reusable configuration sets including resource limits, storage, and networking that can be layered and applied to multiple containers for consistent environments.
  • LXD networking supports bridge networks with NAT, isolated networks, macvlan direct access, and proxy devices for flexible port forwarding without manual iptables rules.
  • Snapshots provide instant point-in-time captures on copy-on-write backends like ZFS, enabling rapid cloning, backup/restore, and container migration between hosts.

What’s Next

In Lesson 58, you will learn about Docker Fundamentals, which takes a different approach to containerization by focusing on application-level containers with layered images, Dockerfiles for reproducible builds, and container networking for microservices architectures.

繁體中文

概述

  • 學習目標:了解如何使用 LXD 執行完整的 Linux 系統容器,包括初始化、啟動和管理容器、設定配置檔、網路、儲存以及建立快照以實現輕量級虛擬化。
  • 先決條件:虛擬化概念(第 54 課),基本的 Linux 命令列技能
  • 預計閱讀時間:20 分鐘

簡介

LXD(發音為「lex-dee」)是一個系統容器管理器,提供類似虛擬機器的使用者體驗,但具有容器的效能特性。與應用程式容器(如 Docker)不同,LXD 執行完整的 Linux 作業系統映像,包含 init 系統、系統服務和多個行程——行為就像輕量級虛擬機器,但共享主機核心。

系統容器彌合了傳統 VM 和應用程式容器之間的差距。它們使用 systemd 或其他 init 系統啟動完整的 Linux 發行版,可以同時執行多個服務,支援使用者管理,行為就像獨立的機器。然而,因為它們共享主機核心且避免了硬體模擬開銷,它們在幾秒鐘內啟動,資源消耗遠低於完整的 VM。

在本課程中,您將初始化 LXD、啟動和管理系統容器、設定配置檔以實現一致的容器設定、設定網路和儲存後端,以及使用快照進行備份和複製工作流程。

安裝和初始化 LXD

LXD 在 Ubuntu 上以 snap 套件的形式發布,確保您始終獲得具有自動更新功能的最新穩定版本。

# 透過 snap 安裝 LXD
$ sudo snap install lxd

# 將使用者加入 lxd 群組
$ sudo usermod -aG lxd $USER
$ newgrp lxd

# 互動式初始化 LXD
$ lxd init

# 或使用預設種子進行非互動式設定
$ cat <<EOF | lxd init --preseed
storage_pools:
  - name: default
    driver: zfs
networks:
  - name: lxdbr0
    type: bridge
    config:
      ipv4.address: 10.10.10.1/24
      ipv4.nat: "true"
EOF

# 驗證安裝
$ lxc version

啟動和管理容器

LXD 使用 lxc 命令列用戶端與容器互動。您可以從遠端映像伺服器上託管的映像啟動容器。

# 列出可用映像
$ lxc image list images: ubuntu/22.04 architecture=amd64

# 啟動容器
$ lxc launch images:ubuntu/22.04 web-server

# 列出執行中的容器
$ lxc list

# 在容器內執行命令
$ lxc exec web-server -- bash
$ lxc exec web-server -- apt update
$ lxc exec web-server -- apt install -y nginx

# 推送和拉取檔案
$ lxc file push local-config.conf web-server/etc/nginx/conf.d/
$ lxc file pull web-server/var/log/nginx/access.log .

# 停止、啟動、重新啟動和刪除容器
$ lxc stop web-server
$ lxc start web-server
$ lxc restart web-server
$ lxc delete web-server --force

# 查看容器詳細資訊
$ lxc info web-server

配置檔和設定

LXD 中的配置檔定義了可套用於容器的可重複使用配置選項和裝置集。每個容器都繼承自預設配置檔,您可以為不同的工作負載類型建立自訂配置檔。

# 查看預設配置檔
$ lxc profile show default

# 為網頁伺服器建立自訂配置檔
$ lxc profile create webserver
$ lxc profile edit webserver
config:
  limits.cpu: "2"
  limits.memory: 1GB
description: Web server profile

# 使用自訂配置檔啟動容器
$ lxc launch images:ubuntu/22.04 nginx-01 --profile default --profile webserver

# 設定個別容器配置
$ lxc config set web-server limits.cpu 4
$ lxc config set web-server limits.memory 2GB

網路

LXD 提供靈活的網路選項。預設橋接網路為容器提供基於 NAT 的網際網路存取。對於更進階的設定,您可以建立多個網路、使用 macvlan 進行直接實體網路存取,或設定代理裝置進行連接埠轉發。

# 列出網路
$ lxc network list

# 建立額外的橋接網路
$ lxc network create internal 
    ipv4.address=172.16.0.1/24 
    ipv4.nat=false

# 將容器附加到網路
$ lxc network attach internal web-server eth1

# 使用代理裝置設定連接埠轉發
$ lxc config device add web-server http proxy 
    listen=tcp:0.0.0.0:80 
    connect=tcp:127.0.0.1:80

# 為容器指定靜態 IP
$ lxc config device set web-server eth0 ipv4.address=10.10.10.50

快照和備份

LXD 支援容器快照,用於時間點備份和複製。使用 ZFS 或 btrfs 等寫時複製儲存後端時,快照幾乎是即時且節省空間的。

# 建立快照
$ lxc snapshot web-server clean-install
$ lxc snapshot web-server configured --stateful

# 從快照還原
$ lxc restore web-server clean-install

# 從快照建立新容器
$ lxc copy web-server/clean-install web-server-clone
$ lxc start web-server-clone

# 匯出容器進行備份
$ lxc export web-server web-server-backup.tar.gz

# 從備份匯入
$ lxc import web-server-backup.tar.gz web-server-restored

# 複製容器到遠端 LXD 伺服器
$ lxc remote add production 192.168.1.100
$ lxc copy web-server production:web-server

重點摘要

  • LXD 提供執行完整 Linux 發行版的系統容器,具有 init 系統和多個服務,提供類似 VM 的體驗,但具有容器級別的效能和資源效率。
  • lxc 命令列用戶端管理完整的容器生命週期:啟動、執行、檔案傳輸、停止、刪除和快照操作都是簡單的單一命令。
  • 配置檔定義了可重複使用的配置集,包括資源限制、儲存和網路,可以分層套用於多個容器以實現一致的環境。
  • LXD 網路支援具有 NAT 的橋接網路、隔離網路、macvlan 直接存取和代理裝置,實現靈活的連接埠轉發。
  • 快照在 ZFS 等寫時複製後端上提供即時的時間點擷取,實現快速複製、備份/還原和主機之間的容器遷移。

下一步

在第 58 課中,您將學習 Docker 基礎,它透過專注於具有分層映像的應用程式級容器、用於可重現建構的 Dockerfile 以及用於微服務架構的容器網路,採取不同的容器化方法。

日本語

概要

  • 学習内容:LXD を使用した完全な Linux システムコンテナの実行方法。初期化、コンテナの起動と管理、プロファイルの構成、ネットワーキング、ストレージ、軽量仮想化のためのスナップショット作成を含みます。
  • 前提条件:仮想化の概念(レッスン54)、基本的な Linux コマンドラインスキル
  • 推定読了時間:20分

はじめに

LXD(「レックスディー」と発音)は、仮想マシンに似たユーザー体験を提供しつつ、コンテナのパフォーマンス特性を持つシステムコンテナマネージャーです。アプリケーションコンテナ(Docker など)とは異なり、LXD は init システム、システムサービス、複数のプロセスを含む完全な Linux オペレーティングシステムイメージを実行します。軽量な仮想マシンのように振る舞いますが、ホストカーネルを共有します。

システムコンテナは従来の VM とアプリケーションコンテナの間のギャップを埋めます。systemd などの init システムで完全な Linux ディストリビューションを起動し、複数のサービスを同時に実行でき、ユーザー管理をサポートし、独立したマシンのように振る舞います。しかし、ホストカーネルを共有しハードウェアエミュレーションのオーバーヘッドを回避するため、数秒で起動し、完全な VM よりもはるかに少ないリソースを消費します。

このレッスンでは、LXD の初期化、システムコンテナの起動と管理、一貫したコンテナ設定のためのプロファイル構成、ネットワーキングとストレージバックエンドのセットアップ、バックアップとクローニングワークフローのためのスナップショットの使用を学びます。

LXD のインストールと初期化

LXD は Ubuntu では snap パッケージとして配布され、自動更新機能付きの最新安定版が常に入手できます。

# snap 経由で LXD をインストール
$ sudo snap install lxd

# ユーザーを lxd グループに追加
$ sudo usermod -aG lxd $USER
$ newgrp lxd

# LXD をインタラクティブに初期化
$ lxd init

# または preseed で非インタラクティブにセットアップ
$ cat <<EOF | lxd init --preseed
storage_pools:
  - name: default
    driver: zfs
networks:
  - name: lxdbr0
    type: bridge
    config:
      ipv4.address: 10.10.10.1/24
      ipv4.nat: "true"
EOF

# インストールを確認
$ lxc version

コンテナの起動と管理

LXD は lxc コマンドラインクライアントを使用してコンテナと対話します。リモートイメージサーバーでホストされているイメージからコンテナを起動します。

# 利用可能なイメージを一覧表示
$ lxc image list images: ubuntu/22.04 architecture=amd64

# コンテナを起動
$ lxc launch images:ubuntu/22.04 web-server

# 実行中のコンテナを一覧表示
$ lxc list

# コンテナ内でコマンドを実行
$ lxc exec web-server -- bash
$ lxc exec web-server -- apt update
$ lxc exec web-server -- apt install -y nginx

# ファイルのプッシュとプル
$ lxc file push local-config.conf web-server/etc/nginx/conf.d/
$ lxc file pull web-server/var/log/nginx/access.log .

# 停止、起動、再起動、削除
$ lxc stop web-server
$ lxc start web-server
$ lxc restart web-server
$ lxc delete web-server --force

# コンテナの詳細を表示
$ lxc info web-server

プロファイルと構成

LXD のプロファイルは、コンテナに適用できる再利用可能な構成オプションとデバイスのセットを定義します。すべてのコンテナはデフォルトプロファイルを継承し、異なるワークロードタイプ用のカスタムプロファイルを作成できます。

# デフォルトプロファイルを表示
$ lxc profile show default

# Web サーバー用のカスタムプロファイルを作成
$ lxc profile create webserver
$ lxc profile edit webserver
config:
  limits.cpu: "2"
  limits.memory: 1GB
description: Web server profile

# カスタムプロファイルでコンテナを起動
$ lxc launch images:ubuntu/22.04 nginx-01 --profile default --profile webserver

# 個別のコンテナ構成を設定
$ lxc config set web-server limits.cpu 4
$ lxc config set web-server limits.memory 2GB

ネットワーキング

LXD は柔軟なネットワーキングオプションを提供します。デフォルトのブリッジネットワークはコンテナに NAT ベースのインターネットアクセスを提供します。より高度なセットアップでは、複数のネットワークの作成、物理ネットワークへの直接アクセス用の macvlan、ポートフォワーディング用のプロキシデバイスを構成できます。

# ネットワークを一覧表示
$ lxc network list

# 追加のブリッジネットワークを作成
$ lxc network create internal 
    ipv4.address=172.16.0.1/24 
    ipv4.nat=false

# コンテナをネットワークにアタッチ
$ lxc network attach internal web-server eth1

# プロキシデバイスでポートフォワーディングを設定
$ lxc config device add web-server http proxy 
    listen=tcp:0.0.0.0:80 
    connect=tcp:127.0.0.1:80

# コンテナに静的 IP を割り当て
$ lxc config device set web-server eth0 ipv4.address=10.10.10.50

スナップショットとバックアップ

LXD はポイントインタイムバックアップとクローニングのためのコンテナスナップショットをサポートします。ZFS や btrfs などのコピーオンライトストレージバックエンドを使用する場合、スナップショットはほぼ瞬時で省スペースです。

# スナップショットを作成
$ lxc snapshot web-server clean-install
$ lxc snapshot web-server configured --stateful

# スナップショットから復元
$ lxc restore web-server clean-install

# スナップショットから新しいコンテナを作成
$ lxc copy web-server/clean-install web-server-clone
$ lxc start web-server-clone

# コンテナをバックアップ用にエクスポート
$ lxc export web-server web-server-backup.tar.gz

# バックアップからインポート
$ lxc import web-server-backup.tar.gz web-server-restored

# コンテナをリモート LXD サーバーにコピー
$ lxc remote add production 192.168.1.100
$ lxc copy web-server production:web-server

重要ポイント

  • LXD は init システムと複数のサービスを持つ完全な Linux ディストリビューションを実行するシステムコンテナを提供し、VM のような体験とコンテナレベルのパフォーマンスとリソース効率を実現します。
  • lxc コマンドラインクライアントは完全なコンテナライフサイクルを管理します:起動、実行、ファイル転送、停止、削除、スナップショット操作はすべて簡単なコマンドです。
  • プロファイルは、リソース制限、ストレージ、ネットワーキングを含む再利用可能な構成セットを定義し、一貫した環境のために複数のコンテナにレイヤー化して適用できます。
  • LXD ネットワーキングは NAT 付きブリッジネットワーク、分離ネットワーク、macvlan ダイレクトアクセス、柔軟なポートフォワーディングのためのプロキシデバイスをサポートします。
  • スナップショットは ZFS などのコピーオンライトバックエンドで瞬時のポイントインタイムキャプチャを提供し、高速なクローニング、バックアップ/リストア、ホスト間のコンテナマイグレーションを可能にします。

次のステップ

レッスン58では、Docker の基礎について学びます。レイヤードイメージによるアプリケーションレベルのコンテナ、再現可能なビルドのための Dockerfile、マイクロサービスアーキテクチャのためのコンテナネットワーキングに焦点を当てた、異なるコンテナ化アプローチを学びます。

You Missed