Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> 關於 Linux

Linux 容器技術 LXC 安裝部署完整指南:從建立到網路配置

編輯:關於 Linux

LXC (Linux Containers) 是核心級輕量虛擬化技術,透過 cgroups 限制資源、namespace 隔離視圖,提供接近原生效能的隔離環境。本文涵蓋安裝驗證、容器全生命週期管理、模板使用與網路配置實務。

前置需求

  • 核心支援:3.10+ 建議,需啟用 CGROUPS, NAMESPACES, VETH, MACVLAN 等選項。
  • 檢查指令:lxc-checkconfig 全部顯示 enabled 即可使用。

安裝 LXC


# 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 testACtrl+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 testARUNNING/STOPPED/FROZEN
銷毀lxc-destroy -n testA刪除容器根目錄
複製lxc-clone -o testA -n testB快速複製容器
快照lxc-snapshot -n testA需 Btrfs/LVM/OverlayFS 支援

容器網路配置

預設橋接模式 (lxcbr0)


# /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 存取外網

容器靜態 IP 設定


# /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

Macvlan 直通物理網卡 (效能更佳)


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 介面)。

資源限制 (cgroups)


# /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 架構與網路拓撲圖

Copyright © Windows教程網 All Rights Reserved
現象可能原因解決
lxc-start 卡住無訊息缺少 tty 設定config 加入 lxc.tty = 4 lxc.pts = 1024
容器無網路橋接未啟動/防火牆阻擋檢查 brctl show, iptables -L, 重啟 lxc-net
掛載失敗缺少 CAP_SYS_ADMINconfig 加入 lxc.cap.drop = (不丟棄) 或 lxc.cap.keep = CAP_SYS_ADMIN