Using nginx-ingress controller to restrict access by IP (ip whitelisting) for a service deployed to a Kubernetes (AKS) cluster


Create or update the nginx-ingress controller

$ helm install stable/nginx-ingress  --set controller.service.externalTrafficPolicy=Local

Create the the hello world web server deployment and service to test the whitelisting

$ kubectl run web --image=tutum/hello-world --port=80 
$ kubectl expose deployment web --port=80
$ kubectl get deployment webNAME      DESIRED   CURRENT   UP-TO-DATE   AVAILABLE   AGEweb       1         1         1            1           17m$ kubectl get svc webNAME      CLUSTER-IP    EXTERNAL-IP   PORT(S)   AGEweb       10.3.30.224   <none>        80/TCP    5m$ kubectl get pod -l=run=webNAME                   READY     STATUS    RESTARTS   AGEweb-5bff8ffd8c-twxwp   1/1       Running   0          17m

Apply the ingress IP Whitelisting rule for the service

apiVersion: extensions/v1beta1
kind: Ingress
metadata:
name: web-ingress
annotations:
ingress.kubernetes.io/whitelist-source-range: 49.36.X.X/32
spec:
rules:
- host: web.manitestdomain.com
http:
paths:
- path: /
backend:
serviceName: web
servicePort: 80
$ kubectl apply -f web-ingress-whitelist.yaml

Testing and Debugging the whitelisting rules

$ curl ipinfo.io/ip
49.36.X.X
$ curl -I web.manitestdomain.com
HTTP/1.1 200 OK
Server: nginx/1.13.5
Date: Sat, 19 May 2018 06:07:01 GMT
Content-Type: text/html; charset=UTF-8
Connection: keep-alive
X-Powered-By: PHP/5.6.14
$ curl ipinfo.io/ip223.Y.Y.Y$ curl -I web.manitestdomain.com
HTTP/1.1 403 Forbidden
Server: nginx/1.13.5
Date: Sat, 19 May 2018 06:15:47 GMT
Content-Type: text/html
Content-Length: 169
Connection: keep-alive
$ kubectl get pods
NAME READY STATUS RESTARTS AGE
nginx-ingress-nginx-ingress-controller-586c47b885-rxm72 1/1 Running 0 1d
nginx-ingress-nginx-ingress-default-backend-65f4cd97fb-sbh7c 1/1 Running 0 1d
web-5bff8ffd8c-twxwp
$ kubectl logs nginx-ingress-nginx-ingress-controller-586c47b885-rxm72 -f..
..
..
49.36.X.X - [49.36.X.X] - - [19/May/2018:06:11:21 +0000] "HEAD / HTTP/1.1" 200 0 "-" "curl/7.52.1" 87 0.002 [default-web-80] 10.2.1.7:80 0 0.002 200

Maninderjit (Mani) Bindra

Written by

Cloud, Containers, K8s, DevOps | CKA | Senior Software Engineer @ Microsoft

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade