在CentOS上搭建Web服务器(如Apache/Nginx)并确保其稳定高效运行,需重点关注以下运维及性能优化要点:
内核参数调整
/etc/sysctl.conf
:conf
net.ipv4.tcp_tw_reuse = 1 # 快速回收TIME_WAIT连接
net.ipv4.tcp_max_tw_buckets = 6000 # 限制TIME_WAIT数量
net.core.somaxconn = 65535 # 提高连接队列长度
vm.swappiness = 10 # 减少Swap使用倾向
sysctl -p
文件描述符限制
/etc/security/limits.conf
:禁用不必要的服务
bash
systemctl stop postfix && systemctl disable postfix
配置优化
/etc/nginx/nginx.conf
:nginx
worker_processes auto; # 自动匹配CPU核心数
worker_connections 10240; # 单个进程最大连接数
keepalive_timeout 65; # 长连接超时
gzip on; # 启用压缩
access_log off; # 高负载时可关闭日志
启用缓存
nginx
location ~* \.(jpg|css|js)$ {
expires 30d;
access_log off;
}
MPM模式选择
event
模式(CentOS 7+默认):apache
<IfModule mpm_event_module>
StartServers 3
MinSpareThreads 75
MaxSpareThreads 250
ThreadsPerChild 25
MaxRequestWorkers 400
</IfModule>
禁用不必要模块
bash
yum remove httpd-mod_php5 # 若使用PHP-FPM
InnoDB配置
/etc/my.cnf
:ini
innodb_buffer_pool_size = 4G # 分配50%-70%可用内存
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2 # 非严格ACID场景可调优
查询缓存
ini
query_cache_type = 0
防火墙配置
bash
firewall-cmd --permanent --add-service={http,https}
firewall-cmd --reload
SELinux策略
bash
setenforce 0 # 临时关闭(生产环境需谨慎)
定期更新
bash
yum update -y && yum upgrade -y
实时监控工具
htop
、nmon
或Prometheus+Grafana
监控资源。goaccess
或ELK
。日志轮转
logrotate
防止日志膨胀:conf
/var/log/nginx/*log {
daily
rotate 30
compress
missingok
}
nginx
listen 443 ssl http2;
top
或perf
定位进程,优化慢查询或代码逻辑。通过以上步骤,可显著提升Web服务器的并发处理能力和稳定性。建议根据实际业务场景进行针对性调优,并通过压力测试(如ab
、wrk
)验证效果。