Using the Private NPM Registry from Docker

RisingStack's services:


Node.js Experts

Learn more at

Sign up to our newsletter!

In this article:

It has been a while since NPM had announced support for private modules – still, to make it with Docker you need some work to do. In this quick tip, you can learn how to use private Node.js modules with Docker.

During this guide I am going to use the RisingStack Alpine Node.js Docker image.

Setting up the Dockerfile

Let’s start with the following simple Dockerfile:

It doesn’t do anything extraordinary, just grabs the Alpine image, copies over the package.json file, installs the dependencies, copies the source files and starts the process.

Adding the NPM token

To access the private modules in NPM, we need to pass the NPM_TOKEN environment variable to the Docker image.

The naive approach would be to add it using the ENV:


However, it does not work. The variables set with ENV are for runtime only.

Luckily since Docker v1.9 there is a new flag available for passing in build-time environment variables: the --build-arg. To make it work we have to modify our Dockerfile:

Note a couple of changes:

  • ARG: with this we can tell Docker, that we will use the NPM_TOKEN build argument
  • COPY .npmrc: using this line we add an .npmrc file to the project. Its content: //${NPM_TOKEN}
  • rm -f .npmrc: simply remove the .npmrc file after npm install is done

To build the image using this image and the token, you can run Docker:

docker build --build-arg NPM_TOKEN=${NPM_TOKEN} .

One thing to keep in mind: even if you delete the .npmrc it will be kept in the commit history – to clean your secret entirely up make sure to squash them.

Let me know if you have any questions or comments.

Share this post



Learn more at

Node.js Experts