如何在GCP Compute Engine上实现Discord Bot 24/7不间断运行
解决方案
你直接在SSH会话中运行python3 bot.py时,进程属于当前SSH会话的子进程,SSH断开时系统会向该会话下所有进程发送SIGHUP信号终止进程,因此需要让Bot进程脱离SSH会话管理,长期稳定后台运行,可选方案如下:
方案1:临时后台运行(适合调试阶段)
- 方法1:nohup命令
执行nohup python3 bot.py &即可,nohup会忽略SIGHUP信号,&将进程放到后台运行,程序默认输出会写入当前目录下的nohup.out文件。
需要停止进程时,先执行ps aux | grep bot.py查询进程PID,再执行kill <PID>结束进程即可。 - 方法2:tmux会话管理
先安装tmux:sudo apt update && sudo apt install tmux -y
- 执行
tmux new -s discord-bot创建专属会话 - 在会话内正常执行
python3 bot.py启动Bot - 按下
Ctrl + B后再按D,即可将会话放到后台运行,此时断开SSH也不会影响Bot运行 - 需要回到会话查看日志/操作时,执行
tmux attach -t discord-bot即可恢复会话
方案2:生产级稳定运行(推荐长期使用)
使用systemd配置系统服务,可实现Bot崩溃自动重启、实例开机自动启动,稳定性最高。
操作步骤如下:
- 创建服务配置文件:执行
sudo nano /etc/systemd/system/discord-bot.service - 写入以下配置,注意替换占位符为你自己的实际信息:
[Unit]
Description=Discord Bot 服务
After=network.target[Service]
User=你的Ubuntu实例用户名(GCP Ubuntu实例默认用户为ubuntu)
WorkingDirectory=你的Bot代码所在的绝对路径(例如/home/ubuntu/my-discord-bot)
ExecStart=Python3的绝对路径 bot.py(如果未用虚拟环境则填/usr/bin/python3,用虚拟环境则填虚拟环境内python路径,例如/home/ubuntu/bot-venv/bin/python3)
Restart=always
RestartSec=5
Environment=PYTHONUNBUFFERED=1[Install]
WantedBy=multi-user.target
- 重载systemd配置:
sudo systemctl daemon-reload - 启动Bot服务:
sudo systemctl start discord-bot.service - 设置实例开机自动启动Bot:
sudo systemctl enable discord-bot.service
常用管理命令
- 查看实时运行日志:
sudo journalctl -u discord-bot.service -f - 重启Bot:
sudo systemctl restart discord-bot.service - 停止Bot:
sudo systemctl stop discord-bot.service
额外注意事项
- 确保GCP Compute Engine实例没有配置自动休眠/关机策略
- 确保实例安全组的出站规则允许访问Discord的相关接口
- 如果Bot依赖环境变量,可直接在systemd配置的Service块中添加
Environment="变量名=变量值"配置
内容的提问来源于stack exchange,提问作者buttermilk
相关产品推荐
相关产品推荐

