如何使用 Kubernetes Ingress 暴露 Flask App?

How to expose Flask App with Kubernetes Ingress?

我有一个名为 hwrequest 的简单 python flask 应用程序。我可以从 PyCharm IDE 运行 它工作正常。 我已经使用以下 Dockerfile

对这个应用程序进行了 docker 化
FROM python:3.8-alpine
LABEL maintainer="John Smith, john.smith@mycompany.com"
RUN apk update && apk add bash curl
COPY . /hwrequest
WORKDIR /hwrequest
RUN pip install -r app/requirements.txt
EXPOSE 5000
ENTRYPOINT ["python"]
CMD ["/hwrequest/app/app.py"]

我可以将它执行到容器中,当我成功调用时 curl 127.0.0.1:5000 现在我正在尝试将此应用程序部署到 Kubernetes 并使用 Ingress 公开它。

这是我的 YAML 文件:

apiVersion: apps/v1
kind: Deployment
metadata:
  labels:
    app: "hwrequest"
  name: "hwrequest"
spec:
  replicas: 1
  selector:
    matchLabels:
      app: "hwrequest"
  template:
    metadata:
      labels:
        app: "hwrequest"
    spec:
      containers:
      - name: "hwrequest"
        image: "myregistry.com/hwrequest:0.0.4"
        imagePullPolicy: Always
        ports:
        - containerPort: 5000
apiVersion: v1
kind: Service
metadata:
  name: "hwrequest"
  labels:
    app: "hwrequest"
spec:
  type: ClusterIP
  ports:
    - port: 5000
      targetPort: 5000
  selector:
    app: "hwrequest"
apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: "hwrequest"
spec:
  rules:
  - http:
      paths:
      - backend:
          serviceName: "hwrequest"
          servicePort: 5000
    host: "hwrequest.mycompany.com"

当我调用 curl hwrequest.mycompany.com 时,我得到 502 Bad Gateway

我做错了什么?

使用入口在 kubernetes 上公开任何应用程序是一项非常重要的任务,这里有一些需要注意的事情

  1. 确保应用程序正在侦听 0.0.0.0 而不是 127.0.0.1
  2. curl 请求应该有 Host header 即 -H "Host: hwrequest.mycompany.com" 因为这是入口控制器如何根据入口资源中定义的规则知道应用哪个规则。
  3. 集群中需要一个入口控制器,例如 nginx 运行,并且入口控制器 pods 需要通过 NodePortLoadBalancer 类型公开服务或可以使用 hostNetwork: true
  4. 部署
  5. 如果使用 NodePort 服务,则需要在 curl 中使用 NODEIP(kubernetes 节点)和 NODEPORT,因此它看起来像 curl http://<NODEIP>:NODEPORT -H "Host: hwrequest.mycompany.com"

如果你使用 hostNetwork 公开 nginx 入口控制器 pods 那么 curl 应该是 curl http:// -H "Host: hwrequest.mycompany.com"`

如果您使用 LoadBalancer 类型的服务(适用于 AWS、Azure、GCP 等云提供商),则 curl 应该是 curl http:// -H "Host: hwrequest.mycompany.com"`

如果你刚刚开始,我建议你看看这个guide关于在 Minikube 上使用 nginx ingress