본문 바로가기
Kubernetes

Kubernetes Networkpolicy로 Pod간 트래픽 제어하기

by beann 2024. 3. 31.

NetworkPolicy는 어느한쪽 종단 Pod인 경우에만 적용되는 네트워크트래픽제어 Kubernetes Resource중 하나이다.

Type에는 Ingress, Egress가 있으며 아래와 같은 정책을 적용할 수 있다.

- 허용되는 다른 Pod(자기 자신 Pod를 제어할 수는 없음)

- Namespace

- IP Block

Pod, Namespace는 Selector / Label설정을 통해 지정할 수 있으며, IP Block은 말그대로 IP에 대한 Ingress, Egress를 통제할 수 있다.

 

참고로 NetworkPolicy는 CNI가 구성되어 있어야하며, CNI가 없다면 NetworkPolicy가 적용되지 않는다.

 

 

 

NetworkPolicy적용


 

시나리오: sj-pod(namespace: be-ns)로 접근 가능한 Pod는 아래 조건에 부합해야함

- labels: app=db를 가진 Pod & any네임스페이스에서 접근 가능.

- Namespace: ns=fe-ns

 

 

Pod 생성 및 IP주소 확인

root@k8s-m:~# k create ns fe-ns
root@k8s-m:~# k create ns be-ns

root@k8s-m:~# k run sj-pod --image=nginx --namespace=be-ns --labels=app=test

root@k8s-m:~# k get pod -n be-ns -o wide 
NAME     READY   STATUS    RESTARTS   AGE   IP                NODE    NOMINATED NODE   READINESS GATES
sj-pod   1/1     Running   0          28s   192.168.218.112   k8s-w   <none>           <none>

root@k8s-m:# k get pod -n be-ns sj-pod --show-labels
NAME     READY   STATUS    RESTARTS   AGE   LABELS
sj-pod   1/1     Running   0          17s   app=test

 

 

 

NetworkPolicy 작성

apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
  name: test-np
  namespace: be-ns
spec:
  policyTypes:
  - Ingress
  ingress:
  - from:
    - namespaceSelector: {} # 모든namespace & app=db 라벨을 가진 모든 Pod의 접근
      podSelector:
        matchLabels:
          app: db
    - namespaceSelector: # fe-ns네임스페이스에서의 모든 접근
        matchLabels:
          role: front-end
  podSelector:
    matchLabels:
      app: test # sj-pod의 라벨
      
 root@k8s-m:~# k apply -f teset-np

 

 

 

default namespace에 테스트용 pod를 만들어 be-ns에 있는 sj-pod에 접근 시도

# app=db라벨을 적용한 default네임스페이스의 Pod는 접근 가능 확인
root@k8s-m:~# k run test-pod -it --rm --image=nginx --labels=app=db -- /bin/bash
If you don't see a command prompt, try pressing enter.
root@test-pod:/# curl 192.168.218.112
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
...
...

# app=db라벨이 없는 dfault 네임스페이스의 Pod는 접근 불가 확인
root@k8s-m:~# k run test-pod2 -it --rm --image=nginx -- /bin/bash
If you don't see a command prompt, try pressing enter.
root@test-pod2:/# curl 192.168.218.112
^C

 

 

 

 

Namespace: ns=fe-ns에서도 접근 가능한지 확인

# fe-ns에서도 접근 가능한것 확인
root@k8s-m:~# k run test-pod3 -it --rm --image=nginx --namespace=fe-ns -- /bin/bash
If you don't see a command prompt, try pressing enter.

root@test-pod3:/# curl 192.168.218.112
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;