在Next.js应用程序上获取环境变量Kubernetes

问题描述

我一直在阅读有关使K8s环境变量在Next.js应用程序中工作的其他问题,但到目前为止,还没有公认的答案。

我的应用程序使用.env.local可以正常工作,但是部署到K8s时出现错误(未定义)。

这是我的next.config.js

module.exports = {
  env: {
    NEXT_PUBLIC_API_BASE_URL: process.env.NEXT_PUBLIC_API_BASE_URL,},};

K8s环境:

k8s environment

有人可以帮助我让我的next.js应用程序使用该环境变量吗?

现在我做了一个简单的技巧,即在dockerfile上添加了ARG和ENV,然后在构建docker映像时将其注入

Dockerfile:

ARG NEXT_PUBLIC_API_BASE_URL
ENV NEXT_PUBLIC_API_BASE_URL=${NEXT_PUBLIC_API_BASE_URL}

解决方法

您应该在 ENV_VARS 文件中添加 .env.local。以 configMap 的形式。 (https://nextjs.org/docs/basic-features/environment-variables)

在 Kubernetes 中,您可以像这样创建 configMap

apiVersion: v1
name: env-local
data:
  .env: |-
    NEXT_PUBLIC_API_URL=http:/your.domain.com/api
    API_URL=http://another.endpoint.com/serverSide
kind: ConfigMap

然后您将该 configMap 作为 FILE 挂载到您的部署中,然后它在 app/.env.local 处可用:


apiVersion: apps/v1
kind: Deployment
spec:
  replicas: 1
  selector:
    matchLabels:
      app: your-app
  template:
    metadata:
      labels:
        app: your-app
    spec:
      containers:
      - image: your/image:latest
        imagePullPolicy: Always
        name: your-app
        ports:
        volumeMounts:
        - mountPath: /app/.env.local
          name: env-local
          readOnly: true
          subPath: .env.local
      volumes:
      - configMap:
          defaultMode: 420
          items:
          - key: .env
            path: .env.local
          name: env-local
        name: env-local


对于服务器端变量来说,同样有效的方法——至少对我而言——只是将它们作为常规环境变量添加到我的 deployment 中:https://kubernetes.io/docs/tasks/inject-data-application/define-environment-variable-container/#define-an-environment-variable-for-a-container

apiVersion: v1
kind: Pod
metadata:
  name: your-app
  labels:
    purpose: demonstrate-envars
spec:
  containers:
  - name: your-app-container
    image: gcr.io/google-samples/node-hello:1.0
    env:
    - name: DEMO_GREETING
      value: "Hello from the environment"
    - name: DEMO_FAREWELL
      value: "Such a sweet sorrow"

    const withSvgr = require('next-svgr');
    
    module.exports = {   
        // Will only be available on the server side
        serverRuntimeConfig: {
            API_URL: process.env.API_URL,},// Will be available on both server and client
        publicRuntimeConfig: {
            NEXT_PUBLIC_API_URL: process.env.API_URL,};
,

我和你有同样的问题。您必须使用NextJs Runtime Configuration: https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration

要在本地运行,我使用了dotenv。局部变量在.env中设置。在服务器上,使用configMap中定义的环境变量。

示例:

publicRuntimeConfig: {
  NEXT_PUBLIC_API_BASE_URL: process.env.NEXT_PUBLIC_API_BASE_URL,