在CentOS上实现PHP负载均衡,通常需要使用Nginx或Apache作为反向代理服务器。这里以Nginx为例,介绍如何实现PHP负载均衡。
- 安装Nginx
首先,确保已经安装了EPEL和Remi仓库。然后,运行以下命令安装Nginx:
sudo yum install epel-release sudo yum install http://rpms.remirepo.net/enterprise/remi-release-7.rpm sudo yum install nginx
- 启动Nginx
安装完成后,启动Nginx服务并设置开机启动:
sudo systemctl start nginx sudo systemctl enable nginx
- 配置负载均衡
编辑Nginx配置文件(通常位于/etc/nginx/nginx.conf
或/etc/nginx/conf.d/default.conf
),在http
部分添加以下内容:
upstream php_backend { server 192.168.1.1:9000; # PHP-FPM服务器1的IP地址和端口 server 192.168.1.2:9000; # PHP-FPM服务器2的IP地址和端口 # 可以根据需要添加更多服务器 } server { listen 80; server_name example.com; # 替换为你的域名或公网IP地址 root /path/to/your/web/root; # 替换为你的网站根目录 index index.php index.html index.htm; location / { try_files $uri $uri/ =404; } location ~ \.php$ { fastcgi_pass php_backend; fastcgi_index index.php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; include fastcgi_params; } }
在这个配置中,我们定义了一个名为php_backend
的上游服务器组,其中包含了两个PHP-FPM服务器。Nginx会使用轮询(round-robin)算法在这两个服务器之间分配请求。
- 重启Nginx
保存配置文件后,重启Nginx服务以使更改生效:
sudo systemctl restart nginx
现在,Nginx已经配置好了PHP负载均衡。访问你的域名或公网IP地址,你应该能看到请求在两个PHP-FPM服务器之间进行负载均衡。如果需要添加更多服务器,只需在php_backend
上游服务器组中添加更多服务器即可。