Rajshri Mohan K S
Rajshri Mohan K S

Reputation: 1759

How do I restrict connections to a service to a list of pods in Kubernetes?

I have a namespace with three pods (deployments) app01, app02, and db. db is exposed within the cluster via a ClusterIP service with name dbsvc. I connect to the service from app01 and app02 using the cluster DNS like dbsvc.namespace.svc.cluster.local. However, I do not want anyone to access dbsvc from outside my namespace. (Since it's ClusterIP, it's not going to be accessible outside the cluster anyways).

In other words, I want to restrict access to dbsvc.namespace.svc.cluster.local only from app01 and app02.

How do I achieve this?

Upvotes: 1

Views: 194

Answers (1)

Matt
Matt

Reputation: 74881

Network traffic can be restricted with a Network Policy on a cluster using a network plugin (CNI) that supports them, like calico.

The policy selectors are deployment specific so here are some example values:

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: app-network-policy
  namespace: namespace
spec:
  podSelector:
    matchLabels:
      role: db
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector:
        matchLabels:
          project: myproject
    - podSelector:
        matchLabels:
          role: app
    ports:
    - protocol: TCP
      port: 3306

Upvotes: 3

Related Questions