使用 kubernetes 卷时出现 Nginx 403 错误

Nginx 403 error while using kubernetes volumes

我正在尝试为 Nginx 使用 Kubernetes 卷,但遇到了问题。设置卷后,Nginx 无法提供 HTML 页面。我也尝试过PV和PVS这次也得到了同样的错误。

nginx.yml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels: 
    app: nginx 

spec: 
  replicas: 2
  selector: 
    matchLabels: 
      app: nginx
  template:
    metadata: 
      labels:
        app: nginx
    spec: 
      volumes:
        - name: nginxhtml
          # persistentVolumeClaim: 
          #   claimName: pvc
          hostPath:
            path: /home/amjed/Documents/SPS/k8s/mongo/mnt
      containers:
        - name: nginx
          image: nginx
          volumeMounts:
            - name: nginxhtml 
              mountPath: /usr/share/nginx/html
              
          ports: 
            - containerPort: 80



---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector: 
    app: nginx
  type: LoadBalancer
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80

  1. 将副本数减少到 1
  2. 验证 /home/amjed/Documents/SPS/k8s/mongo/mnt 位置是否有效并且可以从 pod 访问

首先,创建你想在 minikube 中挂载的文件夹:

dobrucki@minikube:~$ minikube ssh
Last login: Tue Jan 11 13:54:50 2022 from 192.168.49.1
docker@minikube:~$ ls -l 
total 4
drwxr-xr-x 2 docker docker 4096 Jan 11 13:56 nginx-mount

此文件夹映射到 Pods 内的 /usr/share/nginx/html,因此当您连接到您的服务时,将显示您粘贴到此处的文件。 确保您在该文件夹中有一些 .html 文件,否则您将收到 403 错误。对我来说,示例 index.html 是这样的:

<html>
 <head>
 </head>
 <body>
   <h1>Hello World<h1>
 </body>
</html>

您还需要在部署清单中添加 securityContext fsGroup,以便 /usr/share/nginx/html 归 nginx 用户 (101 uid) 所有。

然后,使用以下方法应用 Deployment 和 LoadBalancer 资源:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels: 
    app: nginx 
spec:
  replicas: 2
  selector: 
    matchLabels: 
      app: nginx
  template:
    metadata: 
      labels:
        app: nginx
    spec:
      securityContext:
        fsGroup: 101
      volumes:
        - name: nginxhtml
          hostPath:
            path: /home/docker/nginx-mount
      containers:
        - name: nginx
          image: nginx
          volumeMounts:
            - name: nginxhtml 
              mountPath: /usr/share/nginx/html       
          ports: 
            - containerPort: 80
---
apiVersion: v1
kind: Service
metadata:
  name: nginx-service
spec:
  selector: 
    app: nginx
  type: LoadBalancer
  ports:
    - protocol: TCP
      port: 80
      targetPort: 80

之后您可以检查内容是否正确提供

dobrucki@minikube:~$ curl $(minikube service nginx-service --url)
<html>
 <head>
 </head>
 <body>
   <h1>Hello World<h1>
 </body>
</html>

如果您有更多问题,请告诉我。