Skip to content

Instantly share code, notes, and snippets.

@benjaminknox
Last active December 8, 2023 15:48
Show Gist options
  • Save benjaminknox/36130a3686f811a504ce93726f414aaf to your computer and use it in GitHub Desktop.
Save benjaminknox/36130a3686f811a504ce93726f414aaf to your computer and use it in GitHub Desktop.
Create a load balancer with minikube

Minikube LoadBalancers

This is a guide for creating minikube in a kubernetes cluster, based on this guide: Minikube LoadBalancer Docs

I always prefer having everything locally set up and working as closely to production as possible, it helps debug and ensures that if anything goes wrong in production it is reproducible locally. On minikube you can expose your k8s containers with a LoadBalancer on local ip addresses, accessing them just like you normally would your clusters running on your cloud provider. In this guide we will start the LoadBalancer in minikube and make a deployment that has an apache web host to demonstrate a local LoadBalancer configuration.

The first step is to run this command in your terminal:

$ minikube tunnel

This will create a network route on your computer using minikube tunnel, enabling external access to services in your kubernetes cluster through the cluster's ip address as a gateway. The terminal window you run this in must remain open in order for you to access your cluster. That's all we need for networking, minikube handles assigning ip addresses for access.

Once you have started the minikube tunnel, you can create services for your deployments. For example, the command below deploys an apache web service, run this first and then we will create a service that will expose the deployment with the LoadBalancer:

$ kubectl apply -f - <<EOF
apiVersion: apps/v1
kind: Deployment
metadata:
  name: apache
  labels:
    app: apache
spec:
  replicas: 1
  selector:
    matchLabels:
      app: apache
  template:
    metadata:
      labels:
        app: apache
    spec:
      containers:
      - name: apache
        image: httpd
        ports:
        - containerPort: 80
EOF

Any deployment in your cluster can be exposed on the LoadBalancer through a kubernetes service configuration, the next command creates a service that allows access to your apacher container:

$ kubectl apply -f - <<EOF
apiVersion: v1
kind: Service
metadata:
  name: apache-service
spec:
  selector:
    app: apache
  type: LoadBalancer
  ports:
  - protocol: TCP
    port: 8082
    targetPort: 80
EOF

And now you should be able to go to access the apache web service at this address: http://localhost:8082

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment