在CentOS上优化PHP性能可以显著提升Web应用程序的响应速度和稳定性。以下是一些关键的优化策略:
sudo yum install php-opcache
echo "zend_extension=/usr/lib64/php/modules/opcache.so" | sudo tee -a /etc/php.ini
echo "opcache.enable=1" | sudo tee -a /etc/php.ini
echo "opcache.memory_consumption=64" | sudo tee -a /etc/php.ini
echo "opcache.max_accelerated_files=4000" | sudo tee -a /etc/php.ini
echo "opcache.revalidate_freq=2" | sudo tee -a /etc/php.ini
echo "opcache.fast_shutdown=1" | sudo tee -a /etc/php.ini
sudo systemctl restart php-fpm
/etc/php-fpm.d/www.conf
文件,调整进程数、内存资源消耗等参数。pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.process_idle_timeout = 10
request_terminate_timeout = 120
rlimit_files = 131072
rlimit_core = unlimited
catch_workers_output = yes
php_admin_value[error_log] = /var/log/php-fpm/www-error.log
php_admin_flag[log_errors] = on
php_value[session.save_handler] = files
php_value[session.save_path] = /var/lib/php/session
php_value[soap.wsdl_cache_dir] = /var/lib/php/wsdlcache
php_value[opcache.save_comments] = 0
php_value[opcache.load_comments] = 0
sudo systemctl restart php-fpm
memory_limit
,例如设置为 memory_limit = 128M
。upload_max_filesize
和 post_max_size
以允许更大的文件上传。safe_mode = Off
expose_php = Off
fastcgi_pass
和 fastcgi_index
参数来优化PHP处理性能。server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html index.htm;
location / {
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php-fpm/php-fpm.sock;
fastcgi_index index.php;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
sudo systemctl restart nginx
sudo yum install memcached
sudo yum install php-pecl-memcached
echo "extension=memcached.so" | sudo tee -a /etc/php.ini
/etc/sysctl.conf
文件,添加或修改以下参数以提高性能。net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_tw_recycle = 1
net.ipv4.tcp_fin_timeout = 30
net.ipv4.tcp_keepalive_time = 1200
net.ipv4.ip_local_port_range = "1024 65535"
net.core.somaxconn = 1024
net.core.netdev_max_backlog = 2000
net.ipv4.tcp_max_orphans = 32768
net.ipv4.tcp_syncookies = 1
sudo sysctl -p
top
、htop
、vmstat
、iostat
等工具,实时监控系统资源使用情况,并分析系统的磁盘、内存、CPU等性能指标。通过上述优化措施,可以显著提高CentOS上PHP应用程序的性能和响应速度。每个应用程序的需求和环境不同,因此在进行性能调优时,建议根据具体情况进行调整,并在开发或测试环境中进行测试后,再在生产环境中应用更改。[1,4,5,6,7,8,9,10,11,12,13,14]