在Ubuntu上使用PHP-FPM(FastCGI Process Manager)处理高并发,可以通过以下几个步骤来优化和配置:
首先,确保你已经安装了PHP-FPM。你可以使用以下命令来安装:
sudo apt update sudo apt install php-fpm PHP-FPM的配置文件通常位于 /etc/php/7.x/fpm/pool.d/www.conf(其中 7.x 是你的PHP版本)。你需要根据你的需求调整以下参数:
pm:选择进程管理方式,常用的有 dynamic、ondemand 和 static。
dynamic:根据负载动态调整进程数。ondemand:按需启动进程。static:固定数量的进程。pm = dynamic pm.max_children = 50 pm.start_servers = 5 pm.min_spare_servers = 5 pm.max_spare_servers = 35 request_terminate_timeout:设置请求超时时间,防止长时间运行的脚本占用资源。
request_terminate_timeout = 30s catch_workers_output:捕获工作进程的输出,便于调试。
catch_workers_output = yes 如果你使用的是Nginx或Apache作为Web服务器,需要配置它们以使用PHP-FPM。
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$ { include snippets/fastcgi-php.conf; fastcgi_pass unix:/run/php/php7.x-fpm.sock; # 根据你的PHP版本调整 fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } } <VirtualHost *:80> ServerName example.com DocumentRoot /var/www/html <Directory /var/www/html> Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> <FilesMatch \.php$> SetHandler "proxy:unix:/run/php/php7.x-fpm.sock|fcgi://localhost" </FilesMatch> </VirtualHost> 为了更好地处理高并发,你可能需要调整一些系统参数:
文件描述符限制:增加每个进程可以打开的文件描述符数量。
ulimit -n 65535 你也可以在 /etc/security/limits.conf 中添加以下内容:
* soft nofile 65535 * hard nofile 65535 内核参数:调整TCP参数以提高网络性能。
sudo sysctl -w net.core.somaxconn=4096 sudo sysctl -w net.ipv4.tcp_max_syn_backlog=4096 sudo sysctl -w net.ipv4.ip_local_port_range="1024 65535" 你可以将这些设置添加到 /etc/sysctl.conf 文件中,以便在重启后仍然有效。
使用监控工具(如 htop、top、netdata 等)来监控服务器的性能,并根据实际情况进一步调优PHP-FPM和系统参数。
通过以上步骤,你应该能够在Ubuntu上使用PHP-FPM有效地处理高并发请求。