Table of contents
Docker and private modules
Table of contents
To install private npm packages in a Docker container, you will need to use Docker build secrets.
Background: runtime variables
You cannot install private npm packages in a Docker container using only runtime variables. Consider the following Dockerfile:
FROM nodeCOPY package.json package.jsonRUN npm install# Add your source filesCOPY . .CMD npm start
Which will use the official Node.js image, copy the package.json
into our container, installs dependencies, copies the source files and runs the start command as specified in the package.json
.
In order to install private packages, you may think that we could just add a line before we run npm install
, using the ENV parameter:
ENV NPM_TOKEN=00000000-0000-0000-0000-000000000000
However, this doesn't work as you would expect, because you want the npm install to occur when you run docker build
, and in this instance, ENV
variables aren't used, they are set for runtime only.
Instead of run-time variables, you must use Docker build secrets.
Update the Dockerfile
The Dockerfile that takes advantage of this has a few more lines in it than the earlier example that allows us to use your global .npmrc
and the access token created when running npm login
command (if you haven't run it already - do so before moving on).
# https://docs.npmjs.com/docker-and-private-modulesFROM node:18ENV APP_HOME="/app"WORKDIR ${APP_HOME}COPY package*.json ${APP_HOME}/RUN --mount=type=secret,id=npmrc,target=/root/.npmrc npm installCOPY . ${APP_HOME}/CMD npm start
This will configure your Dockerfile to receive .npmrc
file via build secrets, that will leave no trace after npm dependency installation is done.
Build the Docker image
To build the image using the above Dockerfile and the npm authentication token, you can run the following command. Note the .
at the end to give docker build
the current directory as an argument.
docker build . -t secure-app-secrets:1.0 --secret id=npmrc,src=$HOME/.npmrc
This will build the Docker image with the access token coming from your global .npmrc
file received via build secrets, so you can run npm install
inside your container as the current logged-in user.
Note: You may need to specify a working directory different from the default /
otherwise some frameworks like Angular will fail.