在 Debian 上用 PHP 做“负载均衡”,通常不是 PHP 本身做负载均衡,而是:
下面按常见生产方案给你讲。
用户
|
负载均衡 (Nginx / HAProxy)
|---------> Web1 (Nginx + PHP-FPM)
|---------> Web2 (Nginx + PHP-FPM)
|---------> Web3 (Nginx + PHP-FPM)
|
共享存储 / Redis / 数据库
PHP 只负责业务逻辑,负载均衡由专门组件完成。
sudo apt update
sudo apt install nginx
编辑:
/etc/nginx/conf.d/loadbalance.conf
示例:
upstream php_backend {
least_conn;
server 192.168.1.11:9000;
server 192.168.1.12:9000;
server 192.168.1.13:9000;
}
server {
listen 80;
server_name example.com;
location ~ \.php$ {
fastcgi_pass php_backend;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
}
✅ 支持算法:
round_robin(默认)least_conn(推荐)ip_hash(有 session 时)sudo apt install haproxy
frontend http_front
bind *:80
default_backend php_back
backend php_back
balance roundrobin
server php1 192.168.1.11:9000
server php2 192.168.1.12:9000
HAProxy 更适合:
sudo apt install php-fpm
每个节点都运行 PHP-FPM。
❌ 不要依赖:
✅ 正确做法:
; php.ini
session.save_handler = redis
session.save_path = "tcp://127.0.0.1:6379"
⚠️ 不推荐,但存在:
// 简单转发
$hosts = ['192.168.1.11','192.168.1.12'];
$host = $hosts[array_rand($hosts)];
$ctx = stream_context_create([
'http' => ['method' => $_SERVER['REQUEST_METHOD']]
]);
echo file_get_contents("http://$host".$_SERVER['REQUEST_URI'], false, $ctx);
❌ 性能差
❌ 不稳定
❌ 不适合生产
✅ 正确做法
❌ 错误认知
如果你愿意,我可以:
你现在是 学习 / 生产 / 面试?