Injecting Environment Variables into Secret-Mounted .npmrc in Docker

Hello everyone!

I’ve just started to learn Docker (three days ago), so, please, bear with me.

I have a private NPM module which I can install using .npmrc in a project root folder. The content of .npmrc is the following:

@games:registry=https://gitlab.com/api/v4/projects/12345678/packages/npm/
//gitlab.com/api/v4/projects/12345678/packages/npm/:_authToken=${MATH_SET_TOKEN}

The MATH_SET_TOKEN variable is stored in .bashrc.

Now I want to install that module in a Docker container. I suppose that --mount=type=secret may be useful in this case. From the error I get, it looks that .npmrc is mounted correctly, but the token isn’t. (And I cannot figure out how to properly pass it without hardcoding it into .npmrc.)


The error:

...
> [builder 4/6] RUN --mount=type=secret,id=npmrc,env=MATH_SET_TOKEN     --mount=type=secret,id=npmrc,target=/root/.npmrc     npm ci:
3.089 npm error Bearer @games:registry=https://gitlab.com/api/v4/projects/12345678/packages/npm/
3.089 npm error //gitlab.com/api/v4/projects/12345678/packages/npm/:_authToken=${MATH_SET_TOKEN}
...

An excerpt from my Dockerfile:

...
RUN --mount=type=secret,id=npmrc,env=MATH_SET_TOKEN \
    --mount=type=secret,id=npmrc,target=/root/.npmrc \
    npm ci
...

An excerpt from my docker-compose.yml:

...
secrets:
  npmrc:
    file: ./.npmrc

Question: How to inject environment variables in secret-mounted .npmrc in Docker? Should I add/edit/remove something in Dockerfile, docker-compose.yml? Or should it be done in the terminal?

I think I’ve found a solution that allows referencing environment variables in .npmrc.

Dockerfile:

...
RUN --mount=type=secret,id=npmrc,target=/root/.npmrc \
    --mount=type=secret,id=MATH_SET_TOKEN,env=MATH_SET_TOKEN \
    npm ci
...

docker-compose.yml:

...
services:
  math-service:
    build:
      context: .
      secrets:
        - npmrc
        - MATH_SET_TOKEN
...
secrets:
  npmrc:
    file: ./.npmrc
  MATH_SET_TOKEN:
    environment: MATH_SET_TOKEN