LXC (Linux Containers) 是核心級輕量虛擬化技術,透過 cgroups 隔離資源、namespace 隔離視圖,提供接近原生效能的容器環境。本文以 CentOS/RHEL 為例,詳細說明安裝、驗證、建立容器、生命週期管理、網路配置與複製/快照等完整操作流程。

/usr/share/lxc/templates/ 提供各發行版根檔系統建立腳本。yum install lxc* -y
lxc-checkconfig
# 所有項目顯示 "enabled" 即可使用
lxc-create -t fedora -n testA
# 容器根目錄位於 /var/lib/lxc/testA/
| 操作 | 命令 | 說明 |
|---|---|---|
| 啟動(前景) | lxc-start -n testA | 預設進入主控台,Ctrl+a q 脫離 |
| 啟動(背景) | lxc-start -n testA -d | 守護程序模式 |
| 列出所有 | lxc-ls --fancy | 顯示狀態、IP、PID 等 |
| 進入主控台 | lxc-console -n testA -t 3 | -t 指定 tty 數量 |
| 執行命令 | lxc-attach -n testA -- command | 不進入主控台直接執行 |
| 停止 | lxc-stop -n testA | 優雅關機 |
| 強制停止 | lxc-stop -n testA -k | 送 SIGKILL |
| 查看狀態 | lxc-info -n testA | 顯示狀態、PID、資源用量 |
| 銷毀 | lxc-destroy -n testA | 刪除容器根目錄與配置 |
| 凍結 | lxc-freeze -n testA | 暫停所有進程 (cgroups freezer) |
| 恢復 | lxc-unfreeze -n testA | 解除凍結 |
| 複製 | lxc-clone -o testA -n testB | 建立獨立副本 |
| 快照 | lxc-snapshot -n testA | 需 btrfs/LVM/thin pool 支援 |
# 編輯 /etc/default/lxc
USE_LXC_BRIDGE="true"
LXC_BRIDGE="lxcbr0"
LXC_ADDR="10.0.3.1"
LXC_NETMASK="255.255.255.0"
LXC_NETWORK="10.0.3.0/24"
LXC_DHCP_RANGE="10.0.3.2,10.0.3.254"
LXC_DHCP_MAX="253"
# 重啟網路服務
systemctl restart lxc-net
# 編輯 /var/lib/lxc/testA/config
lxc.net.0.type = veth
lxc.net.0.link = lxcbr0
lxc.net.0.flags = up
lxc.net.0.ipv4.address = 10.0.3.100/24
lxc.net.0.ipv4.gateway = 10.0.3.1
lxc.net.0.type = macvlan
lxc.net.0.link = eth0
lxc.net.0.flags = up
lxc.net.0.macvlan.mode = bridge
一般使用者亦可運行容器(無需 root),需設定 /etc/subuid、/etc/subgid 並配置 ~/.config/lxc/default.conf。
LXC 提供輕量、標準化的容器管理介面,適合開發測試、CI/CD、輕量服務隔離。掌握 lxc-create/start/stop/attach/clone/snapshot 等核心命令,配合 cgroups 與網路模型,即可靈活構建容器化環境。生產環境建議搭配 LXD (LXC 管理守護程序) 獲得更佳體驗。