PHP-FPM在Ubuntu上如何负载均衡

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

在Ubuntu上使用PHP-FPM进行负载均衡,通常涉及以下几个步骤:

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

    sudo apt update
    sudo apt install php-fpm
    
  2. 配置PHP-FPM池: PHP-FPM使用池(pool)来管理不同的PHP进程。你需要为每个Web服务器配置一个池。编辑或创建一个新的池配置文件,例如/etc/php/7.4/fpm/pool.d/www.conf(根据你的PHP版本调整路径)。

    [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 = 5
    pm.start_servers = 2
    pm.min_spare_servers = 1
    pm.max_spare_servers = 3
    
  3. 配置Nginx或Apache: 使用Nginx或Apache作为反向代理来分发请求到多个PHP-FPM实例。

    • Nginx配置: 编辑Nginx的配置文件,例如/etc/nginx/sites-available/default,添加以下内容:

      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配置: 如果你使用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>
      
          ProxyPassMatch ^/(.*\.php(/.*)?)$ fcgi://unix:/run/php/php7.4-fpm.sock|fcgi://localhost:9000/var/www/html/$1
      </VirtualHost>
      
  4. 启动和启用服务: 启动PHP-FPM和Nginx或Apache服务,并设置它们在系统启动时自动运行。

    sudo systemctl start php7.4-fpm
    sudo systemctl enable php7.4-fpm
    
    sudo systemctl start nginx
    sudo systemctl enable nginx
    
    # 或者对于Apache
    sudo systemctl start apache2
    sudo systemctl enable apache2
    
  5. 负载均衡: 如果你有多个PHP-FPM实例,可以使用Nginx的upstream模块来实现负载均衡。编辑Nginx配置文件,添加以下内容:

    upstream php_backend {
        server unix:/run/php/php7.4-fpm.sock;
        server unix:/run/php/php7.5-fpm.sock; # 另一个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 php_backend;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }
    

    确保每个PHP-FPM实例的配置文件(如/etc/php/7.4/fpm/pool.d/www.conf)中的listen指令指向不同的Unix套接字或TCP端口。

通过以上步骤,你可以在Ubuntu上使用PHP-FPM进行负载均衡。

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

推荐阅读: Ubuntu Node.js日志监控工具推荐