How to serve static contents in a kubernetes application

asw*_*kar 9 nginx docker kubernetes microservices kubernetes-ingress

I have a small java webapp comprising of three microservices - api-service,book-service and db-service all of which are deployed on a kubernetes cluster locally using minikube.

I am planning to keep separate UIs for api-service and book-service , with the common static files served from a separate pod, probably an nginx:alpine image.

I was able to create a front end that serves the static files from nginx:alpine referring to this tutorial.

I would like to use ingress-nginx controller for routing requests to the two services.

The below diagram crudely shows where I am now.

I am confused as to where I should place the pod that serves the static content, and how to connect it to the ingress resource.I guess that keeping a front end pod before ingress defeats the purpose of ingress-nginx controller. What is the best practice to serve static files. Appreciate any help. Thanks.

在此处输入图片说明

Clo*_*hel 9

看起来您混淆了这样一个事实,即用户在线浏览将触发标准请求以“下载”您的静态内容使用您的 2 个 API(书籍和 API)。不是 NGINX 服务为访问您的 API 的静态内容提供服务,而是用户浏览器/应用程序,他们对静态内容和 API 执行的操作完全相同(前者具有更多/特定的标头和数据,例如身份验证... )。

在您的图表上,您需要将您的 newstatic-service放在与您的book-service和完全相同的级别api-service,即入口后面。但是你static-service不会db-service像其他 2 那样有链接。然后只需完成你的入口规则,最后是静态服务,如本例所示:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: your-global-ingress
  annotations:
    nginx.ingress.kubernetes.io/rewrite-target: /
spec:
  rules:
  - host: foo.bar.com
    http:
      paths:
      - path: /book-service
        backend:
          serviceName: book-service
          servicePort: 80
      - path: /api-service
        backend:
          serviceName: api-service
          servicePort: 80
      - path: /
        backend:
          serviceName: static-service
          servicePort: 80
Run Code Online (Sandbox Code Playgroud)

您必须调整您的服务名称和端口,并选择您希望用户访问您的 API 的路径,在上面的示例中,您将拥有:

  • foo.bar.com/book-service 为您的图书服务
  • foo.bar.com/api-service 对于 api 服务
  • foo.bar.com/ 即其他一切都进入静态服务