2017-03-10 25 views
1

我有一个docker镜像,它安装了ubuntu和RUN的一些附加命令,比如安装NodeJS。在docker-compose中运行npm install时出现的问题版本号

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的容器,然后做一个ls -a的安装src/文件夹中容器,然后我看到我在主机上看到的所有文件。到现在为止还挺好。

(命令我跑得太往里容器:docker exec -it <container hash> ls -a

由于所有的文件似乎在那里,包括package.jsonDockerfile我添加了一个新的RUN命令是:npm install。所以我有这样的:

VOLUME ["/src"] 
WORKDIR /src 
RUN npm install 

除了给我一个错误,它无法找到在src/文件夹package.json

当我添加一个RUN ls -a(记住,我切换到src/文件夹WORKDIR),那么就说明它是一个空目录...

所以在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)?

解决此问题的方法是什么?

回答

3

你误会VOLUME命令之间的Dockerfile和-v标志的docker守护之差(什么docker-compose用于其卷)。

docker-compose文件volumes项中的值告诉docker哪些目录中映射后你的形象已经完成建设。在构建过程中不会使用它们。

幸运的是,由于撰写文件中的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添加到您的构建根目录中的.dockerignore文件(../..)。

+0

我再次玩过它。 'COPY'命令可以把我的'package.json'复制到'/ src'文件夹中。然后我可以做一个'RUN npm install',这也可以。它显示它创建了一个'node_modules'文件夹。但是,当我运行'docker-compose up'时,它将覆盖'/ src'目录中的'Dockerfile'的所有内容。我猜这是因为'docker-compose.yml'在同一个'/ src'文件夹中做了'-v',因此覆盖了它以前的所有内容? – Vivendi

+0

对。安装本地目录将使用本地驱动器中的内容替换映像中的任何匹配内容。你通常只想在开发过程中这样做。 – jkinkead