Search code examples
kubernetestraefiktraefik-ingress

How to enable CORS in Kubernetes with Traefik


I am trying to enable CORS on ingress in kubernetes running traefik. So that in the response header I could add CORS origin to be allowed to every host for now. How can I do that? Below is the k8 ingress.yml file.

apiVersion: networking.k8s.io/v1beta1
kind: Ingress
metadata:
  name: test-ingress
  namespace: test
  labels:
    app: test-cors-app
  annotations:
    kubernetes.io/ingress.class: traefik
spec:
  rules:
  - host: company.host
    http:
      paths:
      - path: /
        backend:
          serviceName: test-service
          servicePort: 80

UPDATE I have traefik 1.7


Solution

  • You can use this annotation in your ingress : traefik.ingress.kubernetes.io/custom-response-headers or ingress.kubernetes.io/custom-response-headers both will work with traefik.

    Modify your ingress.yml file as :

    apiVersion: networking.k8s.io/v1beta1
    kind: Ingress
    metadata:
      name: test-ingress
      namespace: test
      labels:
        app: test-cors-app
      annotations:
        kubernetes.io/ingress.class: traefik
        traefik.ingress.kubernetes.io/custom-response-headers: "Access-Control-Allow-Origin:*||Access-Control-Allow-Methods:GET,POST,OPTIONS||Access-Control-Allow-Headers:DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range||Access-Control-Expose-Headers:Content-Length,Content-Range"
    spec:
      rules:
      - host: company.host
        http:
          paths:
          - path: /
            backend:
              serviceName: test-service
              servicePort: 80
    

    **Modify annotation attributes accrodingly. It works for traefik lower versions as well. see here