Why does docker create empty node_modules and how

2020-03-24 05:02发布

There are some similar questions but they haven't answered why docker creates the empty node_modules directory in the repo even though the dockerfile is setup to hold node_modules in the container?

I'm interested to know why directory is created on the host empty, give that yarn already installs packages inside the container within node_modules and how to avoid it.

## Dockerfile

FROM node:8.11.4-alpine
RUN apk update && apk add yarn
RUN yarn global add nodemon
WORKDIR /usr/app

COPY package.json yarn.lock /usr/app/
RUN yarn

EXPOSE 3000

## docker-compose.yml

version: "3.2"

services:
  app:
    build:
      context: .
      dockerfile: Dockerfile
    command: nodemon index.js
    volumes:
      - .:/usr/app
      - /usr/app/node_modules
    ports:
      - "3000:3000"

2条回答
地球回转人心会变
2楼-- · 2020-03-24 05:45

Not a docker expert but I think the problem happened because of volumes block in your

docker-compose.yml file. Remove the line

 - /usr/app/node_modules

and try again

查看更多
仙女界的扛把子
3楼-- · 2020-03-24 05:49

You are right, your image building process is installing the node packages into the node_modules directory in the image. So, after you build your image the image contains node_modules and you can use it to run your application.

You see node_modules on your host machine, because of your volumes setup in your Compose file. There is more to it than you see in the other answer though.

What's happening is that you are mapping .:/usr/app in your first volume definition, which means that you are mapping your current directory on the host to /usr/app in the container.

This will override the /usr/app directory in the image with the current directory on the host. And your host does not have the node_modules directory (unless you installed node_modules on the host, too) and therefore your container will not work with this mapping, beacuse you've overriden /usr/app and there is no node_modules dir in the override. Node will throw an error that it cannot find node modules.

The next volume mapping solves the situation, this is actually a common Node development setup. You create a volume /usr/app/node_modules. Note, that this volume does not have a host part there is no : in the mapping, there is only one directory here. This means that Docker will mount the /usr/app/node_modules directory from the image and add it to the previous mapping where you mapped the host dir to /usr/app.

So in the running container you'll have your source code from the host's current directory PLUS node_modules from the underlying image due to the double mapping.

As a side effect you'll see an empty node_modules directory in your host's current directory.

查看更多
登录 后发表回答