萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 作業系統 >  >> Linux 教學

Linux LXC 容器安裝部署完整指南:建立、管理、網路與生命週期操作

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

LXC 架構示意圖

核心概念

  • cgroups:限制 CPU、記憶體、I/O、網路等資源配額。
  • namespace:隔離 PID、NET、MNT、UTS、IPC、USER 等系統視圖。
  • 模板:/usr/share/lxc/templates/ 提供各發行版根檔系統建立腳本。

1. 安裝 LXC 套件

yum install lxc* -y

2. 驗證核心支援

lxc-checkconfig
# 所有項目顯示 "enabled" 即可使用

3. 建立第一個容器 (以 Fedora 模板為例)

lxc-create -t fedora -n testA
# 容器根目錄位於 /var/lib/lxc/testA/

4. 容器生命週期管理

操作命令說明
啟動(前景)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 支援

5. 網路配置

預設橋接模式 (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

容器靜態 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.100/24
lxc.net.0.ipv4.gateway = 10.0.3.1

Macvlan 直通物理網卡(進階)

lxc.net.0.type = macvlan
lxc.net.0.link = eth0
lxc.net.0.flags = up
lxc.net.0.macvlan.mode = bridge

6. 權限與非特權容器

一般使用者亦可運行容器(無需 root),需設定 /etc/subuid、/etc/subgid 並配置 ~/.config/lxc/default.conf。

小結

LXC 提供輕量、標準化的容器管理介面,適合開發測試、CI/CD、輕量服務隔離。掌握 lxc-create/start/stop/attach/clone/snapshot 等核心命令,配合 cgroups 與網路模型,即可靈活構建容器化環境。生產環境建議搭配 LXD (LXC 管理守護程序) 獲得更佳體驗。

copyright © 萬盛學電腦網 all rights reserved