Adding a secure npm repository to a docker container using kubernetes/skaffold deployment strategy

I'm currently facing challenges with building my application on a local cluster using skaffold, k8s, and docker. In particular, I have a code repository that requires a private NPM package, but during the build process, it seems to lose the .npmrc file or the npm secret.

npm ERR! code E404
npm ERR! 404 Not Found - GET https://registry.npmjs.org/@sh1ba%2fcommon - Not found
npm ERR! 404 
npm ERR! 404  '@sh1ba/common@^1.0.3' is not in the npm registry.
npm ERR! 404 You should bug the author to publish it (or use the name yourself!)
npm ERR! 404 
npm ERR! 404 Note that you can also install from a
npm ERR! 404 tarball, folder, http url, or git url.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2021-06-02T06_08_57_246Z-debug.log
unable to stream build output: The command '/bin/sh -c npm install' returned a non-zero code: 1. Please fix the Dockerfile and try again..

Instead of hardcoding the secret into the file, I'd prefer to utilize a k8s environment variable to pass the key to docker as a secret. I've tried different approaches:

  • Using "--build-args" with the npm secret (not recommended)
  • Using "--secret" with the npm secret (a more secure method)
  • Copying the .npmrc file directly, running `npm install`, and then deleting it

The problem arises when attempting to build it using kubernetes/skaffold. It appears that none of the args, env variables, or even the .npmrc file is being recognized. After inspecting the dockerfile, it seems that nothing is being passed over from the manifest (args defined, .npmrc file, etc) to the dockerfile.

Below is an excerpt from the application's manifest:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: auth-depl
spec:
  replicas: 1
  selector: 
    matchLabels:
      app: auth
  template:
    metadata:
      labels:
        app: auth
    spec:
      containers:
        - name: auth
          image: auth
          env:
            - name: NPM_SECRET
              valueFrom:
                secretKeyRef:
                  name: npm-secret
                  key: NPM_SECRET
          args: ["--no-cache", "--progress=plain", "--secret", "id=npmrc,src=.npmrc"]

This is the relevant code in the dockerfile:

# syntax=docker/dockerfile:1.2
# --------------> The build image
FROM node:alpine AS build
WORKDIR /app
COPY package*.json .
RUN --mount=type=secret,mode=0644,id=npmrc,target=/app/.npmrc \
  npm install

# --------------> The production image
FROM node:alpine

WORKDIR /app
COPY package.json .
COPY tsconfig.json .
COPY src .
COPY prisma .

COPY --chown=node:node --from=build /app/node_modules /app/node_modules
COPY --chown=node:node . /app
s
RUN npm run build

CMD ["npm", "start"]

Additionally, here is the skaffold configuration:

apiVersion: skaffold/v2alpha3
kind: Config
deploy:
  kubectl:
    manifests:
      - ./infra/k8s/*
      - ./infra/k8s-dev/*
build:
  local:
    push: false
  artifacts:
    - image: auth
      context: auth
      docker:
        dockerfile: Dockerfile
      sync:
        manual:
          - src: 'src/**/*.ts'
            dest: .

A few points to consider:

  • I've struggled to locate the .npmrc file no matter where I place it (in auth, in the manifest, in skaffold, or in the ~/ directories)
  • I aim to make it easily adaptable for production so that major changes aren't required (although I would appreciate feedback if this approach is unsound)
  • While I managed to get it working with buildArgs in the skaffold.yaml file, I'm uncertain about how this translates to a production environment since passing build args from kubernetes to docker isn't considered safe practice, and secrets are preferred
  • The args in the manifest are causing the following error (server runs successfully if args are excluded):
 - deployment/auth-depl: container auth terminated with exit code 9
    - pod/auth-depl-85fb8975d8-4rh9r: container auth terminated with exit code 9
      > [auth-depl-85fb8975d8-4rh9r auth] node: bad option: --progress=plain
      > [auth-depl-85fb8975d8-4rh9r auth] node: bad option: --secret
 - deployment/auth-depl failed. Error: container auth terminated with exit code 9.

Any advice or insights would be greatly appreciated as I've been struggling with this issue for quite some time now.

Thank you!

Answer №1

When it comes to building and deploying an image to Kubernetes, there are three key levels to consider:

  1. Initiating the building of an image on your local system
  2. The Docker build process that creates and stores the image
  3. Running the image on the Kubernetes cluster

It's worth noting that Docker may or may not be involved in running the containers on some clusters, as this aspect is subject to change.

There are two instances where you may need to handle secrets:

  • During the image building process (steps #1 to #2) using Docker --build-args or --secret
  • At deployment time (step #3) using Kubernetes secrets or config maps, which are separate from the image build process

Skaffold allows you to pass build-time secrets, such as npm passwords, using Docker's --build-args and --secret flags, albeit with slight modifications.

buildArgs supports Go-style templating for referencing environment variables like MYSECRET as {{.MYSECRET}}:

build:
  local:
    useBuildkit: true
  artifacts:
    - image: auth
      context: auth
      docker:
        buildArgs:
          MYSECRET: "{{.MYSECRET}}"

This approach enables you to reference MYSECRET within your Dockerfile.

If your secret is stored in a file locally, you can utilize the secret field in the skaffold.yaml:

build:
  local:
    useBuildkit: true
  artifacts:
    - image: auth
      context: auth
      docker:
        secret:
          id:   npmrc
          src: /path/to/.npmrc

You would then reference the secret in your Dockerfile accordingly.


When configuring your Deployment, ensure you correctly specify the args for your container:

          args: ["--no-cache", "--progress=plain", "--secret", "id=npmrc,src=.npmrc"]

The args field overrides the CMD set in your image directive, providing command-line arguments for your image's entrypoint which is typically node. If you need to access a secret in a running container within a cluster, consider using a Secret or ConfigMap.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Upon transitioning from Angular 5 to Angular 6, a noticeable issue arises: The existing document lacks a required doctype

I recently updated my project from Angular 5 to Angular 6. Post-upgrade, everything compiles without errors. However, when I try to access the website, all I see is a blank screen. Upon inspecting the console, I came across the following error message: Th ...

The error message "npm start error - No production canister_ids.json can be located. Proceeding with local

Every time I execute npm start, the same "error" message pops up saying "No production canister_ids.json found. Continuing with local" Initially, there appeared to be a proxy issue that was visible in the browser console. I was able to resolve it by makin ...

Ensure that both the source and distribution versions of my NPM package are accessible

I have been working on a special NPM package that is exclusively available to developers who utilize our API. Due to certain management decisions, the structure of the package in our NPM repository (Sonatype Nexus) is as follows: +- build | |- browser.min ...

Leveraging jQuery plugin within a React ecosystem

While utilizing semantic react, I found myself in need of a date picker. Fortunately, I stumbled upon this library: https://github.com/mdehoog/Semantic-UI-Calendar However, I am unsure how to incorporate it into my react-based project since it's not ...

The installed local Angular version is outdated compared to the current project version

I've been having trouble customizing my Angular CLI because a package I need only works with an older version of Angular. Currently, my global Angular version is 15.2.9. However, when I create a new Angular project using ng new, the package.json shows ...

The issue arises when TypeScript declarations contain conflicting variables across multiple dependencies

My current project uses .NET Core and ReactJS. Recently, I updated some packages to incorporate a new component in a .tsx file. Specifically, the version of @material-ui/core was updated from "@material-ui/core": "^3.0.3" to "@material-ui/core": "^4.1.3" i ...

When attempting to compile the building project following the upgrade to Angular 9, an error message is displayed stating "Unable to access property 'length' as it is undefined

I'm currently in the process of updating my Angular 9 project by following the migration guide on update.angular.io. After running ng update @angular/core @angular/cli, I encountered an error "ERROR in Cannot read property 'length' of undefi ...

What could be causing a JavaScript error when attempting to run "node compile.js" for my unique dijit theme?

Just recently, I discovered that it is possible to utilize Node.js in conjunction with "less" to produce a customized Dojo Dijit theme. After downloading Node, I globally installed less using the following command: npm install -g less Next, I made update ...

Using nwb build-react-app will set up the root path instead of the relative path

I have been experimenting with nwb to simplify the process of building react apps using the example project found here. After successfully building the app, I noticed that the paths for the css and js files referenced in index.html are absolute rather than ...

The current version of JavaScript does not have support for string templates

Attempting to utilize ES6 String Templates in a Node.js (version 5.7.0) application, but encountering issues. Webstorm is alerting me that The current Javascript version does not support string templates I am positive I have successfully used string te ...

npm installation displays a variety of colors on Docker Hub during the installation process

When attempting npm install in a Dockerfile, I thought disabling the colors would eliminate color codes in the Dockerhub build logs. However, that doesn't seem to be the case. Can anyone point out where I might have gone wrong? To see the details of ...

What is preventing my application (docker) from connecting to the database?

Encountering a frustrating issue here: I've developed a NodeJS application with a server listening on port number 3000. The app includes simple operations such as post, put, and read, which interact with a database running in a Docker Container on por ...

Uninstall the npm package "reload"

Looking for assistance with Ubuntu 14.04. Yesterday, I attempted to set up an "auto-reload" feature for node.js using supervisor + reload. Initially everything was working fine, but after a few reboots, severe lagging started occurring. Upon investigation ...

Tips for inserting a new row directly beneath the header in Google Sheets using the google-spreadsheet npm module:

While I have successfully been able to insert rows below the existing ones using the google-spreadsheet package, my goal is to add a row at the top of the existing rows just beneath the header - essentially inserting it at Row 2 and shifting all other rows ...

Cloud9 encounters NPM update issue with error message 'npm log' module cannot be found

Hey there! This morning I kicked off a brand new project in Cloud9, and encountered an update prompt when running "npm init" which I complied with. After what seemed like a successful installation, I proceeded to run "npm install" for some packages, only ...

Storing kubernetes secrets securely within GitHub Actions

We are currently implementing the use of github actions, with a focus on securely storing sensitive information like kubeconfig within github's secrets. A GitHub secret has been set up under the name KUBECONFIG1 Steps to Replicate The GitHub secret ...

Add the scss file to the vuejs component npm package only if certain conditions specified in the project are met

Creating css/scss themes for my Vue Components Npm package has been a focus of mine lately. This particular package is local and currently being tested using npm link. Both the Package and Project are utilizing webpack. index.js of Package import "./src ...

The function createAnimatedSwitchNavigator is not recognized and cannot be found

I ran into a problem while developing my react native app. I wanted to utilize an NPM package called createAnimatedSwitchNavigator However, upon trying to execute the program, I encountered the following error message: undefined is not a function (e ...

The process.env.NEXT_PUBLIC variable in NextJS seems to be cleared out in production environments

I am facing an issue with my NextJS app "^11.1.2" when deploying it using Dockerfile and CI/CD to production. The problem arises with the rendering of my process.env variables Within my client-side code, I have the following line that should be rendered a ...

Tips for circumventing the need to utilize npx Create-react-app repeatedly

Not sure, but it seems to take quite a while to resolve things... should I go ahead and install it globally with the -g flag? Every time I install it, react and react-dom are also included... if I were to install react globally, would that help reduce th ...