Kubernetes override public DNS name
How can I rewrite some publicly resolvable foo.example.com to an in-cluster service?
kubectl run curl \
--stdin --tty --rm \
--image=radial/busyboxplus:curl
nslookup foo.example.com
As expected, it’s unable to resolve|curl:
Server: 10.152.183.10
Address 1: 10.152.183.10 kube-dns.kube-system.svc.cluster.local
nslookup: can't resolve 'foo.example.com'
curl http://foo.example.com:8080/healthy
curl: (6) Couldn't resolve host 'foo.example.com'
Exit the curl pod so that the DNS may be refreshed.
If the cluster uses [CoreDNS]:
kubectl get deployment \
--selector=k8s-app=kube-dns \
--namespace=kube-system \
--output=name
deployment.apps/coredns
Let’s create an in-cluster service to act as the target:
NAMESPACE="example"
kubectl create deployment kuard \
--image=gcr.io/kuar-demo/kuard-amd64:blue \
--port=8080 \
--namespace=${NAMESPACE}
kubectl expose deployment/kuard \
--name=foo \
--port=8080 \
--target-port=8080 \
--namespace=${NAMESPACE}
Recreate the curl Pod and then it should now resolve the cluster Service DNS name:
nslookup foo.example.com
nslookup foo.example.svc.cluster.local
Server: 10.152.183.10
Address 1: 10.152.183.10 kube-dns.kube-system.svc.cluster.local
Name: foo.example.svc.cluster.local
Address 1: 10.152.183.137 foo.example.svc.cluster.local
And we can curl the service’s endpoint:
curl http://foo.example.com:8080/healthy
ok
Let’s add a rewrite rule to CoreDNS (foo.example.com → foo.example.svc.cluster.local):
KUBE_EDITOR=nano \
kubectl edit configmap/coredns \
--namespace=kube-system
NOTE It would be better to patch the
corednsConfigMap but the CoreDNS config format isn’t JSON|YAML making this more difficult:kubectl get configmap/coredns \ --namespace=kube-system \ --output=jsonpath=".data.Corefile"`
rewrite name exact foo.example.com foo.example.svc.cluster.local
And you’ll need to recreate the Pod for it to be programmed with the updated CoreDNS config:
nslookup foo.example.com
Server: 10.152.183.10
Address 1: 10.152.183.10 kube-dns.kube-system.svc.cluster.local
Name: foo.example.com
Address 1: 10.152.183.137 foo.79523386.svc.cluster.local
curl http://foo.example.com:8080/healthy
ok
Now, in-cluster requests to foo.example.com are redirected to the in-cluster service.