Hey I'm a newbie to both docker and node . I was trying to dockerize a simple node api . Here's my docker file:
WORKDIR app
EXPOSE 3000
ENV NODE_ENV=production
COPY package.json package-lock.json ./
RUN \
--mount=type=cache,target=~/.npm\
npm ci --only-production
USER node
COPY --chown=node:node /src .
CMD [ "npm" , "run" , "dev"]
My doubts and questions , have arised , when i tried to add the cache mount , as far as i know i need to find where npm caches its packages so i can mount my cache to that location in order for npm to be able to find them so it doesn't redownload them . At first the user is the root so i'll mount the cache to the /root/.npm (~ here will be the root home) but then when i switch to the node user and run npm run won't it be unable to find the cached dependencies because the home has changed (it will become /home/node).
whenever i switch users for security purposes i really get confused about these kind of things , so any clarification will be appreciated.
A RUN --mount
option only applies to the specific RUN
command it's on. Once that RUN
command is finished, the mount is removed.
That means you only need to have the correct mount path for whatever directory context is correct when you're running the command. If the home directory is /root
when you run that one command, then it's correct to hard-code
RUN --mount=type=cache,target=/root/.npm \
npm ci --only-production
When you go to run the application, it will use the local node_modules
directory and it won't look at this cache directory at all.
(It is correct for node_modules
to be owned by root, with files generally world-readable but not world-writable. I might similarly remove the COPY --chown
option to apply the same permissions to your source code, preventing it from getting accidentally overwritten.)