在Ubuntu上使用PHP-FPM(FastCGI Process Manager)进行负载均衡,通常涉及以下几个步骤:
安装PHP-FPM: 首先,确保你的Ubuntu系统上已经安装了PHP-FPM。你可以使用以下命令来安装:
sudo apt update
sudo apt install php-fpm
配置PHP-FPM:
PHP-FPM的配置文件通常位于/etc/php/{version}/fpm/pool.d/www.conf,其中{version}是你的PHP版本号。你需要根据你的需求调整这个配置文件。
设置多个PHP-FPM池:
为了实现负载均衡,你可以设置多个PHP-FPM池。每个池可以运行在不同的端口或不同的Unix套接字上。编辑/etc/php/{version}/fpm/pool.d/www.conf文件,添加或修改以下内容:
[pool1]
listen = 127.0.0.1:9001
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
[pool2]
listen = 127.0.0.1:9002
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
配置Nginx:
使用Nginx作为反向代理服务器来分发请求到不同的PHP-FPM池。编辑Nginx的配置文件(通常位于/etc/nginx/sites-available/default),添加以下内容:
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.php index.html index.htm;
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass unix:/var/run/php/php7.4-fpm.sock; # 默认池
fastcgi_pass unix:/var/run/php/php7.4-fpm-pool1.sock; # 第一个池
fastcgi_pass unix:/var/run/php/php7.4-fpm-pool2.sock; # 第二个池
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
启动PHP-FPM池: 启动每个PHP-FPM池:
sudo systemctl start php{version}-fpm@pool1
sudo systemctl start php{version}-fpm@pool2
配置负载均衡策略:
你可以使用Nginx的upstream模块来配置负载均衡策略。编辑Nginx配置文件,添加以下内容:
upstream php_backend {
server unix:/var/run/php/php7.4-fpm.sock; # 默认池
server unix:/var/run/php/php7.4-fpm-pool1.sock; # 第一个池
server unix:/var/run/php/php7.4-fpm-pool2.sock; # 第二个池
least_conn; # 使用最少连接数策略
}
server {
listen 80;
server_name example.com;
location / {
root /var/www/html;
index index.php index.html index.htm;
try_files $uri $uri/ =404;
}
location ~ \.php$ {
fastcgi_pass php_backend;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
}
重启Nginx: 最后,重启Nginx以应用配置更改:
sudo systemctl restart nginx
通过以上步骤,你可以在Ubuntu上使用PHP-FPM进行负载均衡。每个PHP-FPM池可以运行在不同的端口或Unix套接字上,并通过Nginx进行请求分发。