ConfigMaps
Course: Kubernetes Part 2 - chapter 14
Ref - https://kubernetes.io/docs/concepts/configuration/configmap/
A ConfigMap is an API object used to store non-confidential data in key-value pairs. Pods can consume ConfigMaps as environment variables, command-line arguments, or as configuration files in a volume.
A ConfigMap allows you to decouple environment-specific configuration from your container images, so that your applications are easily portable.
Creating a ConfigMap
Section titled “Creating a ConfigMap”- Create the manifest
apiVersion: v1kind: ConfigMapmetadata: name: ecom-backend-configdata: database_url: "mysql://ecom-db:3306/shop" cache_size: "1000" payment_gateway_url: "https://payment-gateway.example.com" max_cart_items: "50" session_timeout: "3600"- Apply the manifest
kubectl apply -f cm.yml- Get the configmap
kubectl describe configmap ecom-backend-configCreating an express app that exposes env variables
Section titled “Creating an express app that exposes env variables”Express app code
import express from 'express';import fs from 'fs';import path from 'path';
const app = express();const port = 3000;app.get('/', (req, res) => { const envVars = { DATABASE_URL: process.env.DATABASE_URL, CACHE_SIZE: process.env.CACHE_SIZE, PAYMENT_GATEWAY_URL: process.env.PAYMENT_GATEWAY_URL, MAX_CART_ITEMS: process.env.MAX_CART_ITEMS, SESSION_TIMEOUT: process.env.SESSION_TIMEOUT, };
res.send(` <h1>Environment Variables</h1> <pre>${JSON.stringify(envVars, null, 2)}</pre> `);});
app.listen(port, () => { console.log(`App listening at http://localhost:${port}`);});Dockerfile to containerise it
FROM node:20
WORKDIR /usr/src/app
COPY package*.json ./RUN npm install
COPY . .
RUN npx tsc -b
EXPOSE 3000CMD [ "node", "index.js" ]Deploy to dockerhub - [https://hub.docker.com/repository/docker/100xdevs/env-backend/general](https://hub.docker.com/repository/docker/100xdevs/env-backend/general)
Trying the express app using docker locally
Section titled “Trying the express app using docker locally” docker run -p 3003:3000 -e DATABASE_URL=asd 100xdevs/env-backend
Try running using k8s locally
Section titled “Try running using k8s locally”- Create the manifest (express-app.yml)
$1b- Apply the manifest
kubectl apply -f express-app.yml- Create the service (express-service.yml)
apiVersion: v1kind: Servicemetadata: name: ecom-backend-servicespec: type: NodePort selector: app: ecom-backend ports: - port: 3000 targetPort: 3000 nodePort: 30007- Apply the service
kubectl apply -f express-service.yml- Try visiting the website
