쿠버네티스 공부 - Network Policy
Udemy CKA 강의를 기반으로 공부해본 내용을 정리합니다.
May 02, 2024
쿠버네티스에서 Network 정책을 수립할 수 있다.
방식은 네트워크 정책을 만든뒤 label을 통해서 연결한다.
Ingress 방식의 network 정책의 예는 아래와 같다.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: db-policy
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
ingress:
- from:
- podSelector:
matchLabels:
name: api-pod
ports:
- protocol: TCP
port: 3306
이러면 네트워크 정책이 생성된다.
Note
Flannel은 네트워크 정책을 지원하지 않는다.
178. Developing network policies
Ingress 와 Egress의 부연설명
DB Pod가 있다.
이때 Network 정책을 Ingress 3306 으로 수립하였다고 가정하자.
이때 DB pod는 API Pod와 통신한다.
Ingress 3306 이라는 정책 수립 시 API 서버로 부터 들어오는 3306 포트는 허용된다.
또한 응답(return) 패킷은 별도로 허용해주지 않아도 된다.

하지만 그렇다는것이 DB Pod가 API Pod로의 요청을 자유롭게 보낼 수 있다는 뜻이아니다.
DB Pod에서 API Pod로 요청을 보낼때는 당연히 Egress 정책을 사용한다.
이 두가지의 차이점을 명확히 이해해야 한다.
Namespace가 다르지만 Label이 동일하게 설정된 두 Pod가 있다면?
ingress.from.namespaceSelector.matchLabels.name
이라는 구문을 통해 네임스페이스의 Labels를 지정해주면된다. 물론 해당 네임스페이스에는 해당 레이블이 존재해야한다.쿠버네티스 환경이 아닌 특정 IP에서만 트래픽을 허용하도록 하는 방법
ingress.from.ipBlock.cidr: 192.168.5.0/24
--생략--
ingress:
- from:
- ipBlock:
cidr: 192.168.5.0/24
DB Pod가 타 외부서버로 DB Backup을 진행한다면?

- Egress 를 적용해야한다.
-- 생략 --
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Ingress
- Egress
ingress:
- from:
- podSelector:
matchLabels:
name: api-pod
ports:
- protocol: TCP
port: 3306
egress:
- to:
- ipBlock:
cidr: 192.168.5.0/24
ports:
- protocol: TCP
port: 80
179. Practice Test - Network Policy
문제에서 가장 까다로웠던 부분은 마지막 문제이다.
NetworkPolicy
를 생성하는데, 한 정책의 두개의 rule을 생성해야한다.-to
를 두번써서 진행하면 된다. 예시는 아래와 같다. -- 생략 --
spec:
podSelector:
matchLabels:
role: db
policyTypes:
- Egress
ingress:
- from:
- podSelector:
matchLabels:
name: api-pod
ports:
- protocol: TCP
port: 3306
egress:
- to:
- podSelector:
matchLabels:
name: payroll
ports:
- protocol: TCP
port: 8
- to:
- podSelector:
matchLabels:
name: payroll2
ports:
- protocol: TCP
port: 8
실제 답안 작성 시 작성했던 yaml 양식이다.
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: internal-policy
spec:
policyTypes:
- Egress
egress:
- to:
- podSelector:
matchLabels:
name: mysql
ports:
- protocol: TCP
port: 3306
- to:
- podSelector:
matchLabels:
name: payroll
ports:
- protocol: TCP
port: 8080
Share article