How to correctly define variables for a container of MERN stack in K8S?

Viewed 26

I'm trying to run in kubernetes mern application (https://github.com/ibrahima92/fullstack-typescript-mern-todo/). I have a client and a server container, and I need to replace the path to the url client in the backend, so I defined variables in the backend code, but they don't replace the values of the variables from the manifest files. There are variables inside the container, but the backend does not use them. I tried such options 1. ${FRONT_URL}, ${process.env.FRONT_URL}, process.env.FRONT_URL. If I directly insert the URL of the service with the port number in backend code then everything works. How to correctly define variables in a container?

I need replace http://localhost:${PORT} to url of service from K8S and the same thing need to do with ${MONGO_URL}

import express, { Express } from 'express'
import mongoose from 'mongoose'
import cors from 'cors'
import todoRoutes from './routes'

const app: Express = express()

const PORT: string | number = process.env.PORT || 4000

app.use(cors())
app.use(todoRoutes)

const uri: string = `mongodb://${MONGO_URL}?retryWrites=true&w=majority`
const options = { useNewUrlParser: true, useUnifiedTopology: true }
mongoose.set('useFindAndModify', false)

mongoose
    .connect(uri, options)
    .then(() =>
        app.listen(PORT, () =>
            console.log(`Server running on http://localhost:${PORT}`)
        )
    )
    .catch((error) => {
        throw error
    })

Manifest

apiVersion: apps/v1
kind: Deployment
metadata:
  name: todo-server-app-deploy
spec:
  replicas: 1
  selector:
    matchLabels:
      app: todo-server-app
  template:
    metadata:
      labels:
        app: todo-server-app
    spec:
      containers:
        - image: repo/todo-server-app:24
          name: container1
          ports:
          - containerPort: 4000
          env:
            - name: FRONT_URL 
              value: a1ecab155236d4c7fba8b0c6a1b6ad2b-549550669.us-east-1.elb.amazonaws.com:80
            - name: MONGO_URL
              value: todo-mongo-service:27017
          imagePullPolicy: IfNotPresent
              



1 Answers

You can create a config map, giving your container run time variables, Or alternatively, build your own docker image using the ENV

You can also acheive that using kustomization.

  • kustomization.yml
secretGenerator: 
   - name: my-secret 
     behavior: create 
     env: .env
  • Deployment.yml

envFrom: 
- secretRef: 
  name: my-secret

Related