Restrict access to service to only some pods

8/3/2021

I have a mosquitto broker running on a pod, this server is exposed as a service as both DNS and IP address.

But this service is accessible by any pod in the cluster.

I want to restrict access to this service such that pods trying to connect to this DNS or IP address should only be able to if the pods have certain name/metadata.

One solution I guess will be to use namespaces? What other solution is there?

-- The Entity
kube-proxy
kubernetes
kubernetes-ingress
kubernetes-pod

1 Answer

8/3/2021

The UseCase you are describing is exactly what NetworkPolicies are here for.

Basically you define selector for pods which the network traffic should be restricted (i.e. your mosquito broker) and what specifica pods need to have in order to be allowed to reach it. For example a label "broker-access: true" or whatever seems to be suitable for you.

an example network policy could look like this:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: broker-policy
  namespace: default  
spec:
  podSelector:
    matchLabels:
      role: message-broker
  policyTypes:
  - Ingress
  ingress:
  - from:
    - podSelector:
        matchLabels:
          broker-access: true
    ports:
    - protocol: TCP
      port: 6379

this network policy would be applied to every pod with label role=message-broker. and it would restrict all incoming traffic except for traffic from pods with label broker-acces=true on port 6379.

Hope this helps and gives you a bit of a skaffold for your NetworkPolicy

-- meaningqo
Source: StackOverflow