为什么在 docker-compose.yml 中设置卷时需要将 Dockerfile 中的 Gemfile 复制到 docker?

Why need COPY Gemfile in Dockerfile to docker while set volumes in docker-compose.yml?

我按照 https://docs.docker.com/samples/rails/ 设置了 docker 环境。

我发现它在 Dockerfile 中设置 WORKDIR /myapp 并在 docker-compose.yml:

中设置卷挂载
services:
  web:
    build: .
    command: bundle exec rails server -b 0.0.0.0
    volumes:
      - .:/myapp

为什么还需要配置这两个 COPY 命令来调用 RUN bundle install ??

COPY Gemfile /myapp/Gemfile
COPY Gemfile.lock /myapp/Gemfile.lock

如果我从 Dockerfile 中删除它,当我 运行 docker compose build 时,出现以下错误:

 => ERROR [5/5] RUN bundle install                                                                                                                                                                     0.7s
------
 > [5/5] RUN bundle install:
#9 0.629 Could not locate Gemfile

docker /myapp 目录下没有Gemfile 文件吗?卷挂载不起作用?我想在 docker-compose.yml 中设置卷挂载后,Gemfile 和其他源代码文件应该存在于 /myapp 目录中。

卷仅安装在 run-timeRUN bundle install 命令在 build-time 处是 运行,其中安装的卷不可用。

我经常建议将构建和 运行 图像分开,因为它可能会混淆什么时候使用什么。