在CentOS上实现PHP-FPM的负载均衡可以通过多种方式来完成,以下是两种常见的方法:
安装Nginx:
sudo yum install epel-release
sudo yum install nginx
配置Nginx:
编辑Nginx配置文件(通常位于/etc/nginx/nginx.conf或/etc/nginx/conf.d/default.conf),添加或修改以下内容:
http {
upstream php_fpm {
server unix:/tmp/php-fpm.sock;
server unix:/tmp/php-fpm2.sock;
# 可以添加更多PHP-FPM实例
}
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;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
include fastcgi_params;
}
}
}
在这个配置中,upstream块定义了PHP-FPM的负载均衡池,fastcgi_pass指令将PHP请求转发到这个池。
启动Nginx:
sudo systemctl start nginx
sudo systemctl enable nginx
配置PHP-FPM:
确保你的PHP-FPM配置文件(通常位于/etc/php-fpm.d/www.conf)中的listen指令设置为Unix socket或TCP端口。例如:
listen = /tmp/php-fpm.sock
或者
listen = 127.0.0.1:9000
如果你使用TCP端口,确保Nginx配置中的fastcgi_pass也相应修改。
启动PHP-FPM:
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
安装HAProxy:
sudo yum 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:/tmp/php-fpm.sock check
server php_fpm2 unix:/tmp/php-fpm2.sock check
# 可以添加更多PHP-FPM实例
在这个配置中,backend块定义了PHP-FPM的负载均衡池,balance roundrobin指令实现了轮询负载均衡。
启动HAProxy:
sudo systemctl start haproxy
sudo systemctl enable haproxy
配置PHP-FPM:
确保你的PHP-FPM配置文件(通常位于/etc/php-fpm.d/www.conf)中的listen指令设置为Unix socket或TCP端口。例如:
listen = /tmp/php-fpm.sock
或者
listen = 127.0.0.1:9000
如果你使用TCP端口,确保HAProxy配置中的server指令也相应修改。
启动PHP-FPM:
sudo systemctl start php-fpm
sudo systemctl enable php-fpm
通过以上两种方法,你可以在CentOS上实现PHP-FPM的负载均衡。选择哪种方法取决于你的具体需求和环境。