CentOS Apache2如何优化并发连接

724
2025/3/15 15:32:11
栏目: 智能运维
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在CentOS上优化Apache2以处理更多的并发连接,可以通过以下几个方面来实现:

1. 调整Apache配置文件

Apache的主要配置文件是/etc/httpd/conf/httpd.conf/etc/apache2/apache2.conf(取决于你的CentOS版本)。以下是一些关键配置项:

a. StartServers

控制启动时创建的服务器进程数。默认值通常是5。

StartServers 5

b. MinSpareServersMaxSpareServers

控制空闲服务器进程的最小和最大数量。

MinSpareServers 5
MaxSpareServers 10

c. MaxRequestWorkers

控制Apache可以同时处理的最大请求数。这个值应该根据服务器的内存和CPU资源来设置。

MaxRequestWorkers 256

d. MaxConnectionsPerChild

控制每个服务器进程可以处理的最大请求数,以防止内存泄漏。

MaxConnectionsPerChild 1000

2. 启用KeepAlive

KeepAlive允许客户端在一个TCP连接上发送多个请求,减少连接建立和关闭的开销。

KeepAlive On
MaxKeepAliveRequests 100
KeepAliveTimeout 5

3. 调整模块

确保只加载必要的模块,减少内存占用。

LoadModule mpm_prefork_module modules/mod_mpm_prefork.so
LoadModule mpm_event_module modules/mod_mpm_event.so
LoadModule mpm_worker_module modules/mod_mpm_worker.so

# 选择合适的MPM模块
<IfModule mpm_prefork_module>
    StartServers 5
    MinSpareServers 5
    MaxSpareServers 10
    MaxRequestWorkers 256
    MaxConnectionsPerChild 1000
</IfModule>

<IfModule mpm_event_module>
    StartServers 2
    MinSpareThreads 25
    MaxSpareThreads 75
    ThreadLimit 64
    ThreadsPerChild 25
    MaxRequestWorkers 256
    MaxConnectionsPerChild 0
</IfModule>

<IfModule mpm_worker_module>
    StartServers 2
    MinSpareThreads 25
    MaxSpareThreads 75
    ThreadLimit 64
    ThreadsPerChild 25
    MaxRequestWorkers 256
    MaxConnectionsPerChild 0
</IfModule>

4. 调整文件描述符限制

确保系统可以打开足够的文件描述符来处理并发连接。

ulimit -n 65535

编辑/etc/security/limits.conf文件,添加以下内容:

* soft nofile 65535
* hard nofile 65535

5. 调整内核参数

编辑/etc/sysctl.conf文件,添加或修改以下内容:

net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535
net.ipv4.ip_local_port_range = 1024 65535
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_fin_timeout = 30

然后运行以下命令使更改生效:

sysctl -p

6. 使用缓存

使用缓存模块(如mod_cachemod_expires)来减少对后端服务器的请求。

LoadModule cache_module modules/mod_cache.so
LoadModule cache_disk_module modules/mod_cache_disk.so
LoadModule expires_module modules/mod_expires.so

<IfModule mod_expires.c>
    ExpiresActive On
    ExpiresByType text/html "access plus 1 month"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
</IfModule>

<IfModule mod_cache.c>
    <IfModule mod_cache_disk.c>
        CacheRoot "/var/cache/apache2/mod_cache_disk"
        CacheEnable disk /
        CacheDirLevels 2
        CacheDirLength 1
    </IfModule>
</IfModule>

7. 监控和调优

使用工具如ab(Apache Bench)或siege来测试服务器的性能,并根据测试结果进一步调优配置。

通过以上步骤,你可以显著提高CentOS上Apache2的并发连接处理能力。记得在每次更改配置后重启Apache服务:

systemctl restart httpd

systemctl restart apache2

根据你的具体需求和环境,可能需要进一步调整这些参数。

辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>

推荐阅读: centos dolphin日志分析