Deploying and exposing an nginx server in kubernetes

In this post we’re going to create the configuration for a deployment, service and ingress controller to access an nginx instance to our network. I’ve picked nginx simply to demonstrate the process of these steps and obviously, out of the box, we get a webpage to view to know whether everything work – feel free to can change the image used to something else for your own uses.

Deployment

Below is the deployment configuration for k8s, creating a deployment named my-nginx. This will generate 2 replicas and expose the image on port 80 of the container.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx
spec:
  selector:
    matchLabels:
      run: my-nginx
  replicas: 2
  template:
    metadata:
      labels:
        run: my-nginx
    spec:
      containers:
      - name: my-nginx
        image: nginx
        ports:
        - containerPort: 80

Service

Now we’ll create the configuration for the my-nginx service

apiVersion: v1
kind: Service
metadata:
  name: my-nginx
  labels:
    run: my-nginx
spec:
  ports:
  - port: 80
    protocol: TCP
  selector:
    run: my-nginx

Ingress

We’re going to use Ingress to expose our service to the network, alternatively we could use a load balancer, but this options requires an external load balancer, so more like used on the cloud, or we could use NodePort which allows us to assigna port to a service so that any request to the port is forwarded to the node – the main problem with this is the port may change, instead Ingress acts like a load balancer within our cluster and will allow us to configure things to route port 80 calls through to our my-nginx service as if it was running outside of k8s.

We’re going to need to enable ingress within k8s. As we’re using Ubuntu and microk8s, run the following

microk8s enable ingress

The following is the configuration for this ingress.

apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: http-ingress
spec:
  rules:
  - http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: my-nginx
            port: 
              number: 80

Running and testing

Now we need to apply the configuration to our kubernetes instance, so I’ve saved all the previously defined configuration sections into a single file named my-nginx.yaml. Now just run the following to run the configuration in k8s

kubectl apply -f my-nginx.yaml

If you like, you can check the endpoint(s) assigned within k8s using

kubectl get ep my-nginx

and then curl the one or more endpoints (in our example 2 endpoints). Or we can jump straight to the interesting bit and access your k8s host’s ip and if all worked, you’ll be directed to one of the replicates nginx instances and we should see the “Welcome to nginx!” page.