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

Docker运行Rails控制台提示找不到所有gem的问题排查

Rails容器控制台全Gem缺失异常排查

问题现象

  • 执行docker-compose run web rails console时,触发「Could not find ..... in locally installed gems」错误,涉及所有项目依赖Gem
  • rails s、rails routes可正常运行,镜像构建过程无报错
  • 容器内直接执行bundle install无任何效果
  • 临时修复方式:执行docker-compose run web bundle install --binstubs可恢复控制台正常使用

问题根源

docker-compose.yml中web服务配置了volumes: - .:/app,将本地项目目录直接挂载覆盖容器内的/app目录。构建阶段通过bundle install安装的Gem存储在容器内的/app相关路径(如vendor/bundle),被本地目录覆盖后,bundler无法找到已安装的Gem文件。

而rails s能正常运行,是因为docker-compose up启动时,容器进程直接使用构建阶段的bundle环境;但docker-compose run启动控制台时,挂载后的目录环境干扰了bundler的Gem查找路径。

修复方案

方案1:精细化挂载目录(推荐)

修改docker-compose.yml的web服务volumes配置,仅挂载项目中需要实时修改的目录,避免覆盖容器内的Gem安装文件:

web:
  build: .
  command: bundle exec rails s -p 3000 -b '0.0.0.0'
  volumes:
    - ./app:/app/app
    - ./config:/app/config
    - ./lib:/app/lib
    - ./log:/app/log
    - ./tmp:/app/tmp
  ports:
    - "3000:3000"
  depends_on:
    - db
    - redis
  environment:
    DATABASE_HOST: db
    DATABASE_USERNAME: app_api
    DATABASE_PASSWORD: app_api
    DATABASE_NAME: app_api_dev

方案2:指定Gem安装到非挂载目录

修改Dockerfile,配置bundler将Gem安装到容器内不被挂载的系统目录,避免被本地目录覆盖:

# Use the official Ruby 2.5.0 image as the parent image
FROM ruby:2.5.0-slim

# Install dependencies
RUN apt-get update -qq \
    && apt-get install -y \
    build-essential \
    shared-mime-info \
    libpq-dev \
    default-libmysqlclient-dev \
    libssl-dev \
    libcurl4-openssl-dev \
    procps

# Set the working directory to /app
WORKDIR /app

# Copy the Gemfile and Gemfile.lock into the image and install gems
ENV BUNDLER_VERSION=2.3.26
# 指定Gem安装路径到系统目录,避免被挂载覆盖
ENV BUNDLE_PATH=/usr/local/bundle
COPY Gemfile Gemfile.lock ./
RUN gem install bundler -v $BUNDLER_VERSION && bundle install --jobs 20 --retry 5

# Copy the rest of the application code into the image
COPY . .

EXPOSE 3000

CMD ["bundle", "exec", "puma", "-C", "config/puma.rb"]

方案3:临时修复(不推荐长期使用)

若需快速恢复控制台使用,可执行以下命令,在本地目录生成binstubs供bundler定位Gem:

docker-compose run web bundle install --binstubs

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 13:37:45