How can I limit a DNS name to be only resolved to services with a specific label in kubernetes?

146 Views Asked by At

I can resolve a DNS name on the internal kubernetes DNS with a value like: http://serviceNameExampleAbc.default.svc.cluster.local where serviceExampleAbc relates to the IP of the service by name serviceExampleAbc...

However, how can I instead only resolve this to the service IP only if it has a specific label to it?

For example http://serviceNameExampleAbc.servicesWithXyzLabelOnly.default.svc.cluster.local would only resolve to serviceNameExampleAbc's IP if it has a label defined for it like below:

apiVersion: v1
kind: Service
metadata:
  name: serviceNameExampleAbc
  labels:
    xyz: abcxyzexmaple
...

1

There are 1 best solutions below

2
Harsh Manvar On

You can use the K8s network polcies to block the traffic across the namespace or services.

So with network policy, you will be able to restrict the traffic across the namespaces, PODs based on the labels, selectors etc.

With network policy service will be able to resolve the IP in DNS but the Network policy won't allow further to connect to end service.

Example

Allow traffic from some PODs in another namespace

kind: NetworkPolicy
apiVersion: networking.k8s.io/v1
metadata:
  name: web-allow-all-ns-db
spec:
  podSelector:
    matchLabels:
      app: web
  ingress:
    - from:
      - namespaceSelector:     #All pods in namespace with label app=db-ns
          matchLabels:
            team: operations  
        podSelector:           #Chooses pods with app=db
          matchLabels:
            app: db 

here is the list of policies you can refer : https://github.com/ahmetb/kubernetes-network-policy-recipes