Linux环境下 ThinkPHP 自动化运维实践
一 自动化部署 CI/CD
#!/usr/bin/env bash
set -e
REPO_URL="git@your-gitlab.com:group/project.git"
COMPOSER_ARGS="--no-dev --optimize-autoloader"
if [ ! -d .git ]; then
git init
git remote add origin "$REPO_URL"
git fetch --all
git checkout -b main --track origin/main
fi
git fetch --all
git reset --hard origin/main
git clean -f -d
composer install $COMPOSER_ARGS
php think optimize:route
php think optimize:config
chmod -R 775 public runtime app/base/log
chown -R www:www .
if [ -f .env.production ]; then
cp .env.production .env
chmod 640 .env
fi
# 视运行形态选择其一
# systemctl restart php8.3-fpm
# 或重启队列/常驻进程:php think queue:restart
要点:优先使用 Git 钩子或 CI/CD(如 Jenkins) 实现拉取、安装、构建、权限设置与服务重启的自动化;生产环境务必关闭调试模式并优化路由/配置缓存。二 定时任务与常驻任务
# 每天 02:00 执行
0 2 * * * /usr/bin/php /var/www/tp6 checkexpired >> /var/log/tp6_cron.log 2>&1
#!/usr/bin/env bash
PHP="/usr/bin/php"
BASE="/var/www/tp6"
CMD="$PHP $BASE queue:listen --queue=default --tries=3"
if ! pgrep -f "$CMD" >/dev/null; then
nohup $CMD >> $BASE/runtime/log/queue.log 2>&1 &
fi
三 进程守护与自启动
[program:thinkphp-queue]
command=/usr/bin/php /var/www/tp6 queue:work --queue=default --tries=3 --sleep=3
directory=/var/www/tp6
autostart=true
autorestart=true
user=www
numprocs=1
redirect_stderr=true
stdout_logfile=/var/www/tp6/runtime/log/supervisor_queue.log
stopwaitsecs=3600
使配置生效:supervisorctl reread && supervisorctl update && supervisorctl start thinkphp-queue:*
要点:为不同队列或业务进程定义多个 program,分离日志与资源,便于排障与扩缩容。四 监控告警与日志
五 安全与运维规范