在優化前,需先明確資源占用的具體情況,避免盲目調整:
top -p $(pgrep nginx | tr '\n' ',')
實時查看Nginx進程的CPU、內存占用;ps -o pid,rss,command -p $(pgrep nginx)
查看每個進程的實際物理內存(RSS)消耗。pmap -x $(pgrep nginx | head -n1) | tail -n 10
查看單個Nginx進程的內存映射,識別內存消耗高的模塊(如緩存、緩沖區)。tail -f /var/log/nginx/error.log | grep -i "memory"
查看錯誤日志中的內存相關警告;使用vmstat 1 3
監控系統內存使用趨勢,判斷是否存在內存泄漏。worker_processes
設置為CPU核心數(auto
可自動匹配),避免過多進程導致上下文切換開銷。例如:worker_processes auto;
events
塊中,根據服務器內存和CPU調整worker_connections
(每個worker的最大連接數),一般設置為1024-4096。例如:events {
worker_connections 2048;
multi_accept on; # 批量接受連接,減少上下文切換
}
http {
client_body_buffer_size 8k; # 客戶端請求體緩沖區
client_max_body_size 10m; # 限制上傳文件大?。ǜ鶕枨笳{整)
large_client_header_buffers 4 8k; # 請求頭緩沖區(默認4個16k,可減?。?/span>
}
proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;
server {
location /static/ {
proxy_cache my_cache;
proxy_pass http://backend;
proxy_cache_valid 200 302 10m; # 緩存200/302狀態碼10分鐘
}
}
proxy_cache
、fastcgi_cache
等模塊,避免內存浪費。keepalive_timeout
(默認75s),減少空閑連接的資源占用。例如:http {
keepalive_timeout 30s; # 根據業務調整(如30s-60s)
keepalive_requests 100; # 每個連接最多處理100個請求
}
/etc/sysctl.conf
中添加以下配置,優化TCP連接處理:net.ipv4.tcp_tw_reuse = 1 # 復用TIME-WAIT連接
net.ipv4.tcp_fin_timeout = 30 # TIME-WAIT超時30秒
net.core.somaxconn = 4096 # 監聽隊列最大長度
vm.swappiness = 10 # 減少Swap使用(0-100,值越小越優先用內存)
執行sysctl -p
使配置生效。dd if=/dev/zero of=/swapfile bs=1G count=8
chmod 600 /swapfile
mkswap /swapfile
swapon /swapfile
永久生效可添加/swapfile none swap sw 0 0
到/etc/fstab
。apt-get clean
刪除已下載的軟件包緩存。rm -rf /var/log/nginx/*.log
刪除舊日志(需提前備份),或使用logrotate
自動輪轉日志。limit_conn
模塊限制單個IP的并發連接數,防止惡意請求占用資源。例如:limit_conn_zone $binary_remote_addr zone=perip:10m;
server {
location / {
limit_conn perip 20; # 每個IP最多20個并發連接
}
}
proxy_cache off; # 關閉代理緩存
# ssl_session_cache shared:SSL:20m; # 注釋掉SSL會話緩存
nginx -s reload
重新加載配置,避免直接restart
導致連接中斷;若內存占用過高,可使用systemctl restart nginx
強制重啟(需謹慎)。Prometheus + Grafana
監控Nginx的active connections
、memory usage
、request rate
等指標,設置告警閾值(如內存使用率>80%時報警)。nginx -t
定期驗證配置文件語法,避免錯誤配置導致資源浪費;通過nginx -V
查看已啟用的模塊,禁用不必要的模塊(如--with-http_gunzip_module
若無需gzip解壓)。通過以上步驟,可系統性解決Debian下Nginx資源占用高的問題,兼顧短期應急與長期穩定性。優化過程中需根據服務器實際負載(如并發量、靜態資源占比)調整參數,避免過度優化。