温馨提示×

如何用debian搭建lnmp

小樊
34
2026-09-28 22:52:20
栏目: 智能运维

下面给你一份**在 Debian(以 Debian 11/12 为例)上搭建 LNMP(Linux + Nginx + MySQL/MariaDB + PHP)**的实用教程,适合新手和服务器部署。


一、系统准备

1. 更新系统

sudo apt update
sudo apt upgrade -y

2. 安装常用工具(可选)

sudo apt install -y curl wget unzip vim git

二、安装 Nginx

sudo apt install -y nginx

启动并设置开机自启:

sudo systemctl start nginx
sudo systemctl enable nginx

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


三、安装 MySQL / MariaDB

方案 A:MariaDB(推荐,Debian 默认)

sudo apt install -y mariadb-server

初始化安全设置:

sudo mysql_secure_installation

方案 B:MySQL

sudo apt install -y mysql-server
sudo mysql_secure_installation

登录数据库测试

sudo mysql

四、安装 PHP

1. 安装 PHP 及常用扩展

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

查看 PHP 版本:

php -v

2. 确认 php-fpm 运行

systemctl status php*-fpm

五、配置 Nginx 支持 PHP

示例站点配置

sudo vim /etc/nginx/sites-available/default

修改为如下内容(示例):

server {
    listen 80;
    server_name your_domain_or_ip;

    root /var/www/html;
    index index.php index.html;

    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

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

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

⚠️ php-fpm.sock 名称可能不同,可用:

ls /run/php/

测试配置并重启

sudo nginx -t
sudo systemctl reload nginx

六、测试 PHP

echo "<?php phpinfo(); ?>" | sudo tee /var/www/html/info.php

浏览器访问:

http://服务器IP/info.php

看到 PHP 信息页即成功(测试完建议删除)。

sudo rm /var/www/html/info.php

七、(可选)防火墙设置

sudo apt install -y ufw
sudo ufw allow 22
sudo ufw allow 80
sudo ufw allow 443
sudo ufw enable

八、(可选)启用 HTTPS(Let’s Encrypt)

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d your_domain.com

九、目录与权限建议

sudo chown -R www-data:www-data /var/www/html
sudo chmod -R 755 /var/www/html

十、常见问题

  • 502 Bad Gateway:php-fpm 未启动或 sock 路径错误
  • 403 Forbidden:目录权限或 index 配置问题
  • 无法连接数据库:检查 bind-address 和用户权限

如果你需要:

  • 多站点配置
  • WordPress / Laravel 部署
  • Docker 版 LNMP
  • 一键脚本(如 lnmp.org)

可以告诉我你的使用场景,我可以进一步细化。

0 踩