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?
3
Answers
If you deploy a ingress-nginx controller, it will create a default ConfigMap with the name of your ingress controller. This is the one you want to modify.
There would be something like this:
The config of
log-format-upstream
in thedata
should be added:Note using
$upstream_addr
that would be the IP address of pod.Another example would be:
But if you want your ingress controller to log the pod name by
X-My-Pod-Name
value, you can set this HEADER in your service. Like for example having the manifest of service updated to have env var:then for example in python, something like:
and finally you can show it in logs by
$http_x_my_pod_name
:Yes, you can achieve this by using annotation and snippet.
$HOSTNAME
will contain the pod name.Yes, custom HTTP headers can be added to requests handled by the NGINX Ingress Controller via annotations. To include a custom header, add the nginx.ingress.kubernetes.io/configuration-snippet annotation.
Here’s how you can accomplish it:
apiVersion: networking.k8s.io/v1 kind: Ingress metadata: name: my-ingress annotations: nginx.ingress.kubernetes.io/configuration-snippet: | more_set_headers "X-Pod: $pod_name"; spec: rules: – host: myapp.example.com http: paths: – path: / pathType: Prefix backend: service: name: my-service port: number: 80
Ensure the pod’s name is easily accessible. You can utilize the NGINX variable $pod_name, which represents the name of the pod that is handling the request. However, in order to use this variable, make sure that your NGINX Ingress Controller is set to provide pod information.
Deploy the Ingress. Apply the YAML configuration to your cluster: bash
kubectl apply -f your-ingress-file.yaml
Check the requests. After implementing the setup, when requests pass through the Ingress, the X-Pod header is included in the requests forwarded to your service. You can review your application’s logs to see which pod is handling the requests.
This allows you to easily identify which pod is delivering a specific request based on the X-Pod header in the logs.
Refer to the Kubernetes Community Forums for more information.