Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

LNMP (Linux + Nginx + MySQL + PHP) 環境手動部署完整紀錄

編輯:Linux 教學

記錄一次基於 CentOS/RHEL 透過 yum 手動部署 LNMP 生產環境的完整流程,涵套套件安裝、核心配置、服務啟動與驗證,適合需要精確控制版本與配置的場景。

環境基線

  • OS:CentOS 6.x / 7.x (示範以 6.x 為主)
  • 架構:x86_64
  • 權限:root 或 sudo

1. 安裝 Nginx

# 加入官方倉庫 (CentOS 7 範例)
rpm -Uvh https://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm
yum install -y nginx

關鍵配置 /etc/nginx/nginx.conf 與 /etc/nginx/conf.d/default.conf:

  • Worker processes:auto
  • 開啟 Gzip、FastCGI 快取
  • 設定 client_max_body_size、proxy_buffers 等效能參數

2. 安裝 MySQL (MariaDB 替代)

yum install -y mariadb-server mariadb
systemctl start mariadb
systemctl enable mariadb
mysql_secure_installation  # 設定 root 密碼、移除匿名用戶、禁止遠端 root 登入等

3. 安裝 PHP 與 PHP-FPM

# CentOS 7 預設 PHP 5.4 較舊,建議啟用 Remi 倉庫安裝 PHP 7.x/8.x
yum install -y epel-release
yum install -y https://rpms.remirepo.net/enterprise/remi-release-7.rpm
yum-config-manager --enable remi-php81
yum install -y php php-fpm php-mysqlnd php-opcache php-gd php-mbstring php-xml php-curl php-zip

PHP-FPM 配置 /etc/php-fpm.d/www.conf:

user = nginx
group = nginx
listen = 127.0.0.1:9000
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35

4. Nginx 整合 PHP-FPM

/etc/nginx/conf.d/php.conf:


server {
    listen 80;
    server_name example.com;
    root /usr/share/nginx/html;
    index index.php index.html;

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

    location ~ \.php$ {
        fastcgi_pass 127.0.0.1:9000;
        fastcgi_index index.php;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_intercept_errors on;
    }
}

5. 啟動與驗證服務


systemctl start nginx php-fpm mariadb
systemctl enable nginx php-fpm mariadb

# 驗證 PHP 處理
echo "" > /usr/share/nginx/html/info.php
curl -I https://localhost/info.php

6. 常見優化與安全加固

  • Nginx:啟用 limit_req_zone 限流、隱藏版本號 server_tokens off、配置 SSL/TLS (Let's Encrypt)
  • PHP:open_basedir 限制目錄、disable_functions 禁用危險函式、OPcache 調優
  • MySQL:innodb_buffer_pool_size 設為實體記憶體 70%、啟用慢查詢日誌、定期備份
  • 防火牆:firewall-cmd --permanent --add-service={http,https}
  • SELinux:設定 setsebool -P httpd_can_network_connect 1 允許 PHP 連外部資料庫

版本資訊快速查詢


nginx -v
php -v
mysql --version

總結

手動部署 LNMP 雖較單鍵腳本繁瑣,但能精確掌控每個元件版本、配置細節與安全策略,利於生產環境的標準化、可複現與審計。建議將配置檔納入版控 (Git),並撰寫 Ansible/Playbook 實現基礎設施即代碼 (IaC)。

Copyright © Windows教程網 All Rights Reserved