【问题标题】:Setting cache-control headers for nginx ingress controller on kubernetes GKE在 kubernetes GKE 上为 nginx 入口控制器设置缓存控制标头
【发布时间】:2019-03-13 15:26:59
【问题描述】:

我有一个 ingress-nginx 控制器来处理我在 GKE 上托管的 Kubernetes 集群的流量。我使用文档中的 helm 安装说明进行了设置:

Docs here

在大多数情况下,一切正常,但如果我尝试通过 server-snippet 注释设置缓存相关参数,则所有应获取缓存控制标头的服务内容都会以 404 的形式返回。

这是我的ingress-service.yaml 文件:

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
  name: ingress-service
  annotations:
    kubernetes.io/ingress.class: nginx
    nginx.ingress.kubernetes.io/proxy-read-timeout: "4000"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "4000"
    nginx.ingress.kubernetes.io/server-snippet: |
      location ~* \.(js|css|gif|jpe?g|png)$ {
        expires 1M;
        add_header Cache-Control "public";
      }
spec:
  tls:
    - hosts:
        - example.com
      secretName: example-com
  rules:
    - host: example.com
      http:
       paths:
        - path: /
          backend:
            serviceName: client-cluster-ip-service
            servicePort: 5000
        - path: /api/
          backend:
            serviceName: server-cluster-ip-service
            servicePort: 4000

同样,只有与正则表达式匹配的资源才会以404 的形式返回(所有.js 文件、.css 文件等)。

对为什么会发生这种情况有任何想法吗?

感谢任何帮助!

【问题讨论】:

    标签: nginx kubernetes kubernetes-ingress google-kubernetes-engine nginx-ingress


    【解决方案1】:

    那些location 块是last and/or longest match wins,并且由于入口本身 不提供任何此类内容,nginx 依赖于指向上游服务器的proxy_pass directive。因此,如果您得到 404,很可能是因为 您的 location 匹配,从而干扰了 proxy_pass 之一。很有可能您实际上想要 configuration-snippet: 代替,可能与 if ($request_uri ~* ...) { 结合来添加标题。

    你可以在本地尝试这个,用一个简单的 nginx.conf 指向 python3 -m http.server 9090 或任何虚假的上游目标。

    另外,为了调试 nginx 入口问题,查阅其实际的 nginx.conf (可以从任何入口 Pod 中获取)和/或查阅入口 Pod 的日志通常是非常宝贵的,其中 nginx 将发出有用的信息调试文本。

    【讨论】:

    • 非常感谢您的回复。 configuration-snippet 方法效果很好。
    • 另外,我确实在相关 pod 上的 nginx.conf 文件中达到了峰值,但它超过 1300 行,而且我是 nginx 菜鸟 :) 你的洞察力让我变得更聪明了。
    • 对我来说,它不能与 configuration-sn-p 一起使用。我像这样添加nginx.ingress.kubernetes.io/configuration-snippet: | if ($uri ~ '/app/.*') { add_header Cache-Control "max-age=60"; ,但结果是cache-control: public, max-age=0
    • (a) 请不要使用 cmets 部分提问,请发布您自己的问题; (b) 当您将来提出自己的问题时,您需要确保特别注意 MCVE 部分,该部分表明您将其添加到一个 Ingress,孤立地,它没有做什么您说,与您的设置中可能干扰您的假设的所有其他促成因素相比。祝你好运
    【解决方案2】:

    configuration-sn-p 将与 nginx 入口一起工作

    你可以使用类似的东西

    nginx.ingress.kubernetes.io/configuration-snippet : |
          if ($request_uri ~* \.(js|css|gif|jpe?g|png)) {
            expires 1M;
            add_header Cache-Control "public";
          }
    

    【讨论】:

    • 对我来说,它不能与 configuration-sn-p 一起使用。我像这样添加nginx.ingress.kubernetes.io/configuration-snippet: | if ($uri ~ '/app/.*') { add_header Cache-Control "max-age=60"; ,但结果是cache-control: public, max-age=0
    • @BibekMantree 我面临同样的问题。你有解决办法吗?
    猜你喜欢
    • 1970-01-01
    • 2021-09-27
    • 1970-01-01
    • 2018-10-29
    • 2011-10-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-10
    • 1970-01-01
    相关资源
    最近更新 更多