在Linux系统中,使用PHP-FPM(FastCGI Process Manager)实现负载均衡可以通过多种方式来完成。以下是几种常见的方法:
Nginx是一个高性能的HTTP和反向代理服务器,可以很好地与PHP-FPM配合使用来实现负载均衡。
安装Nginx:
sudo apt update
sudo apt install nginx
配置Nginx:
编辑Nginx配置文件(通常位于/etc/nginx/nginx.conf
或/etc/nginx/sites-available/default
),添加以下内容:
http {
upstream php_fpm {
server unix:/var/run/php/php7.4-fpm.sock; # 根据实际情况修改
# server 192.168.1.1:9000;
# server 192.168.1.2:9000;
}
server {
listen 80;
server_name example.com;
root /var/www/html;
index index.php index.html index.htm;
location ~ \.php$ {
fastcgi_pass php_fpm;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_param PATH_INFO $fastcgi_path_info;
}
location / {
try_files $uri $uri/ =404;
}
}
}
重启Nginx:
sudo systemctl restart nginx
HAProxy是一个专业的负载均衡器,可以处理大量的并发连接,并且支持多种负载均衡算法。
安装HAProxy:
sudo apt update
sudo apt install haproxy
配置HAProxy:
编辑HAProxy配置文件(通常位于/etc/haproxy/haproxy.cfg
),添加以下内容:
global
log /dev/log local0
log /dev/log local1 notice
daemon
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
frontend http_front
bind *:80
default_backend http_back
backend http_back
balance roundrobin
server php_fpm1 unix:/var/run/php/php7.4-fpm.sock check
server php_fpm2 unix:/var/run/php/php7.4-fpm.sock check
重启HAProxy:
sudo systemctl restart haproxy
PHP-FPM本身支持多进程模式,可以通过配置www.conf
文件来启动多个进程和子进程,从而实现负载均衡。
编辑www.conf
文件:
sudo nano /etc/php/7.4/fpm/pool.d/www.conf
修改以下参数:
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
重启PHP-FPM:
sudo systemctl restart php7.4-fpm
以上方法都可以实现PHP-FPM的负载均衡,具体选择哪种方法取决于你的具体需求和环境。Nginx和HAProxy都是非常流行的选择,它们提供了强大的功能和灵活的配置选项。而PHP-FPM的多进程模式则是一种简单直接的方法,适用于负载不是特别高的场景。