AKS 中的 React 获取 CSS 和 JS 文件的 MIME 错误

React in AKS gets MIME error for CSS and JS files

我在 Kubernetes 中有一个 React 应用程序,我正试图将其迁移到 Azure。应该足够直截了当,人们会想。根据 this 设置证书和入口后,我有一个暴露 React 部署的 ClusterIP。在 React pod 中,我使用 Nginx 来托管静态构建,请参阅下面的文件。 当我尝试访问主机时,页面空白并出现以下错误。

The stylesheet XXXXX/static/css/2.743d7424.chunk.css was not loaded because its MIME type, “text/html”, is not “text/css”. 
The stylesheet XXXXX/static/css/main.44331b01.chunk.css was not loaded because its MIME type, “text/html”, is not “text/css”.

我首先检查的是图像,它在本地运行良好。我检查的第二件事是在没有入口或 TLS 的情况下将 pod 连接到 public 负载平衡器,也工作正常。 因此,问题必须出在我的 Ingress 或管理证书的 Nginx 控制器上。

我不是唯一遇到此问题的人,但问题仍然悬而未决,解决方案不起作用。 https://github.com/kubernetes/ingress-nginx/issues/5265

设置:

入口 yaml

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: basic-ingress
  annotations:
    kubernetes.io/ingress.class: nginx
    cert-manager.io/cluster-issuer: letsencrypt-prod
    nginx.ingress.kubernetes.io/rewrite-target: /
    # FrontendConfig: redirect-config
    kubernetes.io/ingress.allow-http: "true"
spec:
  tls:
  - hosts:
    - mydomain.com
    secretName: tls-secret
  rules:
  - host: mydomain.com
    http:
      paths:
      - path: /*
        pathType: Prefix
        backend:
          service:
            name: react-app
            port:
              number: 80

Docker 文件

FROM node:16-alpine as builder
WORKDIR /usr/src/frontend
COPY package.json package-lock.json /usr/src/frontend/
RUN apk add git && npm ci
COPY . .
RUN npm run build

# NGINX build
FROM nginx:1.20.2-alpine
RUN rm /etc/nginx/conf.d/default.conf
COPY default.conf /etc/nginx/conf.d/default.conf
COPY --from=builder /usr/src/frontend/build/ /usr/share/nginx/html
CMD ["nginx", "-g", "daemon off;"]

Default.conf

server {
    listen 80;
    server_name platform.amplo.ch;
    server_tokens off;
    
    location / {
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        try_files $uri $uri/ /index.html;
    }
}

所以 Github 问题确实揭示了解决方案。问题出在重写目标的路径 and/or 上。感谢@az-iddouch。

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
    - http:
        paths:
          - path: /?(.*)
            backend:
              serviceName: client-cluster-ip-service
              servicePort: 3000
          - path: /api/?(.*)
            backend:
              serviceName: server-cluster-ip-service
              servicePort: 5000