如何让php -S localhost:8000 -t public/在后台运行?类似Docker的-d参数
让PHP内置服务器后台运行的方法
要实现类似Docker -d 参数的后台运行效果,你可以用以下几种实用方案:
使用nohup命令(临时后台运行首选)
在命令前加nohup、末尾加&,让进程脱离终端后台执行:nohup php -S localhost:8000 -t public/ &默认输出会写入当前目录的
nohup.out文件,若不想生成该文件,可将输出重定向到空设备:nohup php -S localhost:8000 -t public/ > /dev/null 2>&1 &停止进程时,先用
ps aux | grep php找到进程ID,再执行kill <PID>即可。使用screen/tmux(需后续交互的场景)
如果你之后可能需要重新连接查看进程输出或操作,终端复用工具更合适:- screen操作步骤:
- 输入
screen新建会话 - 在会话内运行
php -S localhost:8000 -t public/ - 按
Ctrl+A+D分离会话,进程将在后台持续运行 - 重新连接输入
screen -r
- 输入
- tmux操作步骤:
- 输入
tmux new -s php_server新建名为php_server的会话 - 运行目标PHP命令
- 按
Ctrl+B+D分离会话 - 重新连接输入
tmux attach -t php_server
- 输入
- screen操作步骤:
使用systemd服务(长期稳定运行/开机自启)
若需要服务器长期稳定运行甚至开机自动启动,可创建systemd服务:- 创建服务文件
/etc/systemd/system/php-server.service(替换your_user和/path/to/your/project为实际值):
[Unit] Description=PHP Built-in Server After=network.target [Service] Type=simple User=your_user WorkingDirectory=/path/to/your/project ExecStart=/usr/bin/php -S localhost:8000 -t public/ Restart=always [Install] WantedBy=multi-user.target- 重新加载systemd配置:
sudo systemctl daemon-reload - 启动服务:
sudo systemctl start php-server - 设置开机自启:
sudo systemctl enable php-server
查看状态用sudo systemctl status php-server,停止服务用sudo systemctl stop php-server
- 创建服务文件
内容的提问来源于stack exchange,提问作者Luis Alfredo Serrano Díaz
相关产品推荐
相关产品推荐

