LNMP自动化的总体思路
快速落地方案
示例一 Shell脚本最小可用模板 CentOS
#!/usr/bin/env bash
set -e
exec > >(tee lnmp_install.log) 2>&1
# 0) 参数
DB_ROOT_PASS="${DB_ROOT_PASS:-YourStrongDBPass!}"
NGINX_CONF="/etc/nginx/conf.d/default.conf"
PHP_TEST="/usr/share/nginx/html/info.php"
# 1) 基础准备
yum update -y
yum install -y epel-release wget gcc make pcre-devel openssl-devel \
mariadb-server mariadb php php-fpm php-mysql php-mbstring php-xml php-gd php-opcache
# 2) Nginx
systemctl enable --now nginx
# 3) MariaDB
systemctl enable --now mariadb
mysql_secure_installation <<EOF
y
${DB_ROOT_PASS}
${DB_ROOT_PASS}
y
y
y
y
EOF
# 4) PHP-FPM
systemctl enable --now php-fpm
# 5) Nginx + PHP
cat > "$NGINX_CONF" <<'EOF'
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.php index.html;
location / { try_files $uri $uri/ =404; }
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
# 6) 测试页
echo "<?php phpinfo(); ?>" > "$PHP_TEST"
# 7) 重载与验证
systemctl reload nginx php-fpm
echo "Done. Check: http://$(curl -s ifconfig.me)/info.php"
示例二 Ansible Playbook最小可用模板 CentOS
---
- name: Deploy LNMP on CentOS
hosts: webservers
become: yes
vars:
db_root_pass: "YourStrongDBPass!"
tasks:
- name: Update cache
yum:
name: "*"
state: latest
update_cache: yes
- name: Install packages
yum:
name:
- epel-release
- nginx
- mariadb-server
- mariadb
- php
- php-fpm
- php-mysql
- php-mbstring
- php-xml
- php-gd
- php-opcache
state: present
- name: Enable and start services
service:
name: "{{ item }}"
state: started
enabled: yes
loop:
- nginx
- mariadb
- php-fpm
- name: Secure MariaDB
command: >
mysql_secure_installation
args:
stdin: "y\n{{ db_root_pass }}\n{{ db_root_pass }}\ny\ny\ny\ny\n"
- name: Configure Nginx for PHP
copy:
dest: /etc/nginx/conf.d/default.conf
content: |
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.php index.html;
location / { try_files $uri $uri/ =404; }
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;
}
}
- name: Create PHP info
copy:
dest: /usr/share/nginx/html/info.php
content: "<?php phpinfo(); ?>"
- name: Reload Nginx
service:
name: nginx
state: reloaded
上线与运维自动化