简体   繁体   中英

Handling node modules with docker-compose

I am building a set of connected node services using docker-compose and can't figure out the best way to handle node modules. Here's what should happen in a perfect world:

  1. Full install of node_modules in each container happens on initial build via each service's Dockerfile
  2. Node modules are cached after the initial load -- ie functionality so that npm only installs when package.json has changed
  3. There is a clear method for installing npm modules -- whether it needs to be rebuilt or there is an easier way

Right now, whenever I npm install --save some-module and subsequently run docker-compose build or docker-compose up --build , I end up with the module not actually being installed.

Here is one of the Dockerfiles

FROM node:latest

# Create app directory
WORKDIR /home/app/api-gateway

# Intall app dependencies (and cache if package.json is unchanged)
COPY package.json .
RUN npm install

# Bundle app source
COPY . .

# Run the start command
CMD [ "npm", "dev" ]

and here is the docker-compose.myl

version: '3'

services:

  users-db:
    container_name: users-db
    build: ./users-db
    ports:
      - '27018:27017'
    healthcheck:
      test: exit 0'

  api-gateway:
    container_name: api-gateway
    build: ./api-gateway
    command: npm run dev
    volumes:
      - './api-gateway:/home/app/api-gateway'
      - /home/app/api-gateway/node_modules
    ports:
      - '3000:3000'
    depends_on:
      - users-db
    links:
      - users-db

It looks like this line might be overwriting your node_modules directory:

# Bundle app source
COPY . .

If you ran npm install on your host machine before running docker build to create the image, you have a node_modules directory on your host machine that is being copied into your container.

What I like to do to address this problem is copy the individual code directories and files only, eg:

# Copy each directory and file
COPY ./src ./src
COPY ./index.js ./index.js

If you have a lot of files and directories this can get cumbersome, so another method would be to add node_modules to your .dockerignore file. This way it gets ignored by Docker during the build.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM