如何从 Next.js 应用程序访问 Kubernetes 容器环境变量?

2024-04-28

在我的 next.config.js 中,我有一个如下所示的部分:

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 文件中获取环境变量。

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

axios.get(publicRuntimeConfig.BACKOFFICE_BACKEND_URL)

但是,当我将此应用程序部署到 Kubernetes 集群上时,不会收集部署文件中设置的环境变量。所以它们返回为未定义。

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

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

Thanks.

EDIT 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

您可以创建一个配置映射,然后使用自定义环境变量将其作为文件安装在部署中。

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

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

      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

然后,您可以使用 kubernetes 上的环境变量创建带有键“.env”的配置映射。

配置图是这样的:

apiVersion: v1
kind: ConfigMap
metadata:
  name: environment-variables
  namespace: your-namespace
data:
  .env: |
    variable1: value1
    variable2: value2
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何从 Next.js 应用程序访问 Kubernetes 容器环境变量? 的相关文章

随机推荐