在docker-compose构build过程中运行npm install的问题
我有一个docker镜像安装ubuntu和RUN
一些额外的命令,如安装NodeJS。
Dockerfile(结合docker-compose.yml
)也将目录挂载到主机上的目录。 看起来像这样:
services: test: build: context: ../../ dockerfile: docker/Dev/Dockerfile ports: - 7000:7000 volumes: - ./../../src:/src
在Dockerfile
我对卷有以下几行:
VOLUME ["/src"] WORKDIR /src
当我用docker-compose up
运行容器,然后在容器的已安装的src/
文件夹中执行ls -a
,我看到了所有在主机上看到的文件。 到现在为止还挺好。
(命令我也看看里面容器: docker exec -it <container hash> ls -a
)
由于所有的文件似乎在那里,包括一个package.json
我添加了一个新的RUN
命令到我的Dockerfile
是: npm install
。 所以我有这个:
VOLUME ["/src"] WORKDIR /src RUN npm install
除了给我一个错误,它无法findsrc/
文件夹中的package.json
。
当我添加一个RUN ls -a
(记住,我用WORKDIR
切换到src/
文件夹),那么它显示它是一个空目录…
所以在Dockerfile
我有:
VOLUME ["/src"] WORKDIR /src # shows that /src is empty. If I do 'RUN pwd', then it shows I really am in /src RUN ls -a RUN npm install
但是,在我执行docker-compose up
,再在容器的/src
文件夹中执行ls -a
,它会再次显示我所有的源文件。
所以我的问题是,为什么他们没有在编译期间(我正在运行docker-compose build
)呢?
有什么办法解决这个问题?
您误解了Dockerfile中的VOLUME
命令和docker守护进程的-v
标志之间的区别(docker docker-compose
用于其卷)。
docker-compose
文件中的volumes
关键字下的值告诉docker
映像完成构build后要映射的目录。 在构build过程中不使用它们。
幸运的是,由于撰写文件中的context
行,您可以自动访问所有源文件 – 它们只是在本地src
目录中,而不是当前的工作目录!
尝试更新您的Dockerfile到以下内容:
# NOTE: You don't want a VOLUME directive if you only want to mount a local # directory. WORKDIR is optional, but doesn't matter for my example, # so I'm omitting it. # Copy the npm files into your Docker image. If you do this first, the docker # daemon can cache the built layers, making your images build faster and be # substantially smaller, since most of your dependencies will remain unchanged # between builds. COPY src/package.json package.json COPY src/npm-shrinkwrap.json npm-shrinkwrap.json # Actually install the dependencies. RUN npm install # Copy all of your source files from the `src` directory into the Docker image. COPY src .
现在,这里有一个问题:您可能已经在src/node_modules
下安装了npm
模块。 因此,除了最终的COPY
行之外,您可以将上面的所有内容都src/node_modules
,或者可以将src/node_modules
添加到构build根目录( .dockerignore
../..
)中的.dockerignore
文件中。