简体   繁体   中英

Read Kubernetes configMap , nodeJS/express API application

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM