LXC (Linux Containers) 採用核心級虛擬化,效能損耗極低、無指令模擬開銷。本文示範如何從零建立 LXC 專用 rootfs:建立目錄結構、配置掛載表 (fstab)、編寫設定檔、啟動容器並驗證隔離環境。

mkdir -p /lxc/rootfs
cd /lxc/rootfs
mkdir -p bin dev etc lib lib64 proc sbin sys usr var
/lxc/fstab採用 **bind mount** 方式共享宿主機系統目錄 (唯讀),僅 /dev、/dev/pts 可讀寫,/proc、/sys 掛載虛擬檔案系統:
# /lxc/fstab
/bin /lxc/rootfs/bin none ro,bind 0 0
/sbin /lxc/rootfs/sbin none ro,bind 0 0
/lib /lxc/rootfs/lib none ro,bind 0 0
/lib64 /lxc/rootfs/lib64 none ro,bind 0 0
/etc /lxc/rootfs/etc none ro,bind 0 0
/usr /lxc/rootfs/usr none ro,bind 0 0
/dev /lxc/rootfs/dev none rw,bind 0 0
/dev/pts /lxc/rootfs/dev/pts none rw,bind 0 0
/proc /lxc/rootfs/proc proc defaults 0 0
/sys /lxc/rootfs/sys sysfs defaults 0 0
/lxc/config
lxc.utsname = host_name
lxc.rootfs = /lxc/rootfs
lxc.mount = /lxc/fstab
# 可選:網路、cgroup 限制等
# lxc.network.type = veth
# lxc.network.link = br0
# lxc.cgroup.memory.limit_in_bytes = 512M
lxc-execute -n lxc1 -f /lxc/config bash
# -n 容器名稱
# -f 設定檔路徑
# bash 為啟動指令 (進入容器 Shell)
若終端顯示異常,執行 reset 恢復。
bash-4.1# ls /
bin data dev etc lib lib64 proc sbin sys usr var
/lxc/rootfs 內容/etc/hostname 不影響宿主機ps aux 僅顯示容器內進程 (PID namespace 隔離)上述為**共享宿主機目錄**的輕量模式。生產環境通常需要**獨立完整 Rootfs**:
debootstrap --arch=amd64 focal /lxc/rootfs-full https://archive.ubuntu.com/ubuntu/
# 產生完整 Ubuntu 20.04 rootfs
docker run -d --name temp ubuntu:20.04 sleep infinity
docker export temp | tar -x -C /lxc/rootfs-docker
docker rm -f temp
lxc.include = /usr/share/lxc/config/common.conf
lxc.arch = linux64
lxc.rootfs.path = dir:/lxc/rootfs
lxc.uts.name = mycontainer
lxc.mount.auto = proc:rw sys:rw cgroup:mixed
lxc.mount.entry = /bin bin none ro,bind 0 0
lxc.mount.entry = /usr usr none ro,bind 0 0
# ... 其他掛載點
| 現象 | 解決 |
|---|---|
| 容器內無法解析域名 | 複製宿主機 /etc/resolv.conf 至 /lxc/rootfs/etc/ |
| 權限拒絕 | 檢查 /dev、/dev/pts 掛載選項含 rw |
| 系統呼叫被阻擋 | 調整 lxc.seccomp 規則或停用 |
掌握 Rootfs 製作與 LXC 設定,即可輕量級部署隔離應用環境,效能接近原生、啟動秒級完成。