You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Laravel服务器配置为持续运行的服务

生产环境下配置PHP WebSocket服务持续运行的方案

在生产环境中,php artisan serve仅适合本地调试,无法保证服务稳定持续运行。常用的方案是借助进程管理工具来守护WebSocket进程,以下是两种最常用的实现方式:

一、使用 Supervisor(推荐,配置简单)

Supervisor是Linux下的进程管理工具,能自动重启意外退出的进程。

1. 安装 Supervisor

根据服务器系统执行安装命令:

  • Debian/Ubuntu 系列:
apt-get update && apt-get install supervisor
  • CentOS/RHEL 系列:
yum install supervisor

2. 创建 Supervisor 配置文件

在 /etc/supervisor/conf.d/ 目录下新建配置文件,比如 websocket.conf:

[program:laravel-websocket]
command=php /path/to/your/project/artisan websocket:serve
directory=/path/to/your/project
user=www-data ; 替换为运行项目的系统用户,比如www-data、nginx或你的用户名
autostart=true
autorestart=true
stdout_logfile=/var/log/websocket.log
stderr_logfile=/var/log/websocket-error.log

注意替换 /path/to/your/project 为你的Laravel项目实际路径,user 要匹配项目文件的所属用户。

3. 启动并启用 Supervisor 服务

# 重新加载配置
supervisorctl reread
supervisorctl update
# 启动WebSocket进程
supervisorctl start laravel-websocket
# 查看状态
supervisorctl status laravel-websocket

二、使用 Systemd(系统原生服务管理)

如果服务器使用Systemd(大多数现代Linux发行版默认使用),可以直接创建系统服务文件。

1. 创建 Systemd 服务文件

在 /etc/systemd/system/ 目录下新建 laravel-websocket.service 文件:

[Unit]
Description=Laravel WebSocket Service
After=network.target

[Service]
User=www-data
Group=www-data
WorkingDirectory=/path/to/your/project
ExecStart=php /path/to/your/project/artisan websocket:serve
Restart=always
RestartSec=5
StandardOutput=append:/var/log/websocket.log
StandardError=append:/var/log/websocket-error.log

[Install]
WantedBy=multi-user.target

同样替换项目路径和用户组信息。

2. 启动并启用服务

# 重新加载系统服务配置
systemctl daemon-reload
# 启动WebSocket服务
systemctl start laravel-websocket
# 设置开机自启
systemctl enable laravel-websocket
# 查看服务状态
systemctl status laravel-websocket

注意事项

  • 确保服务器开放了WebSocket使用的端口(默认一般是6001,可在Laravel配置中修改),在防火墙中添加规则放行。
  • 定期清理日志文件,避免占用过多磁盘空间。
  • 如果WebSocket依赖Redis等服务,确保这些服务也配置了开机自启,避免依赖服务中断导致WebSocket异常。

内容的提问来源于stack exchange,提问作者devkashee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 23:26:58