在Debian系统中优化Nginx的资源占用,可以从多个方面入手,包括配置优化、缓存设置、负载均衡等。以下是一些关键的优化步骤和建议:
调整 worker_processes 和 worker_connections:
worker_processes
通常设置为等于服务器的 CPU 核心数。worker_connections
每个 Worker 进程可以打开的最大连接数,通常设置为 1024 或更高。启用 HTTP/2 协议:
listen 443 ssl http2;
优化 SSL/TLS 配置:
ssl_protocols TLSv1.2 TLSv1.3; ssl_ciphers HIGH:!aNULL:!MD5;
启用文件缓存:
proxy_cache_path /data/nginx/cache levels=1:2 keys_zone=my_cache:10m max_size=10g inactive=60m use_temp_path=off;
使用代理缓存:
location / { proxy_cache my_cache; proxy_pass http://backend; }
启用 Gzip 压缩:
gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 5; gzip_min_length 256; gzip_types text/plain application/xml application/json application/javascript text/css;
负载均衡策略:
upstream backend { server backend1.example.com; server backend2.example.com; least_conn; }
top
, htop
, vmstat
, iostat
等来监控系统资源使用情况,及时发现并解决潜在的性能问题。apt-get autoremove
和 apt-get clean
命令清理不再需要的软件包和缓存。限制并发连接数:
limit_conn_zone
模块来限制同一IP地址的并发连接数。limit_conn_zone $binary_remote_addr zone=one:10m;
server {
listen 80;
server_name localhost;
location /download {
limit conn one;
root html;
index index.html;
}
}
限制访问速率:
limit_req
模块来限制同一IP地址在特定时间段内的访问量。limit_req_zone $limit_key zone=one:10m rate=1r/s;
server {
listen 80;
server_name example.com;
location / {
limit_req zone=one burst=5 nodelay;
proxy_pass http://backend;
}
}
限制流量:
limit_rate
模块来限制同一IP地址的流量。limit_rate 100k;
server {
listen 80;
server_name example.com;
location /download {
root html;
index index.html;
}
}
设置白名单 IP:
geo
模块来定义白名单 IP 列表,白名单中的 IP 不受上述限制。geo $limit {
default 1;
192.168.1.0/24 0;
10.0.0.1 0;
}
map $limit $limit_key {
0 "";
1 $binary_remote_addr;
}
server {
listen 80;
server_name example.com;
location / {
limit_req zone=one burst=5 nodelay if=$limit_key;
proxy_pass http://backend;
}
}
在进行任何重大配置更改之前,建议先在测试环境中验证更改的效果,以确保系统的稳定性和可靠性。