Read Kubernetes configMap , nodeJS/express API application

10/11/2021

I have a nodeJS api services and .env file with some configuration.

Currently, in my local environment I can run my service. I read the .env file on startup and access the value via process.env.name command

const myEnv = dotenv.config({ path: path.resolve(path.join(__dirname, '/configuration/.env')) });
dotenvExpand(myEnv);

This is my setting in my deployment yaml file

 envFrom:
         - configMapRef:
             name: jobs-nodeapi-qa--configmap

I create a configMap in GCP and deploy. How do I change my code so that it read from the config map

Thanks

-- user2570135
docker
google-cloud-platform
kubernetes
node.js

1 Answer

10/12/2021

No need to change your code which refer to the .env file. Since you have created the ConfigMap, you can then mount it to the correct path that your code expected it to be.

Create the ConfigMap:

apiVersion: v1
kind: ConfigMap
metadata:
  name: env
data:
  .env: |
    key=value

Use it in the pod:

apiVersion: v1
kind: Pod
metadata:
  name: busybox
  labels:
    app: busybox
spec:
  volumes:
  - name: env
    configMap:
      name: env
  containers:
  - name: busybox
    image: busybox
    command:
    - sh
    - -c
    - while :; do cat /configuration/.env; sleep 1; done
    volumeMounts:
    - name: env
      mountPath: /configuration # update this path to the path your app expects

A simple usage above is output the .env content every second.

-- gohm'c
Source: StackOverflow