Nginx cannot find static react app files when being exposed on kubernetes ingress

6/15/2021

I am trying to deploy my react app to a kubernetes cluster by serving it via an nginx server. As you can see in the below Dockerfile I am building my app and afterwards copying the build artefacts into the /usr/share/nginx/html/ path on my nginx server.

# Stage 1 - build container
FROM node:12-alpine as build
WORKDIR /app
ENV PATH /app/node_modules/.bin:$PATH
COPY yarn.lock ./
COPY package.json ./
RUN yarn install
COPY . ./
ENV GENERATE_SOURCEMAP=false SASS_PATH=node_modules:src
ARG env
RUN yarn run build:${env}

# Stage 2 - productive environment
FROM nginx:stable-alpine
COPY --from=build /app/build /usr/share/nginx/html/
COPY nginx.conf /etc/nginx/conf.d/default.conf
RUN apk update	
RUN apk upgrade 
EXPOSE 80
CMD ["nginx","-g","daemon off;"]

I am using the following nginx configuration. From what I understand this should instruct the nginx server to search for resources using the specified root path.

server {
  listen 80;
  root   /usr/share/nginx/html;
  error_page   500 502 503 504  /50x.html;

  location / {
    index  index.html index.htm;
    try_files $uri $uri/ /index.html;
  }
}

I can see that this works when running the docker container locally (all react app resources get loaded), but when I deploy it onto my kubernetes cluster and expose it via an ingress controller, I am getting the following errors for the build artifacts:

GET https://*host*/static/css/main.0e41ac5f.chunk.css net::ERR_ABORTED 404

This is interesting since when I ssh into the container I can see that all the requested files still exist at the correct directory (/usr/share/nginx/html/static/).

I already tried setting the homepage value in my package.json to ".", but this didn't change anything.

My ingress configuration looks like this:

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: search-dev
  annotations:
    kubernetes.io/ingress.class: "public-iks-k8s-nginx"
spec:
  tls:
    hosts:
      - host
    secretName: secret
  rules:
  - host: host
      http:
        paths:
        - path: /
          pathType: Exact
          backend:
            service:
              name: search-frontend-dev
              port:
                number: 80

I also tried setting this annotation:

nginx.ingress.kubernetes.io/rewrite-target: /

But unfortunately this didn't work either.

Would appreciate some help with this.

-- mike
kubernetes
kubernetes-ingress
nginx
reactjs

1 Answer

6/16/2021

For all of you who are having a similar problem, set pathType to Prefix. Otherwise only requests to "/" will get routed to your service. Requests to "/static/..." were simply not routed to the services and therefore to my nginx server.

-- mike
Source: StackOverflow