Linux下ThinkPHP自动化运维实践
一 进程守护与自动恢复
[program:thinkphp-worker]
command=php /var/www/your_project queue:work --queue=default --tries=3 --sleep=3
autostart=true
autorestart=true
user=www-data
numprocs=2
redirect_stderr=true
stdout_logfile=/var/www/your_project/runtime/log/worker.log
stopwaitsecs=3600
sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start thinkphp-worker:*
sudo supervisorctl status
二 定时任务自动化
php think make:command CheckExpired check:expired
return [
'commands' => [
'check:expired' => app\command\CheckExpired::class,
],
];
php think check:expired
0 2 * * * /usr/bin/php /var/www/your_project check:expired >> /var/logphp_cron.log 2>&1
三 日志与性能监控
'log' => [
'type' => 'file',
'var_log_path' => './runtime/log',
'level' => ['info','debug','warn','error'],
],
namespace app\middleware;
use think\facade\Log;
class PerformanceMiddleware {
public function handle($request, \Closure $next) {
$start = microtime(true);
$response = $next($request);
$cost = microtime(true) - $start;
Log::info("[{$request->method()}] {$request->url()} cost={$cost}s mem=".(memory_get_peak_usage()/1024/1024)."MB");
return $response;
}
}
四 部署发布与回滚自动化
server {
listen 80; server_name your.domain;
root /var/www/your_project/public; index index.php;
location / { try_files $uri $uri/ /index.php?$query_string; }
location ~ \.php$ {
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
fastcgi_pass unix:/run/php/php7.4-fpm.sock;
}
}
五 告警与一键巡检脚本
#!/usr/bin/env bash
LOG=/var/www/your_project/runtime/log/error.log
ALERT_EMAIL=ops@example.com
TMP_ERR=$(mktemp)
# 近5分钟新增错误
grep "$(date -d '5 minutes ago' '+%Y-%m-%d %H:%M')" -A2 "$LOG" | grep -E 'ERROR|Exception' > "$TMP_ERR"
if [ -s "$TMP_ERR" ]; then
SUBJ="[ThinkPHP] 近5分钟发现错误"
mail -s "$SUBJ" "$ALERT_EMAIL" < "$TMP_ERR"
fi
rm -f "$TMP_ERR"
#!/usr/bin/env bash
echo "=== ThinkPHP Health Check $(date) ==="
echo "1) PHP-FPM: $(systemctl is-active php7.4-fpm)"
echo "2) Nginx: $(systemctl is-active nginx)"
echo "3) Disk: $(df -h | awk '$NF=="/"{print $5}') used"
echo "4) Queue: $(php think queue:status 2>&1 | head -n 20)"
echo "5) Recent Errors:"
tail -n 50 /var/www/your_project/runtime/log/error.log | tail -n 20