Deploying to Kubernetes with Gitlab
This is a step-by-step instruction on how to automate deployment to your Kubernetes cluster with CI/CD pipelines on Gitlab. Another great article on this topic is available here. The full source code is located here.
Prepare an image
In this example, we will deploy a static page served by Nginx.
- Create
html
folder with andindex.html
file with the content of your preference. - Create
Dockerfile
FROM nginx
COPY html /usr/share/nginx/html
- Test your image
docker build -t my-nx .
docker run --rm -p 8080:80 my-nx
Then go to http://localhost:8080/
in your browser.
Create .gitlab-ci.yml file
stages:
- build
- deploybuild-docker:
image: docker:latest
stage: build
services:
- docker:dind
variables:
CONTAINER_IMAGE: ${DOCKER_REGISTRY_USER}/my-nx:${CI_COMMIT_SHORT_SHA}
before_script:
- docker login -u "$DOCKER_REGISTRY_USER" -p "$DOCKER_REGISTRY_PASSWORD"
script:
- docker build -t ${CONTAINER_IMAGE} .
- docker tag ${CONTAINER_IMAGE} ${CONTAINER_IMAGE}
- docker push "${CONTAINER_IMAGE}"deploy:
stage: deploy
image: dtzar/helm-kubectl
script:
- kubectl config set-cluster k8s --server="${SERVER}"
- kubectl config set clusters.k8s.certificate-authority-data ${CERTIFICATE_AUTHORITY_DATA}
- kubectl config set-credentials gitlab --token="${USER_TOKEN}"
- kubectl config set-context default --cluster=k8s --user=gitlab
- kubectl config use-context default
- sed -i "s/<VERSION>/${CI_COMMIT_SHORT_SHA}/g" deployment.yaml
- kubectl apply -f deployment.yaml
Add gitlab service account to k8s cluster
Run the following config file gitlab-service-account.yaml
apiVersion: v1kind: ServiceAccount
metadata:
name: gitlab-service-account
---apiVersion: rbac.authorization.k8s.io/v1beta1kind: ClusterRoleBinding
metadata:
name: gitlab-service-account-role-binding
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: cluster-admin
subjects:
- kind: ServiceAccount
name: gitlab-service-account
namespace: default
kubectl apply -f gitlab-service-account.yaml
Set Settings/CI/CD/Variables
- DOCKER_REGISTRY_USER — username in docker registry/dockerhub
- DOCKER_REGISTRY_PASSWORD — docker registry password
- SERVER — k8s API endpoint URL, can be found in
~/.kube/config
- CERTIFICATE_AUTHORITY_DATA — found in
~./kube/config
undercertificate-authority-data
section - USER_TOKEN — can be obtained using the command
kubectl describe secret gitlab-service-account-token-*
Now you can run the pipeline, it should build and push docker image and run the deployment to the k8s cluster.