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

Rails 5.2.8.1重装后执行init.sh报rake aborted错误求助

Rails 5.2.8.1 执行init.sh时rake任务报错排查方案

报错信息

执行初始化脚本init.sh时出现rake任务找不到的错误,具体报错:

rake aborted!
' (See the list of available tasks with rake --tasks)
Did you mean? db:create
/usr/local/bundle/gems/rake-13.0.6/exe/rake:27:in <top (required)>
/usr/local/bin/bundle:23:in load'
/usr/local/bin/bundle:23:in '
(See full trace by running task with --trace)
rake aborted!
' (See the list of available tasks with rake --tasks)

环境与配置

  • Rails版本:5.2.8.1
  • 部署方式:Docker Compose
  • 涉及文件:init.sh、docker-compose.yml

init.sh 原内容

rm -f tmp/pids/server.pid
rake db:create && rake db:migrate
rake db:seed
rake db:migrate RAILS_ENV=test
rake es:create_index

docker-compose.yml 核心配置

version: '3.8'
services:  
  db:  
    image: mysql:5.7
    environment:  
      MYSQL_ROOT_PASSWORD: password
      MYSQL_DATABASE: app
      MYSQL_USER: user
      MYSQL_PASSWORD: password
  app:
    build: .
    command: sh -c 'sh ./init.sh && rails s -p 3000 -b '0.0.0.0''
    environment :
      DB_USER: root
      DB_NAME: noteapp
      DB_PASSWORD: password
      DB_HOST: db

排查与解决步骤

1. 统一数据库环境变量

docker-compose.yml中db服务的MYSQL_DATABASE为app,但app服务的DB_NAME为noteapp,两者不一致会导致db:create任务无法找到目标数据库。

  • 修改db服务的MYSQL_DATABASE为noteapp,或修改app服务的DB_NAME为app,保持名称统一。

2. 给rake命令添加bundle exec前缀

Docker环境中直接使用rake可能调用系统全局版本,而非Gemfile指定的版本,导致任务识别失败。修改init.sh:

rm -f tmp/pids/server.pid
bundle exec rake db:create && bundle exec rake db:migrate
bundle exec rake db:seed
bundle exec rake db:migrate RAILS_ENV=test
bundle exec rake es:create_index

3. 修复Docker Compose命令的引号冲突

app服务的command参数中,内部单引号与外层单引号冲突,导致shell解析错误:

# 原错误写法
command: sh -c 'sh ./init.sh && rails s -p 3000 -b '0.0.0.0''
# 修改为
command: sh -c "sh ./init.sh && rails s -p 3000 -b '0.0.0.0'"

4. 添加数据库就绪等待逻辑

Docker Compose的depends_on仅保证容器启动顺序,不确保数据库服务完全可用。在init.sh开头添加等待逻辑:

# 等待MySQL服务就绪
until nc -z $DB_HOST 3306; do
  echo "等待数据库启动..."
  sleep 2
done

rm -f tmp/pids/server.pid
# 后续rake命令...

注:需确保容器内安装了netcat,可在Dockerfile中添加apt-get install -y netcat(Debian/Ubuntu基础镜像)。

5. 验证自定义rake任务

如果es:create_index是自定义任务,需确认:

  • 任务文件存放在lib/tasks目录下,后缀为.rake
  • 任务名称定义正确,可进入容器执行bundle exec rake --tasks查看是否存在该任务

6. 清理缓存并重新构建容器

卸载重装后可能存在缓存问题,执行以下命令重置环境:

docker-compose down -v
docker-compose build --no-cache
docker-compose up

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 23:50:37