Wednesday, June 10, 2020

Create k8s load balancer with nginx backend

 
Use the following yaml file to create a load balancer service on k8s. This load
balancer service will be backed by the deployment which only consists replicate
set with 2 containers using nginx.
 
 
---
apiVersion: v1
kind: Service
metadata:
  name: my-service8080
spec:
  selector:
    app: my-nginx
  ports:
    - port: 8080
      targetPort: 80
  type: LoadBalancer
---
apiVersion: apps/v1
kind: Deployment
metadata:
  name: my-nginx
spec:
  selector:
    matchLabels:
      app: my-nginx
  replicas: 2
  template:
    metadata:
      labels:
        app: my-nginx
    spec:
      containers:
      - name: my-nginx
        image: nginx
        ports:
        - containerPort: 80

The above picked a port 8080 to access the service, the application actually runs on port 80. In many
other applications, the port may be other numbers but the service port can be always specified to maintain a consistent endpoint for other applications.

Once the service and the deployment were created successfully, you can use the following methods to get url to hit the service.

*
   kubectl get svc my-service8080

The above should return information which contains external-ip with ports, the combination of the two will make up the url to hit the service.

**
   kubectl get svc my-service8080 -o yaml

This will return a yaml file, showing port and the hostname which will also make up the url to hit the service.

No comments:

Post a Comment