kubernetesnginx-ingress

How to add the pod name to HTTP response headers using Ingress NGINX Controller?


I have a deployment with multiple replica pods behind a service. Sometimes, I want to know which of these pods is serving a request, i.e. to view the logs when there is some strange behaviour. Is there a way to add an HTTP header like X-Pod: my-app-5954c566c7-48s97 to each request served by an ingress using the NGINX Ingress Controller, for example through annotations?


Solution

  • Update

    After enabling Ingress snippets in my MicroK8s cluster by adding allow-snippet-annotations: "true", I found that my original approach to setting headers via the ingress didn't work as expected. The closest result I achieved was retrieving the pod name for the Ingress controller, which is not the intended behavior.

    The short answer is: No, you can't get the individual pod's hostname via the Ingress controller. You need to set this header inside your application, as the Ingress controller doesn't have direct knowledge of individual pod details.

    Normally, the HOSTNAME environment variable is available inside all pods. You can verify it with:

    kubectl -n my-ns exec -it my-pod-name -- sh -c 'echo $HOSTNAME'
    

    Therefore, if you're using a framework like Node.js, you can set the X-Pod header directly in the application like this:

    Node.js example:

    const hostname = process.env.HOSTNAME
    
    app.get("/my-endpoint", (req, res) => {
        res.set("X-Pod", hostname)    
        ...
    })
    

    Old answer

    Yes, you can achieve this by using annotation and snippet. $HOSTNAME will contain the pod name.

    kind: Ingress
    metadata:
      name: some-ingress
      annotations:
        nginx.ingress.kubernetes.io/server-snippet: |
          proxy_set_header X-Pod $HOSTNAME;