LNMP自动部署实用方案
一、方案总览与选型
| 方式 | 适用场景 | 核心优点 | 关键要点 |
|---|---|---|---|
| Shell 一键脚本 | 单机快速交付 | 简单直观、可定制 | 版本锁定、幂等处理、错误处理与回滚 |
| oneinstack | 多版本/多组件选择 | 功能全、交互/自动均可 | 支持 Nginx/Tengine/OpenResty、多 PHP/DB 版本、SSL/备份 |
| Ansible | 批量/多环境 | 声明式、可复用、可审计 | Playbook 管理、Idempotent、角色化 |
| Docker | 开发/测试/轻量生产 | 环境隔离、快速起停 | 多容器编排、数据卷持久化、网络与权限 |
| Terraform | 云上基础设施 + 初始化 | IaC、可重复部署 | User Data 执行安装脚本、与云资源联动 |
以上方案在实际工程中均被广泛采用,可按规模与运维成熟度选择或组合使用。
二、单机一键脚本思路与关键步骤
三、批量与云上自动化
四、一键脚本最小可用示例 CentOS 7
#!/usr/bin/env bash
set -Eeuo pipefail
# 可配置参数
DB_ROOT_PASS="${DB_ROOT_PASS:-MyStrongPass123!}"
PHP_VER="${PHP_VER:-74}" # 74/80/81/83
NGINX_ROOT="/usr/share/nginx/html"
INFO_PHP="${NGINX_ROOT}/info.php"
echo "[1/5] 安装 EPEL 与 Nginx"
yum install -y epel-release
yum install -y nginx
systemctl start nginx && systemctl enable nginx
curl -I http://localhost | grep -q "200 OK" || { echo "Nginx 启动或访问异常"; exit 1; }
echo "[2/5] 安装 MariaDB 并初始化"
yum install -y mariadb-server mariadb
systemctl start mariadb && systemctl enable mariadb
mysql_secure_installation <<EOF
y
${DB_ROOT_PASS}
${DB_ROOT_PASS}
y
y
y
y
EOF
echo "[3/5] 安装 PHP ${PHP_VER} 与常用扩展"
yum install -y yum-utils
yum install -y "http://rpms.remirepo.net/enterprise/remi-release-7.rpm"
yum-config-manager --disable 'remi-php*'
yum-config-manager --enable "remi-php${PHP_VER}"
yum install -y php php-fpm php-mysqlnd php-mbstring php-xml php-gd php-opcache
systemctl start php-fpm && systemctl enable php-fpm
echo "[4/5] 配置 Nginx 支持 PHP"
cat >/etc/nginx/conf.d/default.conf <<'EOF'
server {
listen 80;
server_name _;
root /usr/share/nginx/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
EOF
systemctl reload nginx
echo "[5/5] 创建 PHP 测试页并验证"
echo "<?php phpinfo(); ?>" > "$INFO_PHP"
curl -I http://localhost/info.php | grep -q "200 OK" || { echo "PHP 页面测试失败"; exit 1; }
echo "LNMP 部署完成:Nginx + MariaDB + PHP ${PHP_VER}"
echo "访问 http://服务器IP/info.php 验证"