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

时间:2019-11-27 13:54:42

标签: reactjs kubernetes environment-variables next.js

在我的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 /容器中的环境变量在前端(基于浏览器)应用程序上部署文件吗?

谢谢。

编辑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

1 个答案:

答案 0 :(得分:3)

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

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