如何从Next.js应用程序访问Kubernetes容器环境变量? [英] How to access Kubernetes container environment variables from Next.js application?

查看:80
本文介绍了如何从Next.js应用程序访问Kubernetes容器环境变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的next.config.js中,我有一部分看起来像这样:

In my next.config.js, I have a part that looks like this:

module.exports = {
  serverRuntimeConfig: { // Will only be available on the server side
    mySecret: 'secret'
  },
  publicRuntimeConfig: { // Will be available on both server and client
    PORT: process.env.PORT,
    GOOGLE_CLIENT_ID: process.env.GOOGLE_CLIENT_ID,
    BACKEND_URL: process.env.BACKEND_URL
  }

我有一个.env文件,当在本地运行时,Next.js应用程序成功从.env文件中获取环境变量。

I have a .env file and when run locally, the Next.js application succesfully fetches the environment variables from the .env file.

例如,我引用这样的env变量:

I refer to the env variables like this for example:

axios.get(publicRuntimeConfig.BACKOFFICE_BACKEND_URL)

但是,当我将此应用程序部署到Kubernetes集群上时,环境变量在部署文件未收集。因此它们以未定义的形式返回。

However, when I have this application deployed onto my Kubernetes cluster, the environment variables set in the deploy file are not being collected. So they return as undefined.

我读到由于前端(基于浏览器)和后端(基于节点)之间的差异而无法读取.env文件,但是必须有某种方法可以实现工作。

I read that .env files cannot be read due to the differences between frontend (browser based) and backend (Node based), but there must be some way to make this work.

有人知道如何使用保存在pod /容器中的环境变量在前端(基于浏览器)应用程序上部署文件吗?

Does anyone know how to use environment variables saved in your pods/containers deploy file on your frontend (browser based) application?

谢谢。

编辑1:

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "38"
  creationTimestamp: xx
  generation: 40
  labels:
    app: appname
  name: appname
  namespace: development
  resourceVersion: xx
  selfLink: /apis/extensions/v1beta1/namespaces/development/deployments/appname
  uid: xxx
spec:
  progressDeadlineSeconds: xx
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: appname
      tier: sometier
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: appname
        tier: sometier
    spec:
      containers:
      - env:
        - name: NODE_ENV
          value: development
        - name: PORT
          value: "3000"
        - name: SOME_VAR
          value: xxx
        - name: SOME_VAR
          value: xxxx
        image: someimage
        imagePullPolicy: Always
        name: appname
        readinessProbe:
          failureThreshold: 3
          httpGet:
            path: /healthz
            port: 3000
            scheme: HTTP
          initialDelaySeconds: 5
          periodSeconds: 10
          successThreshold: 1
          timeoutSeconds: 1
        resources:
          requests:
            cpu: 100m
            memory: 100Mi
        terminationMessagePath: /dev/termination-log
        terminationMessagePolicy: File
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
status:
  availableReplicas: 1
  conditions:
  - lastTransitionTime: xxx
    lastUpdateTime: xxxx
    message: Deployment has minimum availability.
    reason: MinimumReplicasAvailable
    status: "True"
    type: Available
  observedGeneration: 40
  readyReplicas: 1
  replicas: 1
  updatedReplicas: 1


推荐答案

您可以创建一个配置映射然后挂载

You can create a config-map and then mount it as a file in your deployment with your custom environment variables.

apiVersion: extensions/v1beta1
kind: Deployment
metadata:
  annotations:
    deployment.kubernetes.io/revision: "38"
  creationTimestamp: xx
  generation: 40
  labels:
    app: appname
  name: appname
  namespace: development
  resourceVersion: xx
  selfLink: /apis/extensions/v1beta1/namespaces/development/deployments/appname
  uid: xxx
spec:
  progressDeadlineSeconds: xx
  replicas: 1
  revisionHistoryLimit: 10
  selector:
    matchLabels:
      app: appname
      tier: sometier
  strategy:
    rollingUpdate:
      maxSurge: 1
      maxUnavailable: 1
    type: RollingUpdate
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: appname
        tier: sometier
    spec:
      containers:
        - env:
            - name: NODE_ENV
              value: development
            - name: PORT
              value: "3000"
            - name: SOME_VAR
              value: xxx
            - name: SOME_VAR
              value: xxxx
          volumeMounts:
            - name: environment-variables
              mountPath: "your/path/to/store/the/file"
              readOnly: true
          image: someimage
          imagePullPolicy: Always
          name: appname
          readinessProbe:
            failureThreshold: 3
            httpGet:
              path: /healthz
              port: 3000
              scheme: HTTP
            initialDelaySeconds: 5
            periodSeconds: 10
            successThreshold: 1
            timeoutSeconds: 1
          resources:
            requests:
              cpu: 100m
              memory: 100Mi
          terminationMessagePath: /dev/termination-log
          terminationMessagePolicy: File
      volumes:
        - name: environment-variables
          configMap:
            name: environment-variables
            items:
              - key: .env
                path: .env
      dnsPolicy: ClusterFirst
      restartPolicy: Always
      schedulerName: default-scheduler
      securityContext: {}
      terminationGracePeriodSeconds: 30
status:
  availableReplicas: 1
  conditions:
    - lastTransitionTime: xxx
      lastUpdateTime: xxxx
      message: Deployment has minimum availability.
      reason: MinimumReplicasAvailable
      status: "True"
      type: Available
  observedGeneration: 40
  readyReplicas: 1
  replicas: 1
  updatedReplicas: 1

我在部署文件中添加了以下配置:

I added the following configuration in your deployment file:

      volumeMounts:
        - name: environment-variables
          mountPath: "your/path/to/store/the/file"
          readOnly: true
  volumes:
    - name: environment-variables
      configMap:
        name: environment-variables
        items:
          - key: .env
            path: .env

然后,您可以使用 .env键创建配置映射

You can then create a config map with key ".env" with your environment variables on kubernetes.

Configmap像这样:

Configmap like this:

apiVersion: v1
kind: ConfigMap
metadata:
  name: environment-variables
  namespace: your-namespace
data:
  .env: |
    variable1: value1
    variable2: value2

这篇关于如何从Next.js应用程序访问Kubernetes容器环境变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆