如何在K8S中正确定义MERN堆栈容器的变量?



我正在尝试运行kubernetes mern应用程序(https://github.com/ibrahima92/fullstack-typescript-mern-todo/)。我有一个客户端和一个服务器容器,我需要替换后端url客户端的路径,所以我在后端代码中定义了变量,但它们不替换清单文件中变量的值。容器中有变量,但后端不使用它们。我尝试了这些选择。$ {FRONT_URL}, {process.env美元。process.env.FRONT_URL FRONT_URL}。如果我直接在后端代码中插入服务的URL和端口号,那么一切都可以正常工作。如何在容器中正确定义变量?

我需要将http://localhost:${PORT}替换为K8S和服务的url${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
})

清单

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


你可以创建一个配置映射,给你的容器运行时变量,或者,使用ENV

构建自己的docker映像您也可以使用自定义来实现。

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

envFrom: 
- secretRef: 
 name: my-secret

最新更新