在Linux系统下,使用PHP-FPM(FastCGI Process Manager)进行负载均衡可以通过多种方式实现。以下是几种常见的方法:
Nginx是一个高性能的HTTP和反向代理服务器,可以很好地与PHP-FPM配合使用。
安装Nginx:
sudo apt-get update
sudo apt-get install nginx
配置PHP-FPM:
确保PHP-FPM已经在运行,并且配置文件(通常是/etc/php/7.x/fpm/pool.d/www.conf)中设置了监听地址和端口。
listen = /run/php/php7.x-fpm.sock
配置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.x-fpm.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
重启Nginx:
sudo systemctl restart nginx
HAProxy是一个专业的负载均衡器,可以与PHP-FPM配合使用。
安装HAProxy:
sudo apt-get update
sudo apt-get install haproxy
配置PHP-FPM:
确保PHP-FPM已经在运行,并且配置文件(通常是/etc/php/7.x/fpm/pool.d/www.conf)中设置了监听地址和端口。
listen = /run/php/php7.x-fpm.sock
配置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 php1 unix:/run/php/php7.x-fpm.sock check
server php2 unix:/run/php/php7.x-fpm.sock check
重启HAProxy:
sudo systemctl restart haproxy
PHP-FPM支持配置多个池,每个池可以有不同的配置和监听地址。
编辑PHP-FPM配置文件:
编辑/etc/php/7.x/fpm/pool.d/www.conf,复制一份并修改监听地址和端口。
[www1]
listen = /run/php/php7.x-fpm-www1.sock
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
[www2]
listen = /run/php/php7.x-fpm-www2.sock
pm = dynamic
pm.max_children = 5
pm.start_servers = 2
pm.min_spare_servers = 1
pm.max_spare_servers = 3
配置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.x-fpm-www1.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
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.x-fpm-www2.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
重启PHP-FPM和Nginx:
sudo systemctl restart php7.x-fpm
sudo systemctl restart nginx
通过以上方法,你可以在Linux系统下使用PHP-FPM进行负载均衡。选择哪种方法取决于你的具体需求和环境。