提升网站可用性的 Apache2 配置实践
一 架构与冗余
<Proxy balancer://mycluster>
BalancerMember http://10.0.0.11:80
BalancerMember http://10.0.0.12:80
</Proxy>
ProxyPass / balancer://mycluster
ProxyPassReverse / balancer://mycluster
ProxySet lbmethod byrequests
若使用独立负载均衡器,可在多台 Apache 前再放置 HAProxy 做连接复用与健康检查。#!/usr/bin/env bash
if systemctl is-active --quiet apache2; then exit 0; else exit 1; fi
以上组合可在实例、进程、连接三个层面消除单点,显著提升整体可用性。二 运行时稳定性与并发能力
sudo a2dismod mpm_prefork
sudo a2enmod mpm_event
sudo systemctl restart apache2
三 关键配置示例
KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 2
Timeout 30
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>
<IfModule mod_cache_disk.c>
CacheEnable disk /
CacheRoot "/var/cache/apache2"
CacheDirLevels 2
CacheDirLength 1
</IfModule>
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access plus 1 year"
ExpiresByType image/jpeg "access plus 1 year"
ExpiresByType image/png "access plus 1 year"
ExpiresByType text/css "access plus 1 month"
ExpiresByType application/javascript "access plus 1 month"
ExpiresDefault "access plus 2 days"
</IfModule>
<Location "/server-status">
SetHandler server-status
Require local
</Location>
以上参数能显著降低握手与传输开销、提升缓存命中、减少日志抖动,并在故障时更快收敛。
四 运维与监控
ulimit -n 65535),并合理设置内核网络参数(如 net.core.somaxconn、net.ipv4.tcp_tw_reuse)以减少连接排队与资源枯竭风险。htop、sar)与日志分析,建立关键指标(5xx 比例、连接数、响应时延)的阈值告警,提前识别可用性风险。五 变更与验证流程
apache2ctl configtest 确认语法无误;启用必要模块(如 a2enmod ssl cache disk_cache deflate status proxy proxy_balancer)。systemctl reload apache2,确保长连接不断开、现有请求完成后再切换。