ubuntu

php-fpm在ubuntu下如何实现负载均衡

小樊
50
2025-08-01 11:29:05
栏目: 云计算

在Ubuntu下,可以使用Nginx作为反向代理服务器来实现PHP-FPM的负载均衡。以下是配置步骤:

  1. 安装Nginx:
sudo apt-get update
sudo apt-get install nginx
  1. 安装PHP-FPM:
sudo apt-get install php-fpm
  1. 配置PHP-FPM:

编辑/etc/php/7.x/fpm/pool.d/www.conf文件,设置listen参数为一个Unix套接字文件,例如:

listen = /run/php/php7.x-fpm.sock

其中7.x是你的PHP版本号。然后重启PHP-FPM服务:

sudo systemctl restart php7.x-fpm
  1. 配置Nginx:

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

http {
    upstream php_fpm {
        server unix:/run/php/php7.x-fpm.sock;
        # 如果有多个PHP-FPM实例,可以添加更多server块
        # server unix:/run/php/php7.x-fpm2.sock;
    }

    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_fpm;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            include fastcgi_params;
        }
    }
}

其中example.com是你的域名,/var/www/html是你的网站根目录。如果有多个PHP-FPM实例,可以在upstream块中添加更多server块,并使用不同的Unix套接字文件。

  1. 重启Nginx服务:
sudo systemctl restart nginx

现在,Nginx会将PHP请求分发到配置的PHP-FPM实例,实现负载均衡。如果需要进一步优化性能,可以考虑使用HTTP/2、HTTP/3、TLS等技术。

0
看了该问题的人还看了