在Ubuntu系统中,使用PHP-FPM(FastCGI Process Manager)实现负载均衡可以通过多种方式来完成。以下是一些常见的方法:
安装Nginx:
sudo apt update
sudo apt install nginx
配置Nginx:
编辑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$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm.sock; # 根据你的PHP版本调整
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
启用配置: 创建符号链接以启用配置:
sudo ln -s /etc/nginx/sites-available/default /etc/nginx/sites-enabled/
重启Nginx:
sudo systemctl restart nginx
安装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 server1 192.168.1.101:80 check
server server2 192.168.1.102:80 check
重启HAProxy:
sudo systemctl restart haproxy
安装多个PHP-FPM实例: 你可以为每个PHP-FPM实例配置不同的socket文件。
sudo cp /etc/php/7.4/fpm/pool.d/www.conf /etc/php/7.4/fpm/pool.d/www1.conf
sudo cp /etc/php/7.4/fpm/pool.d/www.conf /etc/php/7.4/fpm/pool.d/www2.conf
编辑配置文件:
编辑www1.conf
和www2.conf
,修改listen
参数:
; www1.conf
listen = /run/php/php7.4-fpm-www1.sock
; www2.conf
listen = /run/php/php7.4-fpm-www2.sock
重启PHP-FPM:
sudo systemctl restart php7.4-fpm
配置Nginx:
编辑Nginx配置文件,添加多个fastcgi_pass
指令:
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$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm-www1.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
location /api/ {
root /var/www/html;
index index.php index.html index.htm;
try_files $uri $uri/ =404;
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_pass unix:/run/php/php7.4-fpm-www2.sock;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
}
重启Nginx:
sudo systemctl restart nginx
通过以上方法,你可以在Ubuntu系统中使用PHP-FPM实现负载均衡。选择哪种方法取决于你的具体需求和环境。