温馨提示×

怎样部署linux lnmp

小樊
33
2026-09-15 20:59:30
栏目: 智能运维

下面给你一份从零部署 Linux LNMP(Linux + Nginx + MySQL/MariaDB + PHP)的实用指南,适用于 CentOS 7/8、Ubuntu 20.04/22.04 等常见发行版。你可以按需选择手动部署一键脚本


一、环境准备

1. 系统更新

# CentOS
yum update -y

# Ubuntu / Debian
apt update && apt upgrade -y

2. 关闭防火墙(测试环境,生产请配置规则)

systemctl stop firewalld
systemctl disable firewalld

# Ubuntu
ufw disable

二、手动部署 LNMP(推荐学习使用)

1️⃣ 安装 Nginx

# CentOS
yum install nginx -y
systemctl enable nginx
systemctl start nginx

# Ubuntu
apt install nginx -y
systemctl enable nginx
systemctl start nginx

验证:

curl http://localhost

2️⃣ 安装 MySQL / MariaDB

MySQL(CentOS)

yum install mysql-server -y
systemctl enable mysqld
systemctl start mysqld

MariaDB(Ubuntu)

apt install mariadb-server -y
systemctl enable mariadb
systemctl start mariadb

初始化数据库:

mysql_secure_installation

创建测试用户:

CREATE DATABASE testdb;
CREATE USER 'testuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL ON testdb.* TO 'testuser'@'localhost';
FLUSH PRIVILEGES;

3️⃣ 安装 PHP

# CentOS
yum install php php-fpm php-mysqlnd -y

# Ubuntu
apt install php-fpm php-mysql -y

启动 PHP-FPM:

systemctl enable php-fpm
systemctl start php-fpm

4️⃣ 配置 Nginx 支持 PHP

编辑站点配置:

vim /etc/nginx/conf.d/default.conf

示例配置:

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   unix:/run/php-fpm/www.sock;
        fastcgi_index  index.php;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        include        fastcgi_params;
    }
}

重启 Nginx:

nginx -t
systemctl restart nginx

测试 PHP:

echo "<?php phpinfo(); ?>" > /usr/share/nginx/html/index.php

三、一键部署(生产/快速环境)

✅ 使用 LNMP 一键脚本(非常流行)

wget http://soft.vpser.net/lnmp/lnmp2.0.tar.gz
tar zxf lnmp2.0.tar.gz
cd lnmp2.0
./install.sh lnmp

支持:

  • Nginx
  • MySQL / MariaDB
  • PHP 多版本
  • 自动优化配置

四、常见问题

❌ 502 Bad Gateway

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

❌ 访问不到

  • 防火墙未放开 80 端口
  • Nginx 未启动

五、推荐目录

组件 路径
Nginx /etc/nginx
PHP /etc/php
MySQL /var/lib/mysql
Web根目录 /usr/share/nginx/html

如果你告诉我:

  • ✅ 使用的 Linux 发行版
  • ✅ 是否 生产环境
  • ✅ 是否需要 多 PHP 版本 / HTTPS

我可以给你更精确的部署方案。

0