Install node_modules inside Docker container and synchronize them with host

前端 未结 10 1383
旧巷少年郎
旧巷少年郎 2020-12-12 11:33

I have the problem with installing node_modules inside the Docker container and synchronize them with the host. My Docker\'s version is 18.03.1-ce, build

10条回答
  •  春和景丽
    2020-12-12 12:10

    My workaround is to install dependencies when the container is starting instead of during build-time.

    Dockerfile:

    # We're using a multi-stage build so that we can install dependencies during build-time only for production.
    
    # dev-stage
    FROM node:14-alpine AS dev-stage
    WORKDIR /usr/src/app
    COPY package.json ./
    COPY . .
    # `yarn install` will run every time we start the container. We're using yarn because it's much faster than npm when there's nothing new to install
    CMD ["sh", "-c", "yarn install && yarn run start"]
    
    # production-stage
    FROM node:14-alpine AS production-stage
    WORKDIR /usr/src/app
    COPY package.json ./
    RUN yarn install
    COPY . .
    

    .dockerignore

    Add node_modules to .dockerignore to prevent it from being copied when the Dockerfile runs COPY . .. We use volumes to bring in node_modules.

    **/node_modules
    

    docker-compose.yml

    node_app:
        container_name: node_app
        build:
            context: ./node_app
            target: dev-stage # `production-stage` for production
        volumes:
            # For development:
            #   If node_modules already exists on the host, they will be copied
            #   into the container here. Since `yarn install` runs after the
            #   container starts, this volume won't override the node_modules.
            - ./node_app:/usr/src/app
            # For production:
            #   
            - ./node_app:/usr/src/app
            - /usr/src/app/node_modules
    

提交回复
热议问题