Kubernetes secrets passed in to React App container but not being used

11/5/2021

For my React App made with create-react-app, I want to use Kubernetes secrets as environment variables.

These secrets are used for different NodeJS containers in my cluster and they work just fine. I used a shell to echo the variables within the frontend container itself, and they are there but I realize that the environment variables are not loaded in the React App.

I have ensured that the environment variable keys start with REACT_APP_, so that is not the problem.

Here are some files:

frontend.yml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: frontend
  labels:
    app: frontend
spec:
  selector:
    matchLabels:
      app: frontend
  replicas: 1
  template:
    metadata:
      labels:
        app: frontend
    spec:
      containers:
      - name: frontend
        image: build_link
        ports:
        - containerPort: 3000
        envFrom:
          - secretRef:
              name: prod

Dockerfile

FROM node:17.0.1-alpine3.12

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app

# latest yarn
RUN npm i -g --force yarn serve

COPY package.json yarn.lock .

RUN yarn --frozen-lockfile

# Legacy docker settings cos node 17 breaks build
ENV NODE_OPTIONS=--openssl-legacy-provider

COPY . .

RUN yarn build

ENV NODE_ENV=production

EXPOSE 3000

CMD ["yarn", "prod"]

Kubernetes prod secret

kubectl describe secret prod
Name:         prod
Namespace:    default
Labels:       <none>
Annotations:  <none>

Type:  Opaque

Data
====
REACT_APP_DOCS_SERVER_URL:      41 bytes
REACT_APP_AUTH0_CLIENT_ID:      32 bytes
REACT_APP_AUTH0_DOMAIN:         24 bytes

env of react app console logged in production (sorry i was desperate)

FAST_REFRESH: true
NODE_ENV: "production"
PUBLIC_URL: ""
WDS_SOCKET_HOST: undefined
WDS_SOCKET_PATH: undefined
WDS_SOCKET_PORT: undefined
-- Marcus Teh
docker
kubernetes
reactjs

1 Answer

11/5/2021

The build command for create-react-app takes in environment variables present during the build phase, causing the environment variables added later to be missing.

The fix I made involves combining removing the build command in the Dockerfile and then combining the build and run command in the same command: package.json

{
  ...
  "scripts": {
    "prod": "yarn build && serve build -l 3000",
    "build": "react-scripts build"
  }
}
-- Marcus Teh
Source: StackOverflow