How to get docker and npm workspaces to work fine without copying root master node_modules everywhere

Viewed 2017

I have a project structure like so:

+-- node_modules
+-- package-lock.json
+-- package.json
`-- workspace-a
   `-- package.json <---includes common as a dependency
`-- common
   `-- package.json

and I have a Dockerfile as follows:

FROM node:alpine as builder

# from monorepo root
WORKDIR /app

COPY ./package*.json ./

COPY ./common/package*.json ./common/

COPY ./workspace-a/package*.json ./workspace-a/

RUN npm config set optional

RUN npm i

# build common library
WORKDIR /app/common

COPY ./common ./

RUN npm run build

# build workspace-a using built common library as dependency
WORKDIR /app/workspace-a

COPY ./auth ./

CMD ["npm","run", "build"]

FROM node:alpine
ENV CI=true

WORKDIR /app

COPY --from=builder /app/workspace-a/build .

COPY ./workspace-a/package*.json .

# RUN npm i --only=prod <--- this step will complain about "common" not being available, but added it just to try it

CMD ["npm","start"]

I was wondering how I can avoid having to copy node_modules, which I believe is a giant consolidated folder of all the dependencies that eliminates the need for the submodules to have their own separate node_modules folder, over to each of the containers that will use it. For example, I plan to have a workspace-b added eventually, which will also have its own Dockerfile that will be more or less identical to the one for workspace-a as shown above.

1 Answers

If you want to stop your node_modules folder being copied when you do

COPY ./common ./

Then you want to have a .dockerignore file that contains the directory that docker should ignore, in this case the file would include just:

node_modules

See this page for info

Related