dynamic ingress to Kubernetes services with nginx proxy

11/11/2019

i am trying to make a dynamic proxy_pass with nginx, doing something like that:

  • Requests to foo.mywebsite.com are forwarded to service with foo name
  • Requests to bar.mywebsite.com are forwarded to service with bar name

my nginx.conf works with static values, but with regex, works for about 5 minutes and then errors start

apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config-dns-file
data:
  nginx.conf: |
    server {
      listen 80;
      server_name ~^(?<subdomain>.*?)\.;
      resolver kube-dns.kube-system.svc.cluster.local valid=5s;

      location /healthz {
        return 200;
      }

      location / {
        proxy_pass http://$subdomain.default.svc.cluster.local; 
      }
    }

my pod gets the service ip instead of the name, here are the logs

2019/11/11 22:30:40 [error] 6#6: 163 10.default.svc.cluster.local could not be resolved (3: Host not found), client: 10.142.0.34, server: ~^(?.?)., request: "GET / HTTP/1.1", host: "10.142.0.34"

10. is the beginning of ip to the point. I don't know what is going wrong, can anyone help me with this, thank you!!

-- Bruno Luis
kubernetes
kubernetes-ingress
nginx
nginx-ingress

1 Answer

11/14/2019

FIX WITH THIS

apiVersion: v1
kind: ConfigMap
metadata:
  name: nginx-config-dns-file
data:
  nginx.conf: |
    server {
      listen 80;
      server_name ~^(?<subdomain>.*?)\.;
      resolver kube-dns.kube-system.svc.cluster.local valid=5s;

      location /healthz {
        return 200;
      }

      location / {
        proxy_set_header Host $host
        proxy_pass http://$subdomain.default.svc.cluster.local; 
      }
    }
-- Bruno Luis
Source: StackOverflow