一、LNMP 架构概述
1.1 什么是 LNMP
LNMP 是 Linux + Nginx + MySQL/MariaDB + PHP 的缩写,代表一组用于搭建动态网站的开源软件栈。与经典的 LAMP(Linux + Apache + MySQL + PHP)架构相比,LNMP 以高性能、轻量级的 Nginx 替代了 Apache,更适合高并发、高流量的现代 Web 应用场景。
- Linux:作为底层操作系统,提供稳定、安全的运行环境,主流发行版包括 CentOS、Ubuntu、Debian 等。
- Nginx:高性能的 Web 服务器和反向代理服务器,以其低内存占用、高并发处理能力著称,常用于处理静态资源、负载均衡和反向代理。
- MySQL/MariaDB:关系型数据库管理系统,用于存储网站数据,MariaDB 是 MySQL 的开源分支,兼容性极佳。
- PHP:服务器端脚本语言,专门用于开发动态网页,与 Nginx 配合处理动态内容请求。
1.2 LNMP 架构优势
- 高性能与高并发:Nginx 采用异步事件驱动模型,能在极低资源消耗下处理数万并发连接,远超 Apache 的同步阻塞模型。
- 资源占用低:Nginx 内存 footprint 小,在同等硬件条件下能支持更多用户访问,特别适合云服务器、VPS 等资源受限环境。
- 模块化与可扩展性:各组件解耦,可独立升级、替换或扩展,例如用 PostgreSQL 替代 MySQL,或用 Node.js 处理特定业务。
- 安全性与稳定性:Linux 系统本身安全性高,Nginx 配置灵活,可通过权限控制、访问限制等手段进一步加固网站安全。
- 生态完善:拥有丰富的第三方模块和工具,支持负载均衡、缓存、SSL 加密等高级功能,满足企业级应用需求。
1.3 LNMP 工作流程
当用户访问 LNMP 网站时,请求流程如下:
- 用户通过浏览器发起 HTTP/HTTPS 请求,到达服务器的 Nginx 端口(默认 80/443)。
- Nginx 接收请求后,根据配置文件判断请求类型:
- 静态资源(如 HTML、CSS、JS、图片):直接读取本地文件并返回给用户。
- 动态资源(如
.php文件):将请求转发给 PHP-FPM(PHP FastCGI 进程管理器)处理。
- PHP-FPM 调用 PHP 解释器执行脚本,若脚本需要查询数据库,则通过 MySQL 客户端连接 MySQL 服务器。
- MySQL 执行 SQL 查询并返回结果给 PHP 脚本。
- PHP 脚本将处理结果(如 HTML 页面)返回给 Nginx。
- Nginx 将最终响应发送给用户浏览器,完成一次请求。
二、环境准备与系统初始化
2.1 服务器选择与系统安装
搭建 LNMP 环境前,需准备一台运行 Linux 系统的服务器,可选择:
- 云服务器:阿里云、腾讯云、华为云等,按需付费,弹性扩展,适合生产环境。
- 本地虚拟机:VMware、VirtualBox 等,适合学习和测试。
- 物理服务器:适合大型企业或自建机房。
系统推荐选择 CentOS 7/8 或 Ubuntu 20.04/22.04,本文以 CentOS 7 为例进行演示。
2.2 系统初始化配置
安装完系统后,需进行基础配置以确保环境稳定:
2.2.1 更新系统软件包
yum update -y # CentOS/RHEL
apt update && apt upgrade -y # Ubuntu/Debian
2.2.2 关闭防火墙与 SELinux(测试环境)
生产环境建议配置防火墙规则,而非直接关闭。
# 关闭防火墙
systemctl stop firewalld
systemctl disable firewalld
# 关闭 SELinux
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config
reboot # 重启生效
2.2.3 配置主机名与 hosts
hostnamectl set-hostname lnmp-server
echo "127.0.0.1 lnmp-server" >> /etc/hosts
2.2.4 安装基础依赖工具
yum install -y wget curl vim gcc gcc-c++ make autoconf libtool pcre pcre-devel zlib zlib-devel openssl openssl-devel
三、Nginx 安装与配置
3.1 Nginx 安装方式
Nginx 有两种常见安装方式:源码编译安装 和 yum/apt 包管理器安装。源码编译可自定义模块,包管理器安装更便捷。本文推荐源码编译安装,便于灵活配置。
3.1.1 下载 Nginx 源码包
cd /usr/local/src
wget http://nginx.org/download/nginx-1.25.3.tar.gz
tar -zxvf nginx-1.25.3.tar.gz
cd nginx-1.25.3
3.1.2 配置编译参数
./configure \
--prefix=/usr/local/nginx \
--user=nginx \
--group=nginx \
--with-http_stub_status_module \
--with-http_ssl_module \
--with-http_gzip_static_module \
--with-pcre
参数说明:
--prefix:指定安装目录。--user/--group:指定运行 Nginx 的用户和组。--with-http_stub_status_module:启用状态监控模块。--with-http_ssl_module:启用 HTTPS 支持。--with-http_gzip_static_module:启用静态文件压缩。--with-pcre:启用 PCRE 正则表达式支持。
3.1.3 编译与安装
make -j$(nproc) # 多核编译,加速安装
make install
3.1.4 创建 Nginx 用户与系统服务
useradd -s /sbin/nologin -M nginx # 创建不可登录的 nginx 用户
# 创建 systemd 服务文件
cat > /usr/lib/systemd/system/nginx.service << EOF
[Unit]
Description=nginx - high performance web server
Documentation=http://nginx.org/en/docs/
After=network.target remote-fs.target nss-lookup.target
[Service]
Type=forking
PIDFile=/usr/local/nginx/logs/nginx.pid
ExecStart=/usr/local/nginx/sbin/nginx -c /usr/local/nginx/conf/nginx.conf
ExecReload=/usr/local/nginx/sbin/nginx -s reload
ExecStop=/usr/local/nginx/sbin/nginx -s stop
PrivateTmp=true
[Install]
WantedBy=multi-user.target
EOF
# 重载 systemd 并启动 Nginx
systemctl daemon-reload
systemctl start nginx
systemctl enable nginx
3.2 Nginx 基础配置
3.2.1 主配置文件结构
Nginx 主配置文件为 /usr/local/nginx/conf/nginx.conf,核心结构如下:
# 全局块
user nginx;
worker_processes auto;
error_log logs/error.log;
pid logs/nginx.pid;
# events 块
events {
worker_connections 1024;
}
# http 块
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log logs/access.log main;
sendfile on;
keepalive_timeout 65;
# 服务器块(可配置多个虚拟主机)
server {
listen 80;
server_name localhost;
location / {
root html;
index index.html index.htm;
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
3.2.2 配置虚拟主机
为了在一台服务器上运行多个网站,需配置虚拟主机。示例:
# 在 http 块中添加新的 server 块
server {
listen 80;
server_name www.example.com example.com; # 域名
root /usr/local/nginx/html/example; # 网站根目录
index index.html index.php; # 默认首页
location / {
try_files $uri $uri/ =404;
}
# 处理 PHP 请求
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000; # PHP-FPM 监听地址
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
3.2.3 验证配置并重启 Nginx
/usr/local/nginx/sbin/nginx -t # 验证配置语法
systemctl reload nginx # 平滑重启
四、MySQL/MariaDB 安装与配置
4.1 MariaDB 安装(CentOS 7 推荐)
CentOS 7 官方源中已移除 MySQL,推荐使用开源分支 MariaDB:
yum install -y mariadb mariadb-server
4.2 启动与初始化 MariaDB
systemctl start mariadb
systemctl enable mariadb
# 初始化安全配置(设置 root 密码、删除匿名用户等)
mysql_secure_installation
初始化过程中需按提示操作:
- 输入当前 root 密码(初始为空,直接回车)。
- 设置新的 root 密码。
- 依次确认删除匿名用户、禁止 root 远程登录、删除 test 数据库、重新加载权限表。
4.3 基础数据库操作
4.3.1 登录 MariaDB
mysql -u root -p
输入密码后进入 MariaDB 交互界面。
4.3.2 创建数据库与用户
-- 创建数据库
CREATE DATABASE IF NOT EXISTS test_db DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;
-- 创建用户并授权
CREATE USER 'test_user'@'localhost' IDENTIFIED BY 'your_password';
GRANT ALL PRIVILEGES ON test_db.* TO 'test_user'@'localhost';
FLUSH PRIVILEGES;
4.3.3 备份与恢复数据库
# 备份
mysqldump -u test_user -p test_db > test_db_backup.sql
# 恢复
mysql -u test_user -p test_db < test_db_backup.sql
五、PHP 与 PHP-FPM 安装与配置
5.1 PHP 安装方式
PHP 推荐通过 Remi 源 安装最新稳定版(如 PHP 8.1),或源码编译安装。本文以 Remi 源安装为例:
5.1.1 安装 Remi 源
yum install -y https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum install -y yum-utils
yum-config-manager --enable remi-php81
5.1.2 安装 PHP 及扩展
yum install -y php php-fpm php-mysqlnd php-gd php-xml php-mbstring php-curl php-zip
关键扩展说明:
php-fpm:PHP FastCGI 进程管理器,用于与 Nginx 通信。php-mysqlnd:MySQL 原生驱动,用于连接 MySQL/MariaDB。php-gd:图像处理扩展。php-mbstring:多字节字符串处理扩展。
5.2 PHP-FPM 配置
PHP-FPM 配置文件为 /etc/php-fpm.d/www.conf,核心配置项:
; 运行用户与组(需与 Nginx 一致)
user = nginx
group = nginx
; 监听地址(与 Nginx 配置中 fastcgi_pass 对应)
listen = 127.0.0.1:9000
; 进程管理方式
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 2
pm.max_spare_servers = 8
5.3 启动 PHP-FPM
systemctl start php-fpm
systemctl enable php-fpm
六、LNMP 环境联调与测试
6.1 创建 PHP 测试文件
在 Nginx 网站根目录(如 /usr/local/nginx/html/example)创建 info.php:
<?php
phpinfo();
?>
6.2 访问测试
在浏览器中输入 http://www.example.com/info.php,若显示 PHP 信息页面,则说明 Nginx 与 PHP-FPM 通信正常。
6.3 数据库连接测试
创建 db_test.php 测试 MySQL 连接:
<?php
$host = 'localhost';
$user = 'test_user';
$pass = 'your_password';
$db = 'test_db';
// 创建连接
$conn = mysqli_connect($host, $user, $pass, $db);
// 检查连接
if (!$conn) {
die("连接失败: " . mysqli_connect_error());
}
echo "恭喜你,数据库连接成功!";
mysqli_close($conn);
?>
访问 http://www.example.com/db_test.php,若显示 "数据库连接成功",则 LNMP 环境完整可用。
七、部署 Web 应用(以 Discuz! 为例)
7.1 下载应用程序
cd /usr/local/src
wget https://download.comsenz.com/DiscuzX/3.5/Discuz_X3.5_SC_UTF8.zip
unzip Discuz_X3.5_SC_UTF8.zip
cp -r upload/* /usr/local/nginx/html/example/
7.2 配置文件权限
chown -R nginx:nginx /usr/local/nginx/html/example/
chmod -R 755 /usr/local/nginx/html/example/
7.3 完成安装向导
在浏览器中访问 http://www.example.com/install/index.php,按照向导完成安装:
- 同意协议 → 环境检测 → 配置数据库。
- 输入数据库信息:
- 数据库服务器:
localhost - 数据库名:
test_db - 数据库用户名:
test_user - 数据库密码:
your_password
- 数据库服务器:
- 设置管理员账号密码,完成安装。
7.4 安全加固
安装完成后,删除安装目录:
rm -rf /usr/local/nginx/html/example/install/
八、LNMP 性能优化与安全加固
8.1 Nginx 性能优化
8.1.1 调整 worker 进程数
worker_processes auto; # 自动匹配 CPU 核心数
worker_rlimit_nofile 65535; # 提升文件句柄限制
8.1.2 优化连接数
events {
worker_connections 65535;
multi_accept on;
use epoll;
}
8.1.3 启用缓存与压缩
http {
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
}
8.2 MySQL 性能优化
编辑 /etc/my.cnf,添加以下配置:
[mysqld]
innodb_buffer_pool_size = 1G # 建议为物理内存的 50%-70%
query_cache_type = 0
query_cache_size = 0
max_connections = 1000
wait_timeout = 600
8.3 PHP 性能优化
编辑 /etc/php.ini:
opcache.enable = 1
opcache.memory_consumption = 128
opcache.max_accelerated_files = 10000
opcache.revalidate_freq = 60
8.4 安全加固
-
防火墙配置 :仅开放 80、443、22 端口。
firewall-cmd --permanent --zone=public --add-service=http firewall-cmd --permanent --zone=public --add-service=https firewall-cmd --reload -
HTTPS 加密:配置 Let's Encrypt 免费 SSL 证书,启用 HTTPS。
-
隐藏版本信息 :
server_tokens off; # Nginx expose_php = Off # PHP -
限制访问:配置 Nginx 访问控制,禁止恶意 IP 访问。
九、常见问题排查
9.1 Nginx 无法启动
- 检查端口 80 是否被占用:
netstat -tulnp | grep 80。 - 验证配置语法:
nginx -t。 - 查看错误日志:
/usr/local/nginx/logs/error.log。
9.2 PHP 页面无法解析
- 检查 PHP-FPM 是否启动:
systemctl status php-fpm。 - 确认 Nginx 配置中
fastcgi_pass与 PHP-FPM 监听地址一致。 - 查看 PHP-FPM 日志:
/var/log/php-fpm/error.log。
9.3 数据库连接失败
- 确认 MySQL/MariaDB 服务是否启动。
- 检查数据库用户名、密码、数据库名是否正确。
- 确认用户是否有对应数据库的访问权限。
十、总结与展望
LNMP 架构凭借其高性能、轻量级和可扩展性,已成为现代 Web 开发的主流选择。本文从环境准备、组件安装、配置联调、应用部署到性能优化与安全加固,完整覆盖了 LNMP 网站架构的搭建流程。