温馨提示×

ubuntu下php-fpm如何配置优化

小樊
40
2025-02-25 19:57:59
栏目: 编程语言
PHP开发者专用服务器限时活动,0元免费领,库存有限,领完即止! 点击查看>>

在 Ubuntu 下优化 PHP-FPM 配置可以显著提升 PHP 应用程序的性能。以下是一些常见的优化步骤和建议:

1. 安装 PHP-FPM

首先,确保你已经安装了 PHP-FPM。你可以使用以下命令来安装:

sudo apt update
sudo apt install php-fpm

2. 配置 PHP-FPM

PHP-FPM 的配置文件通常位于 /etc/php/{version}/fpm/pool.d/www.conf,其中 {version} 是你的 PHP 版本号。例如,如果你使用的是 PHP 7.4,配置文件路径将是 /etc/php/7.4/fpm/pool.d/www.conf

2.1 调整进程管理

编辑 www.conf 文件,调整以下参数:

  • pm:选择进程管理方式,推荐使用 dynamicondemand

    pm = dynamic
    pm.max_children = 50
    pm.start_servers = 5
    pm.min_spare_servers = 5
    pm.max_spare_servers = 35
    
  • pm.max_requests:每个子进程在重启之前可以处理的请求数量,有助于防止内存泄漏。

    pm.max_requests = 500
    

2.2 调整请求处理

  • request_terminate_timeout:设置脚本的最大执行时间。
    request_terminate_timeout = 30s
    

2.3 日志级别

  • catch_workers_output:设置为 yes 可以捕获子进程的输出到主进程日志。
    catch_workers_output = yes
    

3. 配置 Nginx 或 Apache

如果你使用 Nginx 或 Apache 作为 Web 服务器,确保它们的配置与 PHP-FPM 正确集成。

3.1 Nginx 配置

编辑 Nginx 配置文件(通常位于 /etc/nginx/sites-available/default),确保 fastcgi_pass 指向正确的 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.4-fpm.sock; # 根据你的 PHP 版本调整
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
    }
}

3.2 Apache 配置

如果你使用 Apache,确保启用了 proxy_fcgi 模块,并在虚拟主机配置中添加以下内容:

<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. 监控和调优

使用监控工具(如 htopphp-fpm status)来监控 PHP-FPM 的性能,并根据实际情况进一步调整配置参数。

5. 其他优化建议

  • 启用 OPcache:在 php.ini 文件中启用 OPcache 可以显著提高 PHP 脚本的执行速度。

    opcache.enable=1
    opcache.memory_consumption=128
    opcache.interned_strings_buffer=8
    opcache.max_accelerated_files=4000
    opcache.revalidate_freq=60
    
  • 调整数据库连接:如果你使用数据库,确保数据库连接池配置正确,避免频繁的连接和断开操作。

通过以上步骤,你可以有效地优化 Ubuntu 下的 PHP-FPM 配置,提升应用程序的性能。

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

推荐阅读:Ubuntu如何配置PHP-FPM

0