在 Ubuntu 上为 ThinkPHP 项目实现负载均衡
一 架构与准备
二 方案一 Nginx 作为负载均衡器
安装与启用
配置示例(/etc/nginx/conf.d/load_balancer.conf)
upstream tp_backend {
server 10.0.0.11:9000 max_fails=2 fail_timeout=30s;
server 10.0.0.12:9000 max_fails=2 fail_timeout=30s;
# 可按需增加权重:server 10.0.0.13:9000 weight=2;
}
server {
listen 80;
server_name your.domain.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl http2;
server_name your.domain.com;
ssl_certificate /etc/letsencrypt/live/your.domain.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/your.domain.com/privkey.pem;
root /var/www/your-app/public;
index index.php;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
include snippets/fastcgi-php.conf;
fastcgi_param SCRIPT_FILENAME $document_root/index.php;
fastcgi_pass tp_backend;
fastcgi_param HTTP_X_REAL_IP $remote_addr;
fastcgi_param HTTP_X_FORWARDED_FOR $proxy_add_x_forwarded_for;
fastcgi_param HTTP_X_FORWARDED_PROTO $scheme;
fastcgi_param HTTP_HOST $host;
}
location ~ /\.ht {
deny all;
}
}
重载与验证
三 方案二 HAProxy 作为负载均衡器
安装与启用
配置示例(/etc/haproxy/haproxy.cfg)
global
log /dev/log local0
log /dev/log local1 notice
daemon
maxconn 4096
defaults
log global
mode http
option httplog
option dontlognull
timeout connect 5000ms
timeout client 50000ms
timeout server 50000ms
frontend http-in
bind *:80
bind *:443 ssl crt /etc/letsencrypt/live/your.domain.com/fullchain.pem
redirect scheme https if !{ ssl_fc }
default_backend tp_servers
backend tp_servers
balance roundrobin
option httpchk GET /health
server app1 10.0.0.11:9000 check
server app2 10.0.0.12:9000 check
# 可选:将请求改写为 /index.php(适配部分直接到 PHP 的 FastCGI 转发)
# reqirep ^([^\ ]*)\ /(.*) \1\ /index.php?$2
重载与验证
四 ThinkPHP 多实例关键配置
五 测试与运维建议