React app doesn't receive environment variables defined in Kubernetes pod

11/20/2021

The app is pretty simple: its job is to display three types of variables:

  1. A variable defined locally in the code,
  2. An environment variable defined in Dockerfile and overwritten on pod creation,
  3. An environment variable defined only on pod creation.

The code is as follows:

import './App.css';

function App() {
  let something = "3Wzc3mgdlIFwc4"
  return (
    <div className="App">
      <header className="App-header">
        <p>
            <code>ENV1: </code> <em>{process.env.REACT_APP_ENV_VARIABLE}</em>
        </p>
        <p>
            <code>ENV2: </code> <em>{process.env.REACT_APP_ENV_VARIABLE_TWO}</em>
        </p>
        <p>
            Hash: <code>{something || "not set"}</code>
        </p>
      </header>
    </div>
  );
}

export default App;

Dockerfile used when building an image got the following values:

FROM node:17.1.0-buster-slim as build
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH

COPY package.json ./
RUN npm config set unsafe-perm true
RUN npm install -g npm@8.1.3
RUN npm install --force
RUN npm install react-scripts@4.0.3 -g

COPY . ./
RUN chown -R node /app/node_modules

ENV REACT_APP_ENV_VARIABLE "It works!"

RUN npm run build

FROM nginx:1.21.4-alpine
COPY --from=build /app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

As I want to deploy the app on Kubernetes, the following pod and service are defined:

apiVersion: v1
kind: Pod
metadata:
  name: playground-pod
  labels:
    name: playground-pod
    app: playground-app
spec:
  containers:
  - name: playground
    image: localhost:5000/playground:1.0
    ports:
    - containerPort: 80
    env:
    - name: REACT_APP_ENV_VARIABLE
      value: "Variable from Kube!"
    - name: REACT_APP_ENV_VARIABLE_TWO
      value: "192.168.0.120"
apiVersion: v1
kind: Service
metadata:
  name: playground-service
  labels:
    name: playground-service
    app: playground-app
spec:
  type: NodePort
  ports:
  - port: 80
    targetPort: 80
    nodePort: 30003
    protocol: TCP
  selector:
    name: playground-pod
    app: playground-app

After successful creation of the pod and the service, the variables in the pod container look this way:

/ # printenv | grep REACT_APP
REACT_APP_ENV_VARIABLE=Variable from Kube!
REACT_APP_ENV_VARIABLE_TWO=192.168.0.120

Yet, when I display the page in the browser, I can see something like this:

ENV1: It works!

ENV2:

Hash: 3Wzc3mgdlIFwc4

So, as you see, the local variable is displayed as expected, the variable that was intended to be overwritten is not overwritten and keeps the value from the Dockerfile, and the second variable that was only present in pod definition is not displayed at all.

Why is that? What should I do to make it work as expected?

-- AbreQueVoy
docker
kubernetes
reactjs

0 Answers