ubuntu如何利用php-fpm提升网站性能

643
2025/3/10 15:31:33
栏目: 云计算
开发者测试专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在Ubuntu系统中,利用PHP-FPM(FastCGI Process Manager)可以显著提升PHP网站的性能。以下是一些关键步骤和最佳实践:

1. 安装PHP-FPM

首先,确保你的系统上已经安装了PHP和PHP-FPM。你可以使用以下命令来安装它们:

sudo apt update
sudo apt install php-fpm php-cli

2. 配置PHP-FPM

PHP-FPM的配置文件通常位于/etc/php/{version}/fpm/pool.d/www.conf。你可以根据需要编辑这个文件来优化性能。

关键配置项:

  • pm:选择进程管理方式,常用的有dynamicondemandstatic
    • dynamic:根据负载动态调整进程数。
    • ondemand:按需启动进程。
    • static:固定数量的进程。
  • pm.max_children:最大子进程数。
  • pm.start_servers:启动时的服务器进程数。
  • pm.min_spare_servers:最小空闲服务器进程数。
  • pm.max_spare_servers:最大空闲服务器进程数。
  • request_terminate_timeout:请求超时时间。

例如,如果你选择dynamic模式,可以这样配置:

[www]
listen = /run/php/php7.4-fpm.sock
listen.owner = www-data
listen.group = www-data
user = www-data
group = www-data
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
request_terminate_timeout = 30s

3. 配置Nginx或Apache

如果你使用的是Nginx或Apache作为Web服务器,你需要配置它们以使用PHP-FPM处理PHP请求。

Nginx配置示例:

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.4-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

Apache配置示例:

<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.4-fpm.sock|fcgi://localhost"
    </FilesMatch>
</VirtualHost>

4. 启动和监控PHP-FPM

启动PHP-FPM服务并设置开机自启动:

sudo systemctl start php7.4-fpm
sudo systemctl enable php7.4-fpm

你可以使用以下命令来监控PHP-FPM的状态和性能:

sudo systemctl status php7.4-fpm
sudo tail -f /var/log/php7.4-fpm.log

5. 其他优化建议

  • 使用OPcache:OPcache可以显著提高PHP脚本的执行速度。确保在php.ini中启用了OPcache。
    opcache.enable=1
    opcache.memory_consumption=128
    opcache.interned_strings_buffer=8
    opcache.max_accelerated_files=4000
    
  • 调整文件描述符限制:确保PHP-FPM有足够的文件描述符可用。
    ulimit -n 65535
    
  • 使用持久连接:在数据库连接中使用持久连接可以减少连接开销。

通过以上步骤和优化,你可以显著提升使用PHP-FPM的Ubuntu网站的性能。

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

推荐阅读: ubuntu软连接怎样修改目标路径