二、虚拟化技术与云计算-10-kvm-virtualization-guide-part6-template-creation
·
KVM 虚拟化技术实战指南 - 第六部分:虚拟机模板制作
文档信息
- 系列: KVM 虚拟化技术实战指南
- 部分: 第六部分 - 虚拟机模板制作
- 版本: V1.0
- 创建日期: 2026 年 3 月 9 日
- 对应视频: 11-11 (04:54)
- 预计阅读时间: 1-2 小时
目录
- 模板基础概念
- 创建基础镜像模板
- [使用 cloud-init 自动化](#使用 cloud-init 自动化)
- [使用 virt-sysprep 清理系统](#使用 virt-sysprep 清理系统)
- 模板管理与分发
- [快速部署 VM](#快速部署 vm)
- 模板优化技巧
- 实战案例
模板基础概念
什么是虚拟机模板?
定义:
虚拟机模板是一个预配置的基础镜像,包含:
- 操作系统安装
- 基础软件包
- 系统配置
- 安全加固
- 但未包含特定信息 (如主机名、IP、密码等)
作用:
┌─────────────────────────────────────────────────────────┐
│ 虚拟机模板的优势 │
├─────────────────────────────────────────────────────────┤
│ │
│ 1. 快速部署 │
│ - 从模板部署 VM: 5-10 分钟 │
│ - 全新安装 VM: 30-60 分钟 │
│ - 效率提升:80%+ │
│ │
│ 2. 标准化配置 │
│ - 统一的系统配置 │
│ - 一致的软件版本 │
│ - 相同的安全基线 │
│ │
│ 3. 减少错误 │
│ - 避免手动安装错误 │
│ - 配置一致性保证 │
│ - 质量可控 │
│ │
│ 4. 批量部署 │
│ - 一次制作,多次使用 │
│ - 自动化批量部署 │
│ - 适合云计算环境 │
│ │
└─────────────────────────────────────────────────────────┘
模板制作流程
┌─────────────────────────────────────────────────────────┐
│ 模板制作完整流程 │
├─────────────────────────────────────────────────────────┤
│ │
│ 1. 创建 VM │
│ ↓ │
│ 2. 安装操作系统 │
│ ↓ │
│ 3. 安装必要软件 │
│ ↓ │
│ 4. 系统配置和优化 │
│ ↓ │
│ 5. 安全加固 │
│ ↓ │
│ 6. 清理系统 (virt-sysprep) │
│ ↓ │
│ 7. 转换为模板 │
│ ↓ │
│ 8. 测试和验证 │
│ ↓ │
│ 9. 发布和分发 │
│ │
└─────────────────────────────────────────────────────────┘
创建基础镜像模板
方法 1: 手动创建模板
步骤 1: 创建基础 VM
# 创建用于制作模板的 VM
virt-install \
--name centos7-template-base \
--description "CentOS 7 模板基础系统" \
--ram 2048 \
--vcpus 2 \
--disk path=/var/lib/libvirt/images/centos7-template-base.qcow2,size=20,format=qcow2,bus=virtio \
--os-variant centos7.0 \
--network network=default,model=virtio \
--graphics vnc,listen=0.0.0.0 \
--cdrom /var/lib/libvirt/images/CentOS-7-x86_64-DVD-2009.iso \
--noautoconsole
步骤 2: 安装操作系统
# 通过 VNC 连接安装系统
virt-viewer centos7-template-base
# 安装选项:
# - 语言:English
# - 时区:Asia/Shanghai
# - 分区:自动 (使用整个磁盘)
# - 软件包:Minimal Install
# - 网络:启用 (DHCP)
# - Root 密码:temp123 (临时)
步骤 3: 安装必要软件
# 在 VM 中执行
# 1. 更新系统
yum update -y
# 2. 安装基础工具
yum install -y \
vim \
wget \
curl \
git \
net-tools \
bash-completion \
htop \
iotop \
tcpdump \
rsync
# 3. 安装虚拟化增强
yum install -y qemu-guest-agent
systemctl enable --now qemu-guest-agent
# 4. 安装监控代理
yum install -y collectd
systemctl enable --now collectd
步骤 4: 系统配置和优化
# 1. 配置 SSH
cat >> /etc/ssh/sshd_config <<EOF
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
ClientAliveInterval 300
ClientAliveCountMax 2
EOF
systemctl restart sshd
# 2. 配置防火墙
firewall-cmd --permanent --add-service=ssh
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload
# 3. 配置时间同步
timedatectl set-timezone Asia/Shanghai
yum install -y chrony
systemctl enable --now chronyd
# 4. 优化内核参数
cat >> /etc/sysctl.conf <<EOF
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.ip_forward = 1
vm.swappiness = 10
EOF
sysctl -p
# 5. 配置日志轮转
cat > /etc/logrotate.d/custom <<EOF
/var/log/custom/*.log {
daily
rotate 7
compress
delaycompress
missingok
notifempty
}
EOF
步骤 5: 清理系统
# 1. 清理 yum 缓存
yum clean all
rm -rf /var/cache/yum
# 2. 清理日志
> /var/log/messages
> /var/log/secure
> /var/log/yum.log
find /var/log -type f -name "*.log" -exec truncate -s 0 {} \;
# 3. 清理临时文件
rm -rf /tmp/*
rm -rf /var/tmp/*
# 4. 清理 bash 历史
history -c
> ~/.bash_history
# 5. 清理网络配置
> /etc/udev/rules.d/70-persistent-net.rules
rm -f /etc/ssh/ssh_host_*
# 6. 清理机器 ID
> /etc/machine-id
rm -f /var/lib/dbus/machine-id
# 7. 清理 ARP 缓存
ip neigh flush all
# 8. 清理 DNS 缓存
systemctl restart nscd 2>/dev/null || true
步骤 6: 关闭 VM 并转换为模板
# 关闭 VM
virsh shutdown centos7-template-base
# 等待完全关闭
virsh list --all | grep centos7-template-base
# 复制镜像作为模板
cp /var/lib/libvirt/images/centos7-template-base.qcow2 \
/var/lib/libvirt/images/centos7-template.qcow2
# 设置权限
chown libvirt-qemu:kvm /var/lib/libvirt/images/centos7-template.qcow2
chmod 644 /var/lib/libvirt/images/centos7-template.qcow2
# 查看模板信息
qemu-img info /var/lib/libvirt/images/centos7-template.qcow2
方法 2: 使用 virt-builder 快速创建
安装 virt-builder
# CentOS/RHEL
yum install -y libguestfs-tools
# Ubuntu/Debian
apt install -y libguestfs-tools
查看可用模板
# 列出所有可用镜像
virt-builder --list
# 搜索 CentOS
virt-builder --list | grep centos
# 搜索 Ubuntu
virt-builder --list | grep ubuntu
# 输出示例:
# centos-7.6 x86_64 CentOS 7.6
# centos-8 x86_64 CentOS 8
# ubuntu-20.04 x86_64 Ubuntu 20.04 LTS
创建 CentOS 7 模板
# 下载并创建模板
virt-builder centos-7.6 \
--size 20G \
--format qcow2 \
--output /var/lib/libvirt/images/centos7-template.qcow2 \
--root-password password:TempPass123 \
--hostname centos7-template \
--ssh-inject root:file:/root/.ssh/id_rsa.pub \
--install vim,wget,curl,git,net-tools,bash-completion,qemu-guest-agent \
--update \
--selinux-relabel \
--edit '/etc/selinux/config:s/^SELINUX=.*/SELINUX=enforcing/' \
--edit '/etc/ssh/sshd_config:s/^#?PermitRootLogin.*/PermitRootLogin no/' \
--edit '/etc/ssh/sshd_config:s/^#?PasswordAuthentication.*/PasswordAuthentication no/'
# 设置权限
chown libvirt-qemu:kvm /var/lib/libvirt/images/centos7-template.qcow2
chmod 644 /var/lib/libvirt/images/centos7-template.qcow2
创建 Ubuntu 20.04 模板
virt-builder ubuntu-20.04 \
--size 20G \
--format qcow2 \
--output /var/lib/libvirt/images/ubuntu20-template.qcow2 \
--root-password password:TempPass123 \
--hostname ubuntu20-template \
--ssh-inject root:file:/root/.ssh/id_rsa.pub \
--install vim,wget,curl,git,net-tools,qemu-guest-agent \
--update \
--edit '/etc/ssh/sshd_config:s/^#?PermitRootLogin.*/PermitRootLogin no/' \
--edit '/etc/ssh/sshd_config:s/^#?PasswordAuthentication.*/PasswordAuthentication no/'
# 设置权限
chown libvirt-qemu:kvm /var/lib/libvirt/images/ubuntu20-template.qcow2
chmod 644 /var/lib/libvirt/images/ubuntu20-template.qcow2
使用 cloud-init 自动化
什么是 cloud-init?
定义:
cloud-init 是一个初始化工具,用于在 VM 首次启动时自动配置:
- 用户和密码
- SSH 密钥
- 网络配置
- 软件包安装
- 自定义脚本
优势:
✓ 零接触部署
✓ 标准化配置
✓ 自动化程度高
✓ 适合大规模部署
安装 cloud-init
# 在模板 VM 中安装
# CentOS/RHEL
yum install -y cloud-init cloud-utils-growpart
# Ubuntu/Debian
apt install -y cloud-init
# 启用服务
systemctl enable --now cloud-init-local
systemctl enable --now cloud-init
systemctl enable --now cloud-config
systemctl enable --now cloud-final
配置 cloud-init
创建 user-data 文件
#cloud-config
# 主机名配置
hostname: web-server-01
manage_etc_hosts: true
# 用户配置
users:
- name: admin
sudo: ALL=(ALL) NOPASSWD:ALL
shell: /bin/bash
ssh_authorized_keys:
- ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ... admin@example.com
lock_passwd: true
- name: deploy
sudo: ALL=(ALL) NOPASSWD:ALL
shell: /bin/bash
ssh_authorized_keys:
- ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQ... deploy@example.com
# SSH 配置
ssh_pwauth: false
disable_root: true
# 软件包安装
packages:
- vim
- git
- curl
- wget
- htop
- iotop
- nginx
- mysql-server
# 服务管理
runcmd:
- systemctl enable nginx
- systemctl start nginx
- systemctl enable mysqld
- systemctl start mysqld
# 写入文件
write_files:
- path: /etc/motd
content: |
Welcome to CentOS 7 Web Server
Deployed by cloud-init
permissions: '0644'
- path: /tmp/first-boot.txt
content: "First boot at $(date)"
permissions: '0644'
# 执行命令
bootcmd:
- echo "Boot at $(date)" >> /var/log/boot.log
# 最终命令
final_message: "Cloud-init completed successfully!"
创建 meta-data 文件
# meta-data
instance-id: web-server-01
local-hostname: web-server-01
network:
version: 1
config:
- type: physical
name: eth0
subnets:
- type: dhcp
生成 cloud-init 镜像
# 创建 cloud-init ISO
mkdir -p /tmp/cloud-init-iso
cp user-data /tmp/cloud-init-iso/user-data
cp meta-data /tmp/cloud-init-iso/meta-data
# 生成 ISO
mkisofs -J -V cidata \
-o /var/lib/libvirt/images/cloud-init.iso \
/tmp/cloud-init-iso/*
# 或者使用 cloud-localds (推荐)
cloud-localds /var/lib/libvirt/images/cloud-init.iso \
user-data \
meta-data
部署带 cloud-init 的 VM
# 从模板创建 VM 并挂载 cloud-init
virt-install \
--name web-server-01 \
--ram 2048 \
--vcpus 2 \
--disk path=/var/lib/libvirt/images/centos7-template.qcow2,format=qcow2,bus=virtio \
--disk path=/var/lib/libvirt/images/cloud-init.iso,device=cdrom \
--os-variant centos7.0 \
--network network=default,model=virtio \
--graphics vnc \
--import \
--noautoconsole
# VM 首次启动时会自动执行 cloud-init 配置
使用 virt-sysprep 清理系统
什么是 virt-sysprep?
定义:
virt-sysprep 是一个用于清理和重置虚拟机镜像的工具,可以:
- 清除系统特定信息
- 删除日志文件
- 清除网络配置
- 重置机器 ID
- 清除用户历史
使用场景:
✓ 创建模板前清理
✓ 批量部署前重置
✓ 镜像分发前清理
基本使用
# 查看可用的操作
virt-sysprep --list-operations
# 输出示例:
# backup-files Remove backup files
# bash-history Remove bash history
# dhcp-client-state Remove DHCP client leases
# log-files Remove log files
# machine-id Remove machine ID
# ssh-hostkeys Remove SSH host keys
# ...
# 执行所有清理操作
virt-sysprep -d centos7-template-base
# 或指定镜像文件
virt-sysprep -a /var/lib/libvirt/images/centos7-template-base.qcow2
选择性清理
# 启用特定操作
virt-sysprep -a centos7-template.qcow2 \
--enable bash-history,log-files,machine-id,ssh-hostkeys,dhcp-client-state
# 禁用特定操作
virt-sysprep -a centos7-template.qcow2 \
--disable lvm-uuids,net-hwaddr
# 查看默认启用的操作
virt-sysprep --list-operations | grep enabled
自定义清理脚本
#!/bin/bash
# custom-sysprep.sh
IMAGE=$1
# 创建清理脚本
cat > /tmp/cleanup.sh <<'EOF'
#!/bin/bash
# 自定义清理操作
# 清理应用日志
find /var/log/app -type f -delete 2>/dev/null
# 清理缓存
rm -rf /var/cache/app/*
# 清理临时文件
rm -rf /opt/temp/*
# 重置配置
> /etc/app/config.ini
EOF
chmod +x /tmp/cleanup.sh
# 使用 virt-customize 执行
virt-customize -a $IMAGE \
--upload /tmp/cleanup.sh:/usr/local/bin/cleanup.sh \
--run '/usr/local/bin/cleanup.sh'
# 然后执行 virt-sysprep
virt-sysprep -a $IMAGE
完整清理流程
#!/bin/bash
# full-sysprep.sh
VM_NAME=$1
TEMPLATE_NAME=$2
echo "Starting full sysprep for $VM_NAME..."
# 1. 关闭 VM
virsh shutdown $VM_NAME
sleep 30
# 2. 验证已关闭
if ! virsh domstate $VM_NAME | grep -q "shut off"; then
echo "VM not shut off, forcing..."
virsh destroy $VM_NAME
fi
# 3. 获取镜像路径
DISK=$(virsh domblklist $VM_NAME | grep vda | awk '{print $2}')
# 4. 执行 virt-sysprep
virt-sysprep -a $DISK \
--enable all \
--disable lvm-uuids
# 5. 复制为模板
cp $DISK /var/lib/libvirt/images/${TEMPLATE_NAME}.qcow2
# 6. 设置权限
chown libvirt-qemu:kvm /var/lib/libvirt/images/${TEMPLATE_NAME}.qcow2
chmod 644 /var/lib/libvirt/images/${TEMPLATE_NAME}.qcow2
# 7. 压缩镜像 (可选)
qemu-img convert -f qcow2 -O qcow2 -c \
/var/lib/libvirt/images/${TEMPLATE_NAME}.qcow2 \
/var/lib/libvirt/images/${TEMPLATE_NAME}-compressed.qcow2
mv /var/lib/libvirt/images/${TEMPLATE_NAME}-compressed.qcow2 \
/var/lib/libvirt/images/${TEMPLATE_NAME}.qcow2
echo "Template $TEMPLATE_NAME created successfully"
模板管理与分发
模板存储结构
/var/lib/libvirt/templates/
├── centos/
│ ├── centos7-minimal.qcow2
│ ├── centos7-standard.qcow2
│ └── centos7-docker.qcow2
├── ubuntu/
│ ├── ubuntu20-minimal.qcow2
│ ├── ubuntu20-standard.qcow2
│ └── ubuntu20-docker.qcow2
├── metadata/
│ ├── centos7-minimal.xml
│ ├── centos7-standard.xml
│ └── ...
└── README.md
创建模板元数据
<!-- centos7-minimal.xml -->
<?xml version="1.0" encoding="UTF-8"?>
<template>
<name>centos7-minimal</name>
<description>CentOS 7 Minimal Install Template</description>
<os>CentOS 7.9</os>
<arch>x86_64</arch>
<size>20GB</size>
<format>qcow2</format>
<created>2026-03-09</created>
<updated>2026-03-09</updated>
<version>1.0</version>
<packages>
<package>vim</package>
<package>wget</package>
<package>curl</package>
<package>git</package>
<package>net-tools</package>
<package>qemu-guest-agent</package>
</packages>
<configuration>
<ssh>
<root-login>disabled</root-login>
<password-auth>disabled</password-auth>
<key-auth>enabled</key-auth>
</ssh>
<firewall>enabled</firewall>
<selinux>enforcing</selinux>
</configuration>
<checksum>sha256:xxxxxxxxxxxx</checksum>
</template>
模板版本控制
#!/bin/bash
# version-template.sh
TEMPLATE=$1
VERSION=$2
# 创建版本目录
mkdir -p /var/lib/libvirt/templates/archive/$TEMPLATE
# 复制当前版本
cp /var/lib/libvirt/images/${TEMPLATE}.qcow2 \
/var/lib/libvirt/templates/archive/$TEMPLATE/${TEMPLATE}-v${VERSION}.qcow2
# 创建校验和
sha256sum /var/lib/libvirt/templates/archive/$TEMPLATE/${TEMPLATE}-v${VERSION}.qcow2 \
> /var/lib/libvirt/templates/archive/$TEMPLATE/${TEMPLATE}-v${VERSION}.sha256
# 更新元数据
sed -i "s/<version>.*<\/version>/<version>${VERSION}<\/version>/" \
/var/lib/libvirt/templates/metadata/${TEMPLATE}.xml
sed -i "s/<updated>.*<\/updated>/<updated>$(date +%Y-%m-%d)<\/updated>/" \
/var/lib/libvirt/templates/metadata/${TEMPLATE}.xml
echo "Template $TEMPLATE version $VERSION archived"
模板分发
方法 1: HTTP 下载
# 在 HTTP 服务器上提供下载
ln -s /var/lib/libvirt/images/centos7-template.qcow2 \
/var/www/html/templates/centos7-template.qcow2
# 客户端下载
wget http://template-server/templates/centos7-template.qcow2
# 验证校验和
sha256sum -c centos7-template.sha256
方法 2: rsync 同步
# 服务器端配置
# /etc/rsyncd.conf
[templates]
path = /var/lib/libvirt/templates
read only = yes
uid = root
gid = root
# 客户端同步
rsync -avz template-server::templates/centos7/ \
/var/lib/libvirt/images/centos7/
方法 3: Git LFS
# 初始化 Git 仓库
cd /var/lib/libvirt/templates
git init
git lfs install
# 跟踪大文件
git lfs track "*.qcow2"
# 添加模板
git add centos7/
git commit -m "Add CentOS 7 templates"
# 推送到远程
git remote add origin git@git-server:templates.git
git push -u origin master
# 客户端克隆
git clone git@git-server:templates.git
快速部署 VM
从模板部署单个 VM
#!/bin/bash
# deploy-from-template.sh
TEMPLATE=$1
VM_NAME=$2
RAM=${3:-2048}
VCPUS=${4:-2}
DISK_SIZE=${5:-20}
echo "Deploying $VM_NAME from $TEMPLATE..."
# 1. 复制模板镜像
cp /var/lib/libvirt/images/${TEMPLATE}.qcow2 \
/var/lib/libvirt/images/${VM_NAME}.qcow2
# 2. 设置权限
chown libvirt-qemu:kvm /var/lib/libvirt/images/${VM_NAME}.qcow2
chmod 644 /var/lib/libvirt/images/${VM_NAME}.qcow2
# 3. 扩展磁盘 (如果需要)
if [ $DISK_SIZE -gt 20 ]; then
qemu-img resize /var/lib/libvirt/images/${VM_NAME}.qcow2 ${DISK_SIZE}G
fi
# 4. 创建 VM 定义
virt-install \
--name $VM_NAME \
--ram $RAM \
--vcpus $VCPUS \
--disk path=/var/lib/libvirt/images/${VM_NAME}.qcow2,format=qcow2,bus=virtio \
--os-variant centos7.0 \
--network network=default,model=virtio \
--graphics vnc \
--import \
--noautoconsole
echo "VM $VM_NAME deployed successfully"
批量部署 VM
#!/bin/bash
# batch-deploy.sh
TEMPLATE=$1
PREFIX=$2
COUNT=$3
RAM=${4:-2048}
VCPUS=${5:-2}
echo "Deploying $COUNT VMs from $TEMPLATE..."
for i in $(seq 1 $COUNT); do
VM_NAME="${PREFIX}-$(printf '%03d' $i)"
echo "Deploying $VM_NAME..."
# 复制模板
cp /var/lib/libvirt/images/${TEMPLATE}.qcow2 \
/var/lib/libvirt/images/${VM_NAME}.qcow2
# 设置权限
chown libvirt-qemu:kvm /var/lib/libvirt/images/${VM_NAME}.qcow2
# 创建 VM
virt-install \
--name $VM_NAME \
--ram $RAM \
--vcpus $VCPUS \
--disk path=/var/lib/libvirt/images/${VM_NAME}.qcow2,format=qcow2,bus=virtio \
--os-variant centos7.0 \
--network network=default,model=virtio \
--graphics vnc \
--import \
--noautoconsole
echo "$VM_NAME deployed"
done
echo "All VMs deployed successfully"
使用方法:
chmod +x batch-deploy.sh
./batch-deploy.sh centos7-template web-server 5 2048 2
# 部署 5 台 web-server VM
使用 cloud-init 批量部署
#!/bin/bash
# deploy-with-cloudinit.sh
TEMPLATE=$1
VM_NAME=$2
USER_DATA=$3
echo "Deploying $VM_NAME with cloud-init..."
# 1. 复制模板
cp /var/lib/libvirt/images/${TEMPLATE}.qcow2 \
/var/lib/libvirt/images/${VM_NAME}.qcow2
# 2. 生成 cloud-init ISO
cloud-localds /var/lib/libvirt/images/${VM_NAME}-cloudinit.iso \
$USER_DATA
# 3. 创建 VM
virt-install \
--name $VM_NAME \
--ram 2048 \
--vcpus 2 \
--disk path=/var/lib/libvirt/images/${VM_NAME}.qcow2,format=qcow2,bus=virtio \
--disk path=/var/lib/libvirt/images/${VM_NAME}-cloudinit.iso,device=cdrom \
--os-variant centos7.0 \
--network network=default,model=virtio \
--graphics vnc \
--import \
--noautoconsole
echo "$VM_NAME deployed with cloud-init"
模板优化技巧
减小镜像大小
# 1. 在模板中清理
virt-customize -a template.qcow2 \
--run 'yum clean all' \
--run 'rm -rf /var/cache/yum/*' \
--run 'find /var/log -type f -name "*.log" -delete' \
--run 'rm -rf /tmp/*'
# 2. 压缩镜像
qemu-img convert -f qcow2 -O qcow2 -c \
template.qcow2 \
template-compressed.qcow2
# 3. 使用更小的基础镜像
# Minimal Install vs Full Install
# 最小化:1-2GB
# 完整版:4-5GB
优化启动速度
# 1. 减少启动服务
virt-customize -a template.qcow2 \
--run 'systemctl disable bluetooth' \
--run 'systemctl disable cups' \
--run 'systemctl disable NetworkManager-wait-online'
# 2. 优化 fstab
virt-customize -a template.qcow2 \
--edit '/etc/fstab:s/defaults/defaults,noatime,nodiratime/'
# 3. 使用更快的文件系统
# ext4 vs xfs
# xfs 在大文件场景性能更好
预安装常用软件
# 创建不同用途的模板
# Web 服务器模板
virt-customize -a centos7-base.qcow2 \
--install nginx,php,php-mysql,php-fpm \
--run 'systemctl enable nginx'
# 数据库模板
virt-customize -a centos7-base.qcow2 \
--install mariadb-server,mariadb \
--run 'systemctl enable mariadb'
# Docker 模板
virt-customize -a centos7-base.qcow2 \
--upload docker.repo:/etc/yum.repos.d/docker.repo \
--install docker-ce \
--run 'systemctl enable docker'
# Kubernetes 模板
virt-customize -a centos7-base.qcow2 \
--run 'setenforce 0' \
--run 'yum install -y kubelet kubeadm kubectl'
实战案例
案例 1: Web 服务器集群部署
需求:
部署 10 台 Web 服务器
统一配置
快速交付
自动化初始化
步骤:
# 1. 创建 Web 服务器模板
virt-builder centos-7.6 \
--size 20G \
--output /var/lib/libvirt/images/centos7-web-template.qcow2 \
--install nginx,php,php-fpm,git,vim \
--run 'systemctl enable nginx'
# 2. 准备 cloud-init 配置
cat > web-user-data.yaml <<EOF
#cloud-config
hostname: web-$(printf '%02d' $RANDOM)
packages:
- nginx
- php
- php-fpm
runcmd:
- systemctl start nginx
- systemctl enable nginx
- echo "<?php phpinfo(); ?>" > /usr/share/nginx/html/index.php
EOF
# 3. 批量部署
for i in $(seq 1 10); do
VM_NAME="web-server-$(printf '%03d' $i)"
# 复制模板
cp /var/lib/libvirt/images/centos7-web-template.qcow2 \
/var/lib/libvirt/images/${VM_NAME}.qcow2
# 生成 cloud-init ISO
cloud-localds /var/lib/libvirt/images/${VM_NAME}-cloudinit.iso \
web-user-data.yaml
# 创建 VM
virt-install \
--name $VM_NAME \
--ram 2048 \
--vcpus 2 \
--disk path=/var/lib/libvirt/images/${VM_NAME}.qcow2,format=qcow2,bus=virtio \
--disk path=/var/lib/libvirt/images/${VM_NAME}-cloudinit.iso,device=cdrom \
--os-variant centos7.0 \
--network network=default,model=virtio \
--import \
--noautoconsole
done
echo "10 web servers deployed"
案例 2: 开发环境快速搭建
需求:
为新员工准备开发环境
包含常用工具
统一配置
快速交付
步骤:
# 1. 创建开发环境模板
virt-builder centos-7.6 \
--size 30G \
--output /var/lib/libvirt/images/centos7-dev-template.qcow2 \
--install \
vim,git,curl,wget \
gcc,gcc-c++,make,cmake \
python3,python3-pip \
nodejs,npm \
docker-ce \
vscode-code \
--run 'useradd -m -s /bin/bash developer' \
--run 'echo "developer:DevPass123" | chpasswd' \
--run 'echo "developer ALL=(ALL) NOPASSWD:ALL" >> /etc/sudoers'
# 2. 准备开发环境配置
cat > dev-user-data.yaml <<EOF
#cloud-config
users:
- name: newdev
sudo: ALL=(ALL) NOPASSWD:ALL
shell: /bin/bash
ssh_authorized_keys:
- ssh-rsa AAAA... newdev@company.com
packages:
- docker-compose
- maven
- gradle
runcmd:
- usermod -aG docker newdev
- su - newdev -c "npm install -g nodemon"
- su - newdev -c "pip3 install flask django"
EOF
# 3. 部署开发环境
virt-install \
--name dev-workstation \
--ram 4096 \
--vcpus 4 \
--disk path=/var/lib/libvirt/images/centos7-dev-template.qcow2,format=qcow2,bus=virtio \
--disk path=/var/lib/libvirt/images/dev-cloudinit.iso,device=cdrom \
--os-variant centos7.0 \
--network network=default,model=virtio \
--graphics vnc \
--import \
--noautoconsole
案例 3: 测试环境自动化
需求:
每天需要多次创建/销毁测试环境
环境配置一致
自动化测试集成
步骤:
#!/bin/bash
# test-env-manager.sh
ACTION=$1
ENV_TYPE=$2
TEMPLATE="centos7-test-template"
PREFIX="test-env"
case $ACTION in
"create")
# 创建测试环境
VM_NAME="${PREFIX}-$(date +%Y%m%d-%H%M%S)"
# 复制模板
cp /var/lib/libvirt/images/${TEMPLATE}.qcow2 \
/var/lib/libvirt/images/${VM_NAME}.qcow2
# 创建 VM
virt-install \
--name $VM_NAME \
--ram 2048 \
--vcpus 2 \
--disk path=/var/lib/libvirt/images/${VM_NAME}.qcow2,format=qcow2,bus=virtio \
--os-variant centos7.0 \
--network network=default,model=virtio \
--import \
--noautoconsole
echo "Test environment $VM_NAME created"
echo $VM_NAME
;;
"destroy")
# 销毁测试环境
virsh destroy $ENV_TYPE
virsh undefine $ENV_TYPE
# 删除磁盘
rm -f /var/lib/libvirt/images/${ENV_TYPE}.qcow2
echo "Test environment $ENV_TYPE destroyed"
;;
"cleanup")
# 清理所有测试环境
for vm in $(virsh list --name | grep $PREFIX); do
virsh destroy $vm
virsh undefine $vm
rm -f /var/lib/libvirt/images/${vm}.qcow2
done
echo "All test environments cleaned up"
;;
esac
集成到 CI/CD:
# .gitlab-ci.yml
test:
script:
- VM_NAME=$(./test-env-manager.sh create)
- sleep 60 # 等待 VM 启动
- ssh $VM_NAME "run tests"
- ./test-env-manager.sh destroy $VM_NAME
总结
模板制作检查清单
制作前:
□ 确定模板用途
□ 选择基础系统
□ 规划软件包列表
□ 准备配置文件
制作中:
□ 最小化安装
□ 安装必要软件
□ 系统配置优化
□ 安全加固
□ 清理系统
□ 转换为模板
制作后:
□ 测试模板
□ 记录元数据
□ 版本控制
□ 分发给用户
模板管理最佳实践
✓ 统一存储位置
✓ 版本控制
✓ 定期更新
✓ 安全存储
✓ 文档化
✓ 自动化部署
性能优化要点
✓ 使用 QCOW2 压缩格式
✓ 最小化安装
✓ 清理不必要文件
✓ 预安装常用软件
✓ 优化启动项
✓ 使用 virtio 驱动
本文档属于 KVM 虚拟化技术实战系列
对应视频:11-11 (04:54)
最后更新:2026 年 3 月
更多推荐
所有评论(0)