Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 255
reactor Avatar asked Dec 01 '25 03:12

reactor


1 Answers

I know this is old, but I found a solution for me.

The issue with workspaces and docker is that workspaces just makes symlinks to the the workspace folder. When the node_modules folder is mounted as volumes to docker containers, the container sees those symlinks as not belonging to the container and they are disposed of or invalidated.

The solution was simply to run npm install on the entrypoint of the docker container and then run the command to start your application for that container (usually through a npm or bash script that does both). It can get a little complicated for things like containers microsoft makes on their own respository and you may need to use docker inspect on the image to find the startup command. I had a bit of trouble finding the command to start my functions application fwiw.

like image 160
thomasmeadows Avatar answered Dec 02 '25 21:12

thomasmeadows



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!