LXC (Linux Containers) 是核心級輕量虛擬化技術,透過 cgroups 限制資源、namespace 隔離視圖,提供接近原生效能的隔離環境。本文涵蓋安裝驗證、容器全生命週期管理、模板使用與網路配置實務。
3.10+ 建議,需啟用 CGROUPS, NAMESPACES, VETH, MACVLAN 等選項。lxc-checkconfig 全部顯示 enabled 即可使用。
# CentOS/RHEL
yum install -y lxc lxc-templates
# Ubuntu/Debian
apt-get update && apt-get install -y lxc lxc-templates
# 啟用服務
systemctl enable --now lxc
# 使用 fedora 模板建立名為 testA 的容器
lxc-create -t fedora -n testA
# 模板位於 /usr/share/lxc/templates/
# 容器根目錄預設在 /var/lib/lxc/testA/
| 操作 | 指令 | 說明 |
|---|---|---|
| 啟動 (前景) | lxc-start -n testA -F | -F 前景模式,可見開機訊息 |
| 啟動 (背景) | lxc-start -n testA -d | -d daemon 模式 |
| 列出容器 | lxc-ls --fancy | 顯示狀態、IP、PID 等 |
| 進入主控台 | lxc-console -n testA | Ctrl+a q 離開 |
| 執行指令 | lxc-attach -n testA -- command | 不進入主控台直接執行 |
| 停止 | lxc-stop -n testA | 優雅關機 |
| 強制終止 | lxc-stop -n testA -k | 發送 SIGKILL |
| 凍結/解凍 | lxc-freeze -n testA / lxc-unfreeze -n testA | 暫停/恢復所有進程 |
| 查看狀態 | lxc-info -n testA | RUNNING/STOPPED/FROZEN |
| 銷毀 | lxc-destroy -n testA | 刪除容器根目錄 |
| 複製 | lxc-clone -o testA -n testB | 快速複製容器 |
| 快照 | lxc-snapshot -n testA | 需 Btrfs/LVM/OverlayFS 支援 |
# /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
# 容器預設連接 lxcbr0,透過 NAT 存取外網
# /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.10/24
lxc.net.0.ipv4.gateway = 10.0.3.1
lxc.net.0.type = macvlan
lxc.net.0.link = eth0
lxc.net.0.macvlan.mode = bridge
lxc.net.0.ipv4.address = 192.168.1.100/24
lxc.net.0.ipv4.gateway = 192.168.1.1
容器直接出現在實體網段,無 NAT 損耗,但宿主機與容器間預設不通 (需額外 macvlan 介面)。
# /var/lib/lxc/testA/config
lxc.cgroup.memory.limit_in_bytes = 512M
lxc.cgroup.memory.memsw.limit_in_bytes = 1G
lxc.cgroup.cpuset.cpus = 0-1
lxc.cgroup.cpu.shares = 512
lxc.cgroup.blkio.throttle.read_bps_device = "8:0 10485760"
lxc.mount.entry = /host/data mnt/data none bind,create=dir 0 0
lxc.mount.entry = /host/app opt/app none bind,ro 0 0
| 現象 | 可能原因 | 解決 |
|---|---|---|
| lxc-start 卡住無訊息 | 缺少 tty 設定 | config 加入 lxc.tty = 4 lxc.pts = 1024 |
| 容器無網路 | 橋接未啟動/防火牆阻擋 | 檢查 brctl show, iptables -L, 重啟 lxc-net |
| 掛載失敗 | 缺少 CAP_SYS_ADMIN | config 加入 lxc.cap.drop = (不丟棄) 或 lxc.cap.keep = CAP_SYS_ADMIN |