You need to enable JavaScript to run this app. Ubuntu系统下配置Rails自定义任务为systemd开机自启报错求解
优惠活动
大模型
产品
解决方案
定价
更多

Ubuntu系统下配置Rails自定义任务为systemd开机自启报错求解

修复方案

核心问题原因

两个报错的根源是systemd默认以root用户执行任务,和你手动执行时的普通用户(vidur)环境不一致:

  1. couldn't find login name -- expanding ~ 报错是因为仅配置了HOME环境变量但未指定执行用户,系统解析~路径时无法匹配到对应登录用户
  2. 数据库Access denied for user 'root'@'localhost'报错是因为root用户执行Rails任务时,会使用数据库默认的root账号尝试连接,和你普通用户下database.yml的配置不匹配

具体修改步骤

1. 修正systemd服务配置

替换你的socketing.service配置内容为以下内容:

[Unit]
Description=TCP Service at Port 51324
After=network.target

[Service]
# 指定和手动执行时一致的运行用户/用户组,解决权限和环境匹配问题
User=vidur
Group=vidur
# 配置Rails项目根目录(请确认路径为存在Rakefile、Gemfile的实际项目根目录)
WorkingDirectory=/home/vidur/rails_app/project_dir
# 配置必要环境变量
Environment="RAILS_ENV=production" # 如果你用开发环境请改为development
Environment="HOME=/home/vidur"
Environment="PATH=/home/vidur/.rbenv/shims:/home/vidur/.rbenv/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin"
# 启动命令
ExecStart=/home/vidur/.rbenv/shims/bundle exec rails socketing:start
# 标记为常驻前台进程,systemd会持续监控
Type=simple
# 异常自动重启配置
Restart=on-failure
RestartSec=5

[Install]
WantedBy=multi-user.target

如果你仍然要使用custom_script.sh启动,需要先给脚本添加执行权限:chmod +x /home/vidur/rails_app/tukaweb/custom_script.sh,同时确认脚本内cd的路径和实际项目根目录一致。

2. 执行配置生效命令

依次执行以下命令完成部署:

  • 停止旧服务:sudo systemctl stop socketing.service
  • 重载systemd配置:sudo systemctl daemon-reload
  • 启动新服务:sudo systemctl start socketing.service
  • 查看服务运行状态:sudo systemctl status socketing.service
  • 确认端口监听正常:ss -tulpn | grep 51324
  • 配置开机自启:sudo systemctl enable socketing.service

额外注意项

确认你的Rake任务中端口配置和实际需求一致,你当前代码中TCPServer绑定的是51324,和注释、服务描述中的51234不一致,避免后续端口访问错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.17 15:45:05