温馨提示×

如何安装Linux LNMP环境

小樊
41
2026-07-10 22:40:21
栏目: 智能运维

LNMP 是 Linux + Nginx + MySQL/MariaDB + PHP 的常用 Web 运行环境。下面我按最常见、最稳定的方式,给你一套通用安装流程,适用于 CentOS 7/8、Rocky、AlmaLinux、Ubuntu 20.04/22.04


一、安装前准备

1️⃣ 系统更新

# CentOS / Rocky / Alma
yum update -y

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

2️⃣ 关闭 SELinux(CentOS 系列)

setenforce 0
sed -i 's/SELINUX=enforcing/SELINUX=disabled/' /etc/selinux/config

3️⃣ 开放防火墙端口

# firewalld
firewall-cmd --permanent --add-service=http
firewall-cmd --permanent --add-service=https
firewall-cmd --reload

# Ubuntu ufw
ufw allow 80
ufw allow 443

二、安装 Nginx

✅ CentOS / Rocky

yum install -y epel-release
yum install -y nginx

✅ Ubuntu

apt install -y nginx

启动并设置开机自启:

systemctl start nginx
systemctl enable nginx

测试:

curl http://127.0.0.1

三、安装 MySQL / MariaDB

方式一:MySQL(推荐)

CentOS

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

查看初始密码:

grep 'temporary password' /var/log/mysqld.log

初始化:

mysql_secure_installation

Ubuntu

apt install -y mysql-server
mysql_secure_installation

方式二:MariaDB

# CentOS
yum install -y mariadb mariadb-server

# Ubuntu
apt install -y mariadb-server

启动:

systemctl start mariadb
systemctl enable mariadb

四、安装 PHP

✅ CentOS(Remi 源)

yum install -y epel-release
yum install -y https://rpms.remirepo.net/enterprise/remi-release-8.rpm
yum module reset php -y
yum module enable php:remi-8.2 -y
yum install -y php php-fpm php-mysql php-json php-gd php-mbstring php-xml php-curl

✅ Ubuntu

apt install -y php php-fpm php-mysql php-json php-gd php-mbstring php-xml php-curl

启动 PHP-FPM:

systemctl start php-fpm
systemctl enable php-fpm

五、配置 Nginx 支持 PHP

1️⃣ 修改 Nginx 配置

server {
    listen 80;
    server_name your_domain_or_ip;

    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; # CentOS
        # fastcgi_pass   unix:/run/php/php8.2-fpm.sock; # Ubuntu
        fastcgi_index  index.php;
        include fastcgi.conf;
    }
}

2️⃣ 重载 Nginx

nginx -t
systemctl reload nginx

六、测试 PHP

创建测试文件:

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

浏览器访问:

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

✅ 能看到 PHP 信息页面即成功。


七、一键安装方案(推荐)

如果你不想手动配置,可使用成熟脚本:

✅ LNMP 一键安装包(最常用)

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

支持:

  • Nginx
  • MySQL / MariaDB
  • PHP 5.6 ~ 8.2
  • 自动配置

八、常见问题

❓ 502 Bad Gateway

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

❓ PHP 不解析

  • Nginx 未配置 .php 解析
  • PHP-FPM 未监听正确端口或 sock

九、我可以继续帮你

你可以告诉我:

  • ✅ 系统版本(CentOS / Ubuntu)
  • ✅ 是否生产环境
  • ✅ 是否需要 HTTPS(Let’s Encrypt)
  • ✅ 是否部署 WordPress / Laravel

我可以给你完全定制版 LNMP 安装方案

0