NpmAuthenticate in Docker context on Azure DevOps pipeline
Are you utilizing a Docker container for your application builds? If so, and you’re implementing a staged build strategy, you might need to authenticate with your Azure DevOps artifact repository from within the build container. Here’s how to achieve that:
-
Create a copy of
.npmrcfile for it to be enriched with credentials# a bash task in your Azure pipeline cp -a src/.npmrc src/.user_npmrc -
Use the NpmAuthenticate task in your pipeline to generate the credentials for the private registry. Note: Be sure to specify
.user_npmrcasworkingFile. We’ll see later why. Also, being a copy of.npmrcit specifies the registries you want to work with. For example, for a file that lives under asrcsubdir in the project root:steps: - task: npmAuthenticate@0 inputs: workingFile: $(System.DefaultWorkingDirectory)/src/.user_npmrc -
Add a
COPYdirective to yourDockerfileto copy.user_npmrc, now with credentials, inside the image and be used bynpm.Tip: Copy it to
/tmpto prevent private registry credentials to be eventually included in the finalized Docker image.COPY .user_npmrc /tmp/.npmrc -
Modify your
Dockerfileto specify the path to thenpmuser config usingNPM_CONFIG_USERCONFIGenvironment variable in anARGstatement.Note:
ARGrepresents environment variables utilized only during Docker image build time. This step is needed because, by default,npmchecks for credentials in the (other).npmrcfile, the one in the user’s home folder, but this time we want it to use the one from/tmpwe copied in the previous step.ARG NPM_CONFIG_USERCONFIG=/tmp/.npmrc
Important: Ensure these lines are placed above the npm install command in your Dockerfile! By doing so, the path to your user .npmrc file will be accessible during your npm install command allowing node modules in private registries to be downloaded and installed.
In the end, your Dockerfile should look like this:
FROM node:18
# ...
ARG NPM_CONFIG_USERCONFIG=/tmp/.npmrc
COPY .user_npmrc /tmp/.npmrc
COPY package.json package-lock.json .npmrc ./
COPY src ./src
RUN npm install --omit=dev
# ...
That’s it!
I hope it helps. Thanks for reading.
