ThinkPHP Linux版高可用部署指南
高可用部署的核心是通过负载均衡分散流量、冗余设计避免单点故障、共享存储保证数据一致性,以及监控运维及时发现问题。以下是针对ThinkPHP框架的具体实施步骤:
在所有服务器(应用服务器、数据库服务器、负载均衡服务器)上安装必要的软件,确保环境一致:
sudo apt update && sudo apt install php php-cli php-fpm php-mysql php-zip php-gd php-mbstring php-curl php-xml php-bcmath -y
sudo apt install nginx -y
sudo apt install mysql-server -y
sudo systemctl start mysql
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer
以上步骤在所有服务器上重复执行,确保环境统一。
通过负载均衡器(如Nginx、HAProxy)将流量分发到多个ThinkPHP应用服务器,避免单点故障。以下以Nginx为例:
/etc/nginx/nginx.conf或/etc/nginx/sites-available/default),添加upstream块定义应用服务器组:http {
upstream thinkphp_servers {
server 192.168.1.101:80; # 应用服务器1
server 192.168.1.102:80; # 应用服务器2
server 192.168.1.103:80; # 应用服务器3
# 可添加更多服务器
}
}
server块中添加location,将请求转发到upstream组:server {
listen 80;
server_name yourdomain.com;
location / {
proxy_pass http://thinkphp_servers; # 转发到upstream组
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;
}
}
sudo nginx -t # 测试配置语法
sudo systemctl restart nginx
可选负载均衡器:
frontend http_front
bind *:80
default_backend http_back
backend http_back
balance roundrobin
server thinkphp1 192.168.1.101:80 check
server thinkphp2 192.168.1.102:80 check
server thinkphp3 192.168.1.103:80 check
负载均衡器本身需配置高可用(如Keepalived实现主备),避免成为单点故障。
确保多个ThinkPHP应用服务器的一致性和稳定性:
git pull同步代码,保证版本一致。.env文件:SESSION_DRIVER=redis
SESSION_REDIS_HOST=192.168.1.200 # Redis服务器IP
SESSION_REDIS_PORT=6379
SESSION_REDIS_PASSWORD=yourpassword
并安装Redis扩展:sudo apt install php-redis -y。.env文件:CACHE_DRIVER=redis
CACHE_REDIS_HOST=192.168.1.200
CACHE_REDIS_PORT=6379
CREATE USER 'replicator'@'%' IDENTIFIED BY 'password';
GRANT REPLICATION SLAVE ON *.* TO 'replicator'@'%';
FLUSH PRIVILEGES;
SHOW MASTER STATUS; # 记录File和Position
从服务器执行:CHANGE MASTER TO MASTER_HOST='master_ip', MASTER_USER='replicator', MASTER_PASSWORD='password', MASTER_LOG_FILE='mysql-bin.000001', MASTER_LOG_POS=107;
START SLAVE;
通过SHOW SLAVE STATUS\G检查复制状态。数据库是应用的核心,需确保数据冗余和故障恢复能力:
/etc/mysql/mysql.conf.d/mysqld.cnf):[mysqld]
gtid_mode=ON
enforce_gtid_consistency=ON
master_info_repository=TABLE
relay_log_info_repository=TABLE
transaction_write_set_extraction=XXHASH64
group_replication_group_name="aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
group_replication_start_on_boot=OFF
group_replication_local_address= "192.168.1.101:33061"
group_replication_group_seeds= "192.168.1.101:33061,192.168.1.102:33061,192.168.1.103:33061"
group_replication_bootstrap_group=OFF
重启MySQL后,在主服务器执行:SET GLOBAL group_replication_bootstrap_group=ON;
START GROUP_REPLICATION;
SET GLOBAL group_replication_bootstrap_group=OFF;
从服务器执行:START GROUP_REPLICATION;。高可用需持续监控系统状态,及时处理故障:
upstream模块fail_timeout参数),自动剔除故障服务器。通过以上步骤,可实现ThinkPHP在Linux环境下的高可用部署,确保应用稳定运行。