LNMP服务器的资源限制实践指南
一 系统级限制
文件描述符与进程数
* soft nofile 65535
* hard nofile 65535
worker_rlimit_nofile 65535;
events {
worker_connections 16384;
}
内核网络与端口
net.core.somaxconn = 32768
net.ipv4.ip_local_port_range = 1024 65535
net.core.netdev_max_backlog = 32768
net.ipv4.tcp_max_syn_backlog = 65536
net.ipv4.tcp_tw_reuse = 1
sysctl -p使配置生效。上述参数有助于在高并发下减少连接丢弃与队列溢出。容器场景(可选)
docker run -d --name nginx --memory=500m --memory-swap=1g nginx:latest
docker run -d --name mysql --device-write-bps /dev/sda:10mb mysql:8.0
二 Nginx层限制
http {
limit_req_zone $binary_remote_addr zone=req_limit:10m rate=10r/s;
server {
location / {
limit_req zone=req_limit burst=20 nodelay;
}
}
}
http {
limit_conn_zone $binary_remote_addr zone=conn_limit:10m;
server {
limit_conn conn_limit 20; # 每IP并发
limit_conn_status 429; # 可选:返回429而非503
}
}
location /download/ {
limit_rate 100k;
}
sudo yum install fail2ban -y
# 配置 /etc/fail2ban/jail.local
[DEFAULT]
bantime = 600
findtime = 600
maxretry = 3
[nginx]
enabled = true
filter = nginx
action = iptables-multiport[name=nginx, port="http,https", protocol=tcp]
logpath = /var/log/nginx/access.log
三 PHP-FPM层限制
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 2
pm.max_spare_servers = 8
pm.max_requests = 10000 # 防止内存泄漏累积
memory_limit = 128M
max_execution_time = 30
request_terminate_timeout = 30
四 MySQL MariaDB层限制
max_connections = 150
innodb_buffer_pool_size = 2G
五 监控与容量规划