linux

Linux服务器上ThinkPHP如何进行负载均衡

小樊
40
2025-11-24 17:01:42
栏目: 云计算

Linux服务器上 ThinkPHP 负载均衡实战

一 架构与前置准备

二 方案一 Nginx 反向代理 + PHP-FPM 多实例

upstream php_backend {
    # 可按需调整权重、最大失败次数与失败超时
    server 192.168.1.11:9000 weight=1 max_fails=3 fail_timeout=30s;
    server 192.168.1.12:9000 weight=1 max_fails=3 fail_timeout=30s;
    # 如需会话保持(不建议长期依赖,优先用Redis共享Session)
    # ip_hash;
}

server {
    listen 80;
    server_name example.com;
    root  /var/wwwphp/public;   # 各实例的 public 目录
    index index.php index.html;

    # URL重写,适配 ThinkPHP 路由
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # PHP 处理
    location ~ \.php$ {
        include        fastcgi_params;
        fastcgi_param  SCRIPT_FILENAME  $document_root$fastcgi_script_name;
        fastcgi_param  HTTP_HOST        $host;
        fastcgi_pass   php_backend;     # 反向代理到 upstream
    }

    # 静态资源缓存(示例)
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    # 隐藏敏感文件
    location ~ /\.ht {
        deny all;
    }
}

三 方案二 Swoole 常驻进程 + Nginx 负载均衡

upstream swoole_backend {
    server 192.168.1.21:9501 weight=1 max_fails=3 fail_timeout=30s;
    server 192.168.1.22:9501 weight=1 max_fails=3 fail_timeout=30s;
    # 如需会话粘滞(不建议长期依赖)
    # ip_hash;
}

server {
    listen 80;
    server_name api.example.com;

    location / {
        proxy_pass http://swoole_backend;
        proxy_http_version 1.1;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 120s;   # Swoole 长连接可适当增大
    }
}

四 分布式一致性关键配置

五 健康检查与运维建议

0
看了该问题的人还看了