skip to Main Content

I’m using Nuxt3 with K8 and want to pass some secrets using Kubernetes Secrets to my Nuxt3 app.

I cannot set the environment variables in my Docker container directly, because the container is public.

So I build the image docker image like this

FROM node:18-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build
EXPOSE 3000
ENTRYPOINT [ "node", ".output/server/index.mjs" ]

And then pass secrets to this image using Kubernetes secrets like this

...
    spec:
      containers:
        - name: frontend
          image: <DOCKER_IMAGE>:<VERSION>
          imagePullPolicy: Always
          envFrom:
            - secretRef:
                name: frontend-secret
          ports:
            - containerPort: 3000
      restartPolicy: Always
...

I can see the environment variables set correctly in my pod, but the Nuxt app does not read these. My understanding is maybe because Nuxt reads environment variables at dev, build and generate time and my container has already been built and there were no environment variables available in Docker when it was built.

Now how can the Nuxt app read my secrets passed by Kubernetes after the build stage or any other approach that I can use to resolve this?

2

Answers


  1. According to the linked documentation, the way to do this is by setting the env var directly on the commandline, when the server is run.

    You can override the ENTRYPOINT, passing the env var that has been loaded from the secret

    ...
        spec:
          containers:
            - name: frontend
              image: <DOCKER_IMAGE>:<VERSION>
              imagePullPolicy: Always
              env:
                - name: FRONTEND_SECRET
                  valueFrom:
                    secretKeyRef:
                      key: frontend-secret
                      name: frontend-secret
              command:
                - FRONTEND_SECRET=${FRONTEND_SECRET}
                - node
                - .output/server/index.mjs
              ports:
                - containerPort: 3000
          restartPolicy: Always
    ...
    

    (obviousy changing the name of the key to whatever you have encoded in the secret)

    Login or Signup to reply.
  2. Nuxt3 has runtimeConfig that you may configure, from their docs [1]:

    Nuxt provides a runtime config API to expose configuration and secrets within your application.

    To expose config and environment variables to the rest of your app, you will need to define runtime configuration in your nuxt.config file, using the runtimeConfig option.

    [1]. https://nuxt.com/docs/guide/going-further/runtime-config

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search