Docker with Private NPM Dependencies

Posted Saturday, January 9, 2021.

In a previous post private npm packages, we walked through how to pull down a private dependency package to our application. Once you are done developing, you might want to build it in docker for distribution. It's not as easy as just building it as you need to supply special permissions to the docker container so it can pull from this private repo. Let's see how to do this.

More Personal Access Tokens

Create a new personal access token on GitHub, this time with read:packages only. We do this so we dont give the docker container any escalated privileges, even if they are only temporary (if you are using a two stage build for example)

  1. Go to github.com
  2. Select settings and go to Developer Settings > Personal access tokens
  3. Generate a new token with the following scope: read:packages
  4. Name it something which you will remember what it is for and copy the token value
  5. Create a new file at ~/.npm/github_token and place the contents of the token in there

Create a .npmrc dummy deploy file

We will make a local file in the project (similar to .npmrc that you might normally use), but we need to have a variable injected into it. Create a file in the root of your consuming project /.npmrc-deploy with the following contents (adjusting registry name):

//npm.pkg.github.com/:_authToken=${NPM_TOKEN}
@hiimtmac:registry=https://npm.pkg.github.com

Adjust the dockerfile

Our current dockerfile might look something like this:

FROM node:14

WORKDIR /app
COPY . ./
RUN yarn && yarn build

We will make a couple changes so that yarn wont hit any snags when pulling our private package:

FROM node:14

ARG NPM_TOKEN

WORKDIR /app
COPY . ./
COPY ./.npmrc-deploy ./.npmrc
RUN yarn && yarn build

What this does is copy our .npmrc-deploy file in as if it was a regular .npmrc file for yarn to use. The NPM_TOKEN arg can then be injected at build time so that there is a valid token. This build command will look like this:

docker build --build-arg NPM_TOKEN="$(cat ~/.npm/github_token)" -t hiimtmac/cool-app .

We didn't call the file .npmrc because that would effect the local dev experience and we want it to use the global config at ~/.npmrc instead.

In Closing

This mechanism for building NPM applications with private packages has worked well for me. If there is a better way to go about this, please let me know!


Tagged With: