温馨提示×

Debian LNMP怎么配置

小樊
35
2026-08-26 01:40:15
栏目: 智能运维

下面给你一份**在 Debian 系统上配置 LNMP(Linux + Nginx + MySQL/MariaDB + PHP)**的完整思路和步骤,适用于 Debian 11 / 12,生产或开发环境都可用。


一、环境说明

  • Linux:Debian 11 (Bullseye) / Debian 12 (Bookworm)
  • Nginx:高性能 Web 服务器
  • MySQL / MariaDB:数据库(Debian 默认推荐 MariaDB)
  • PHP:PHP-FPM 模式(Nginx 最优搭配)

二、更新系统

sudo apt update
sudo apt upgrade -y

三、安装 Nginx

sudo apt install -y nginx

启动并设置开机自启:

sudo systemctl enable nginx
sudo systemctl start nginx

验证:

systemctl status nginx

浏览器访问服务器 IP,看到 Nginx 欢迎页即成功。


四、安装 MariaDB(数据库)

sudo apt install -y mariadb-server

启动并设置自启:

sudo systemctl enable mariadb
sudo systemctl start mariadb

初始化数据库安全设置

sudo mysql_secure_installation

建议:

  • 设置 root 密码 ✅
  • 移除匿名用户 ✅
  • 禁止 root 远程登录 ✅
  • 删除测试数据库 ✅

登录验证

mysql -u root -p

五、安装 PHP(PHP-FPM)

Debian 12 默认 PHP 8.2,11 默认 7.4 / 8.2(取决于源)

sudo apt install -y php php-fpm php-mysql php-curl php-gd php-mbstring php-xml php-zip

查看 PHP 版本:

php -v

查看 PHP-FPM 服务名(很重要):

systemctl list-units | grep php

常见名称:

  • Debian 11:php7.4-fpm
  • Debian 12:php8.2-fpm

启动 PHP-FPM:

sudo systemctl enable php8.2-fpm
sudo systemctl start php8.2-fpm

六、配置 Nginx 支持 PHP

1️⃣ 创建站点目录

sudo mkdir -p /var/www/example.com

2️⃣ 示例 PHP 文件

echo "<?php phpinfo(); ?>" | sudo tee /var/www/example.com/index.php

3️⃣ 配置 Nginx 虚拟主机

sudo nano /etc/nginx/sites-available/example.com

示例配置(重点):

server {
    listen 80;
    server_name example.com www.example.com;

    root /var/www/example.com;
    index index.php index.html index.htm;

    location / {
        try_files $uri $uri/ =404;
    }

    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/run/php/php8.2-fpm.sock;
    }

    location ~ /\.ht {
        deny all;
    }
}

4️⃣ 启用站点

sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/

5️⃣ 测试并重载 Nginx

sudo nginx -t
sudo systemctl reload nginx

七、验证 LNMP 是否成功

浏览器访问:

http://服务器IP

看到 phpinfo() 页面即成功 ✅


八、常见问题排查

❌ 502 Bad Gateway

  • PHP-FPM 未启动
  • fastcgi_pass socket 路径错误

检查:

ls /run/php/
systemctl status php8.2-fpm

❌ Nginx 无法解析 PHP

  • 未配置 location ~ \.php$
  • PHP-FPM 未监听 TCP 或 Unix socket

九、可选优化(生产环境)

✅ 开启 HTTPS(Let’s Encrypt)

sudo apt install certbot python3-certbot-nginx
sudo certbot --nginx

✅ 数据库远程访问(谨慎) ✅ Nginx 开启 Gzip / 缓存 ✅ PHP 调整 upload_max_filesizememory_limit


十、总结

LNMP 在 Debian 上的核心流程:

Nginx → PHP-FPM → PHP → MariaDB

如果你需要:

  • 一键脚本
  • Docker 方式
  • WordPress / Laravel 专用配置
  • Debian + LNMP 生产级安全方案

可以直接告诉我你的使用场景 ✅

0