首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

Nginx + Tomcat 生產級配置:動靜分離、負載均衡、緩存優化與安全加固

     編輯:Java 綜合教學

Nginx 基礎管理

  • 啟動:雙擊 nginx.exe,任務管理器出現兩個進程即成功;
  • 常用命令:
    nginx -s stop 強制關閉 | nginx -s quit 優雅關閉 | nginx -s reload 熱加載配置 | nginx -s reopen 重啟日誌

核心配置文件解析(nginx.conf 精簡版)

worker_processes 1;  # 建議 = CPU 核心數或 2倍
events {
    worker_connections 1024;
    # use epoll;  # Linux 高併發必開
}
http {
    include mime.types;
    default_type application/octet-stream;
    sendfile on;
    keepalive_timeout 65;

    # Gzip 壓縮
    gzip on;
    gzip_min_length 1k;
    gzip_buffers 4 16k;
    gzip_comp_level 2;
    gzip_types text/plain application/x-javascript text/css application/xml;
    gzip_vary on;

    # 靜態文件緩存
    open_file_cache max=655350 inactive=20s;
    open_file_cache_valid 30s;
    open_file_cache_min_uses 2;

    # 負載均衡上游組
    upstream hostname {
        server 127.0.0.1:9000 max_fails=0 weight=2;
        server 127.0.0.1:9001 max_fails=0 weight=2;
    }

    server {
        listen 8181;
        server_name localhost;
        root /img;  # 靜態資源目錄

        # 所有動態請求反向代理
        location / {
            proxy_pass https://hostname;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme;
            proxy_redirect default;  # 關鍵:修正 302 重定向 Host,防後端 IP 暴露
            client_max_body_size 10m;
            client_body_buffer_size 128k;
            proxy_connect_timeout 90;
            proxy_read_timeout 90;
            proxy_buffer_size 4k;
            proxy_buffers 6 32k;
            proxy_busy_buffers_size 64k;
            proxy_temp_file_write_size 64k;
        }

        # 動靜分離:靜態資源直讀
        location ~\.(gif|jpg|jpeg|png|css|js|php)$ {
            root /usr/nginxStaticFile;  # 靜態文件發布目錄
            expires 7d;  # 瀏覽器緩存 7 天
        }

        # Nginx 狀態監控頁
        location /nginxstatus {
            stub_status on;
            access_log on;
        }

        error_page 500 502 503 504 /50x.html;
        location = /50x.html { root html; }
    }
}

關鍵配置深度解讀

配置塊作用生產建議
upstream + weight負載均衡分流根據服務器性能分配權重,max_fails+fail_timeout 實現故障自動剔除
proxy_redirect default修正 302 Location Host必開,否則重定向暴露後端真實 IP/端口
動靜分離 location 正則靜態資源 Nginx 直讀配合 expires 減輕後端壓力,CDN 前置更佳
proxy_buffers/buffer_size代理緩衝區調優根據頁面平均大小調整,減少磁盤臨時文件
stub_status監控活躍連接、請求數配合 Prometheus/Grafana 做可視化告警

Windows 與 Linux 差異提示

  • Windows 無需 use epoll,Linux 高併發必開;
  • 靜態資源 root 路徑按實際部署調整;
  • 上游 server 填寫真實 Tomcat 實例 IP:Port。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved