How to write network policy files to allow traffic to access the application from only few IP address (eg: 127.18.12.1, 127.19.12.3 ). I have referred the file https://github.com/ahmetb/kubernetes-network-policy-recipes but didn't find satisfactory answer. It would be great if anyone help me to write the network-policy file. I also referred Kubernetes official document for network-policy.
My sample code
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: test-network-policy
namespace: example
spec:
podSelector:
matchLabels:
app: couchdb
policyTypes:
- Egress
egress:
- to:
- ipBlock:
cidr: 127.18.12.1/16
ports:
- protocol: TCP
port: 8080
If you donot want to edit networkpolicy and restrict traffic from ingress for particular domain you can edit ingress with annotation liked :
apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: restricted-ingress
annotations:
kubernetes.io/ingress.class: "nginx"
nginx.ingress.kubernetes.io/from-to-www-redirect: "True"
nginx.ingress.kubernetes.io/force-ssl-redirect: "True"
nginx.ingress.kubernetes.io/whitelist-source-range: "00.0.0.0, 142.12.85.524"
for network policy
apiVersion: networking.k8s.io/v1
kind: NetworkPolicy
metadata:
name: test-policy
namespace: default
spec:
podSelector:
matchLabels:
app: db
policyTypes:
- Ingress
- Egress
ingress:
- from:
- ipBlock:
cidr: 172.17.0.0/16
except:
- 172.17.1.0/24
- podSelector:
matchLabels:
role: frontend
ports:
- protocol: TCP
port: 6379
egress: - to: - ipBlock: cidr: 10.0.0.0/24 ports: - protocol: TCP port: 5978