Rails 5.2.8.1重装后执行init.sh报rake aborted错误求助
报错信息
执行初始化脚本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

