PHP项目系统服务与systemd

wen PHP项目 1

本文目录导读:

PHP项目系统服务与systemd

  1. 创建systemd服务单元文件
  2. 常用PHP服务场景
  3. 管理服务命令
  4. 高级配置技巧
  5. 安全性优化
  6. 调试和故障排除
  7. 性能监控模板
  8. 部署脚本示例

我来详细讲解PHP项目如何创建和管理systemd服务。

创建systemd服务单元文件

基本服务配置

创建 /etc/systemd/system/php-service.service:

[Unit]
Description=PHP Application Service
After=network.target
After=mysql.service
Wants=mysql.service
[Service]
Type=simple
User=www-data
Group=www-data
WorkingDirectory=/var/www/project
# PHP脚本执行
ExecStart=/usr/bin/php /var/www/project/worker.php
# 环境变量
Environment="APP_ENV=production"
Environment="DB_HOST=localhost"
# 安全配置
PrivateTmp=true
ProtectSystem=full
NoNewPrivileges=true
RestrictRealtime=true
RestrictAddressFamilies=AF_INET AF_INET6 AF_UNIX
# 重启策略
Restart=always
RestartSec=5s
StartLimitInterval=400
StartLimitBurst=3
# 资源限制
LimitNOFILE=65535
LimitNPROC=4096
MemoryMax=512M
CPUQuota=80%
[Install]
WantedBy=multi-user.target

常用PHP服务场景

队列处理服务

[Unit]
Description=PHP Queue Worker Service
After=redis.service
[Service]
User=www-data
ExecStart=/usr/bin/php artisan queue:work --sleep=3 --tries=3
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target

WebSocket服务

[Unit]
Description=PHP WebSocket Server
After=network.target
[Service]
ExecStart=/usr/bin/php /var/www/socket/server.php start
ExecStop=/usr/bin/php /var/www/socket/server.php stop
ExecReload=/usr/bin/php /var/www/socket/server.php restart
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target

PHP-FPM服务

[Unit]
Description=PHP FastCGI Process Manager
After=network.target
[Service]
Type=forking
PIDFile=/run/php/php-fpm.pid
ExecStart=/usr/sbin/php-fpm --nodaemonize --fpm-config /etc/php/fpm/php-fpm.conf
ExecReload=/bin/kill -USR2 $MAINPID
ExecStop=/bin/kill -SIGINT $MAINPID
PrivateTmp=true
[Install]
WantedBy=multi-user.target

管理服务命令

# 重新加载配置
sudo systemctl daemon-reload
# 启动服务
sudo systemctl start php-service
# 停止服务
sudo systemctl stop php-service
# 重启服务
sudo systemctl restart php-service
# 启用开机自启
sudo systemctl enable php-service
# 禁用开机自启
sudo systemctl disable php-service
# 查看状态
sudo systemctl status php-service
# 查看日志
sudo journalctl -u php-service -f
# 查看最近100行日志
sudo journalctl -u php-service -n 100
# 实时查看日志
sudo journalctl -u php-service -f --since "1 hour ago"

高级配置技巧

环境变量管理

创建环境变量文件 /etc/php-service.env:

APP_ENV=production
DB_HOST=localhost
DB_PORT=3306
REDIS_HOST=127.0.0.1
LOG_LEVEL=error

在服务文件中引用:

[Service]
EnvironmentFile=/etc/php-service.env

多实例服务模板

创建 php-worker@.service:

[Unit]
Description=PHP Worker Service %i
After=redis.service
[Service]
User=www-data
WorkingDirectory=/var/www/project
ExecStart=/usr/bin/php artisan queue:work --queue=%i
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target

启动多个实例:

sudo systemctl start php-worker@high@php-worker@medium@php-worker@low

监控和通知

创建监控服务 /usr/local/bin/php-health-check.sh:

#!/bin/bash
SERVICE="php-service"
STATUS=$(systemctl is-active $SERVICE)
if [ "$STATUS" != "active" ]; then
    # 发送告警
    echo "Service $SERVICE is down!" | mail -s "Service Alert" admin@example.com
    # 尝试重启
    systemctl restart $SERVICE
fi

配合systemd定时器使用:

# /etc/systemd/system/php-health-check.timer
[Unit]
Description=PHP Service Health Check
[Timer]
OnCalendar=*:0/5
Persistent=true
[Install]
WantedBy=timers.target

安全性优化

[Service]
# 用户权限
User=www-data
Group=www-data
# 文件系统保护
ProtectSystem=strict
ReadWritePaths=/var/www/project/storage
ReadWritePaths=/var/log/php-service
# 关闭不需要的系统调用
SystemCallFilter=@system-service
# 内存保护
MemoryDenyWriteExecute=true
# 网络访问控制 #如果不需要网络
PrivateNetwork=true
# 限制访问其他进程
ProtectKernelTunables=true
ProtectControlGroups=true
# 隐藏进程信息
HidePID=true

调试和故障排除

日志查询命令

# 实时日志
journalctl -u php-service -f -o json
# 错误日志
journalctl -u php-service -p err -b
# 特定时间范围
journalctl -u php-service --since "2024-01-01" --until "2024-01-02"
# 查看PID
systemctl show php-service | grep MainPID

使用strace调试

# 跟踪服务进程
sudo strace -p $(systemctl show php-service -p MainPID | cut -d= -f2) -e trace=network,file

性能监控模板

创建监控配置 /etc/systemd/system/php-service.service.d/monitor.conf:

[Service]
# CPU Profile
CPUAccounting=true
CPUWeight=100
# Memory Profile
MemoryAccounting=true
MemoryMax=512M
MemoryHigh=384M
# IO Profile
IOAccounting=true
IOWeight=100
# Task Profile
TasksAccounting=true
TasksMax=50

查看监控数据:

systemd-cgtop
systemctl show php-service | grep -E "(CPU|Memory|IO)"

部署脚本示例

#!/bin/bash
# deploy-php-service.sh
SERVICE_NAME="php-service"
PROJECT_DIR="/var/www/project"
PHP_BIN="/usr/bin/php"
# 部署前停止服务
sudo systemctl stop $SERVICE_NAME
# 更新代码
cd $PROJECT_DIR
git pull origin main
# 安装依赖
$PHP_BIN composer install --no-dev --optimize-autoloader
# 运行迁移
$PHP_BIN artisan migrate --force
# 清除缓存
$PHP_BIN artisan optimize:clear
# 启动服务
sudo systemctl start $SERVICE_NAME
# 检查状态
sudo systemctl status $SERVICE_NAME --no-pager
echo "Deployment completed!"

通过以上配置,你可以为PHP项目创建稳定、可管理的systemd服务,实现自动化管理和监控。

抱歉,评论功能暂时关闭!