温馨提示×

如何在Ubuntu上配置LNMP环境

小樊
37
2025-12-26 01:48:43
栏目: 智能运维

在 Ubuntu 上配置 LNMP 环境的实操步骤

一 准备与安装 Nginx

  • 更新系统并安装 Nginx:
    • sudo apt update && sudo apt upgrade -y
    • sudo apt install nginx -y
  • 启动并设置开机自启:
    • sudo systemctl start nginx
    • sudo systemctl enable nginx
  • 如启用 UFW 防火墙,放行 HTTP/HTTPS:
    • sudo ufw allow ‘Nginx HTTP’
    • sudo ufw allow ‘Nginx HTTPS’
  • 访问服务器 IP,出现 Nginx 欢迎页即表示安装成功。

二 安装与初始化 MySQL

  • 安装 MySQL 服务器:
    • sudo apt install mysql-server -y
  • 运行安全初始化脚本,设置 root 密码并加固:
    • sudo mysql_secure_installation
  • 常用管理命令:
    • 查看状态:sudo systemctl status mysql
    • 设置开机自启:sudo systemctl enable mysql
    • 登录数据库:sudo mysql -u root -p
  • 如需新版或特定版本,可使用 MySQL APT 源安装并选择版本。

三 安装与配置 PHP 及 PHP-FPM

  • 安装 PHP 与常用扩展(以 PHP 8.1 为例,可按需替换为 7.4/8.0/8.2):
    • sudo apt install php-fpm php-mysql php-cli php-curl php-gd php-mbstring php-xml php-zip php-opcache -y
  • 启动并设置开机自启 PHP-FPM(服务名随版本变化,如 php8.1-fpm):
    • sudo systemctl start php8.1-fpm
    • sudo systemctl enable php8.1-fpm
  • 如需多版本共存,可使用 ondrej/php PPA 安装并管理多个 PHP 版本。

四 配置 Nginx 与 PHP-FPM 协同工作

  • 编辑默认站点配置(示例为 /etc/nginx/sites-available/default),在 server 块中加入或修改:
    • 支持 PHP 解析:
      • location ~ .php$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/var/run/php/php8.1-fpm.sock; # 请与已安装版本一致 }
    • 可选:URL 美化(将所有请求转发到 index.php)
      • location / { try_files $uri $uri/ /index.php?$query_string; }
  • 检查配置并重启服务:
    • sudo nginx -t
    • sudo systemctl restart nginx
  • 创建测试文件 /var/www/html/info.php
    • echo “” | sudo tee /var/www/html/info.php
  • 浏览器访问 http://服务器IP/info.php,看到 PHP 信息页即表示成功。

五 常见问题与后续优化

  • 端口占用:Nginx 默认使用 80/443,若启动失败,检查端口占用:
    • sudo lsof -i :80
  • 权限问题:确保 /var/www/run/php 目录权限正确,Nginx 与 PHP-FPM 运行用户可访问网站文件。
  • 防火墙:如使用 UFW,放行 80/443;如使用云厂商安全组,同样需放通对应端口。
  • 日志排查:查看 /var/log/nginx/error.log/var/log/php8.1-fpm.log 定位解析或连接问题。
  • 后续优化与安全:
    • 配置 HTTPS:使用 Certbot 一键申请并自动配置证书
      • sudo apt install certbot python3-certbot-nginx
      • sudo certbot --nginx
    • 性能与安全:启用 OPcache、限制上传大小、关闭暴露版本信息、定期更新系统与组件。

0