Using GitLab Runners with Docker or Kubernetes
local graph
Chapter 16 — Using GitLab Runners with Docker or Kubernetes
Section titled “Chapter 16 — Using GitLab Runners with Docker or Kubernetes”In the previous chapter, we installed a GitLab Runner with the shell executor. In this chapter, we will take a closer look at containerized GitLab Runners. You can run a GitLab Runner in a container in multiple ways:
- With the Shell executor running in a custom-built Docker container: This is not recommended because you are responsible for building and supporting this custom container afterward. On the other hand, if you want to tightly control the components inside the container and the behavior of them, then it might be a good way to containerize the Runner. Scaling this solution also requires more work from your side because the Runner itself only knows how to run jobs and connect to GitLab. You will collect state (files in /tmp or elsewhere) in your containers if they don’t restart after a job, so be prepared to handle that as well.
- With the Docker executor, which pulls and starts a Docker image for your job: This is a much more scalable solution, with the added bonus of having no state. Each build gets a pristine clean environment and starts all over again. Another bonus is that you are able to create services for a job, which is another container or several that are started in parallel with a container for your job. For instance, you can start a MySQL database and it will be a linked service that is available under the service name.
- With the Kubernetes executor so that you can use a Kubernetes cluster: The Runner can communicate with the cluster management API and ask for resources to spin up containers. The Runners are completely stateless and when there is a decreasing number of jobs in the queue, the number of containers is scaled back automatically.
- With the Docker executor and autoscaling enabled (Docker Machines creates new Runners): In this configuration, the GitLab Runner controls the Docker Machine binary. It can create new Runner containers on the fly and scale down again if there are less jobs in the queue.
In this chapter, we are going to take a look at the basic way of running a GitLab Runner, and how to orchestrate this using a management system such as Kubernetes. The autoscaling executors will be part of the next chapter. The reason for this is that the autoscaling Docker executor has a lot of options and requires more planning and system management features to maintain.
The following topics will be covered in this chapter:
- Runner client architecture
- Creating your own Dockerized GitLab Runner
- Using a prebuilt Docker container to deploy GitLab Runners
- Using a Kubernetes cluster to spawn GitLab Runners
To follow along with the instructions in this chapter, please download this book’s GitHub repository, along with the examples that are available, from GitHub at https://github.com/PacktPublishing/Mastering-GitLab-12/tree/master/Chapter16.
The other requirements for this chapter are as follows:
- Docker installed for your platform
- The wget command-line download tool (https://www.gnu.org/software/wget/)
- Access to the Alpine Docker image (https://hub.docker.com/_/alpine)
- Access to the Python Alpine Docker image (https://hub.docker.com/r/lgatica/python-alpine)
- Access to the GitLab Runner Docker image (https://hub.docker.com/r/gitlab/gitlab-runner)
- The kubectl utility on your system (you can find installation instructions at https://kubernetes.io/docs/tasks/tools/install-kubectl/)
- Helm or Tiller (a Kubernetes utility to help you to manage clusters: https://helm.sh/docs/using_helm/)
If you utilize a GitLab Runner with Docker, the resulting architecture differs from the one in the previous chapter in one way. The Runner binary is executed from inside a Docker container instead of directly on a host system. The following diagram shows this architecture:

The image is the same whether you create a container yourself or you use an existing container from the internet.
If you are going to orchestrate your GitLab Runners using Kubernetes, the architecture is going to look a bit different. You can see that, inside the cluster, a GitLab Runner with the Kubernetes architecture can talk to the cluster’s Kubernetes API to scale up the number of Runner instances:

The two architectures both use Docker containers as the core unit of operation. The first needs more management in the field of scaling, upgrading the software, and setting up a network. Much of that has already been arranged with Kubernetes.
Now, we know about the difference between these architectures and that a Runner is deployed without a container, but what does this mean in practice? We will explore this in the following sections.
Most people will use prebuilt Docker containers, but there are reasons to build your own. Maybe you have special requirements when building your software that aren’t installed in the default Docker images that are available or maybe it’s just not possible because of security restrictions. A lot of default images have software included that contain vulnerabilities.
Let’s create our own Dockerized GitLab Runner for the project from Chapter 10, Create Your Product, Verify, and Package it, that is, the event manager documentation, using a Dockerfile. You will find our first attempt in the next section.
Let me stress that this Dockerfile is purely for demonstration purposes. We don’t recommend building containers like this for production-like systems or even your own development systems. It’s being used here to show you how easily you can wrap commands and services in containers.
The first line of the file is as follows:
FROM alpine:3.7This is the base image we used for the container. It is from the Alpine Linux distribution, which contains only the bare minimum to run programs. It is only 4.41 MB and, when using container security scanners such as Clair (https://github.com/coreos/clair), it doesn’t show vulnerabilities. You can also build containers from scratch (see https://ericchiang.github.io/post/containers-from-scratch/), but this is a very tedious task. The Alpine Linux image is safe enough and is ready to go immediately.
In the following lines, we install some basic packages:
RUN apk add --no-cache \ ca-certificates \ git \ wgetWe need CA certificates because we need the GitLab Runner client to connect to our HTTPS endpoint, where a TLS handshake will take place. The Git binary is also necessary to clone code from a project.
Finally, the last command that is set to run in the creation sequence of the container is used to download, execute, and register the GitLab Runner with our GitLab server:
RUN wget https://s3.amazonaws.com/gitlab-runner-downloads/master/binaries/gitlab-runner-linux-386 && chmod +x gitlab-runner-linux-386 && \ ./gitlab-runner-linux-386 register \ --non-interactive \ --url "https://gitlab-ee.joustie.nl/" \ --registration-token "xxxxxxx" \ --executor "shell" \ --shell "sh" \ --description "dockerized shell-runner" \ --tag-list "docker" \ --run-untagged="true" \ --locked="false"For this example’s sake, we have hardcoded all of the arguments in the Dockerfile to show you how easy it is to Dockerize your command (don’t do this normally):
- non-interactive: Without it, there would be a dialog that takes you through the configuration settings.
- url: This is the URL of our GitLab server.
- registration-token: This is the token of a Runner from the project, group, or GitLab instance’s scope.
- executor: This specifies which kind of Runner to implement. We chose to use the shell executor.
- shell: This specifies which kind of shell to implement; this could be bash, sh, or powershell on Windows. We chose sh as it is the most basic one.
- description: This is what description you will see in GitLab.
- tag-list: We can put tags on Runners for easier management in GitLab. In this case, we have used docker.
- run-untagged: We set it to true, which means that any job with or without tags can be run on this Runner.
- locked: The Runner isn’t tied to a project.
The next step is to build the Docker container with the docker build command (we specify –no-cache so that we can rebuild every time). The output is as follows, and we will go through it step by step. The first part is pulling the Alpine base image:
$ docker build --no-cache -t dockerrunner . Sending build context to Docker daemon 2.56kB Step 1/4 : FROM alpine:3.9 3.9: Pulling from library/alpine Digest: sha256:769fddc7cc2f0a1c35abb2f91432e8beecf83916c421420e6a6da9f8975464b6 Status: Downloaded newer image for alpine:3.9 ---> 055936d39205The first Docker layer has been created. The second step is adding the necessary packages:
Step 2/4 : RUN apk add --no-cache ca-certificates git openssl tzdata wget ---> Running in 0ab19e2eef86 fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/main/x86_64/APKINDEX.tar.gz fetch http://dl-cdn.alpinelinux.org/alpine/v3.9/community/x86_64/APKINDEX.tar.gz (1/8) Installing ca-certificates (20190108-r0) (2/8) Installing nghttp2-libs (1.35.1-r0) (3/8) Installing libssh2 (1.8.2-r0) (4/8) Installing libcurl (7.64.0-r1) (5/8) Installing expat (2.2.6-r0) (6/8) Installing pcre2 (10.32-r1) (7/8) Installing git (2.20.1-r0) (8/8) Installing wget (1.20.3-r0) Executing busybox-1.29.3-r10.trigger Executing ca-certificates-20190108-r0.trigger OK: 21 MiB in 22 packages Removing intermediate container 0ab19e2eef86 ---> 17ab7c7dd1b9The previous code downloaded the packages we specified, as well as some dependencies. This is still a modest amount of packages. In the following build step, the GitLab Runner binary is downloaded:
Step 3/4 : RUN wget https://s3.amazonaws.com/gitlab-runner-downloads/master/binaries/gitlab-runner-linux-386 && chmod +x gitlab-runner-linux-386 && ./gitlab-runner-linux-386 register --non-interactive --url "https://gitlab-ee.joustie.nl/" --registration-token "xxxx" --executor "shell" --shell "sh" --description "dockerized shell-runner" --tag-list "docker" --run-untagged="true" --locked="false" ---> Running in d90d35beaa37 --2019-05-22 21:05:18-- https://s3.amazonaws.com/gitlab-runner-downloads/master/binaries/gitlab-runner-linux-386 Resolving s3.amazonaws.com... 52.216.18.115 Connecting to s3.amazonaws.com|52.216.18.115|:443... connected. HTTP request sent, awaiting response... 200 OK .... 2019-05-22 19:46:24 (2.22 MB/s) - 'gitlab-runner-linux-386' saved [25824256/25824256]The next step is the execution of the Runner:
Runtime platform arch=386 os=linux pid=1 revision=5159dcdb version=11.12.0~beta.1484.g5159dcdbRunning in system-mode.Then, we need to register it:
Registering runner... succeeded runner=Vh6hpU1D Runner registered successfully. Feel free to start it, but if it's running already the config should be automatically reloaded! Removing intermediate container b55a2ae6998a ---> be4317ad95b0The binary was successfully downloaded, and the registration was successful; a specific Runner token was created and is now part of the Docker image. The final part of the build sets the entry point for the instantiation of a Docker instance with this image:
Step 4/4 : ENTRYPOINT ["./gitlab-runner-linux-386","run"] ---> Running in 8b54b77030bc Removing intermediate container 8b54b77030bc ---> be206c4c268c Successfully built be206c4c268c Successfully tagged dockerrunner:latestIt automatically tagged the image with latest. The image is now available on the machine where its build was executed. You can view it by using the following command:
$ docker images ...If you go to GitLab and open the Runner list in the administrative settings menu, a new Runner will appear there:

Now, it’s time to start the Runner and try to build the eventmanager-documentation project. You can start the Runner in the foreground using the following command:
$ docker run -ti dockerrunnerThe following output should appear after a brief pause:
Runtime platform arch=386 os=linux pid=1 revision=5159dcdb version=11.12.0~beta.1484.g5159dcdb Starting multi-runner from /etc/gitlab-runner/config.toml ... builds=0 Running in system-mode.
Configuration loaded builds=0 listen_address not defined, metrics & debug endpoints disabled builds=0 [session_server].listen_address not defined, session endpoints disabled builds=0As you can see, it has successfully loaded a configuration that was saved in the container during the registration phase. It also mentions the fact that it didn’t load a metrics and debug session server, so this Runner exposes no service of any kind to the outside world. It has connected to the GitLab server and is now waiting for commands.
When we try to run the eventmanager-documentation project pipeline for the master branch, it will spin off a build job to the new GitLab Runner:
Checking for jobs... received job=675 repo_url=https://gitlab-ee.joustie.nl/marketing/eventmanager-documentation.git runner=LT7jz43c WARNING: Job failed: exit status 1 duration=347.5203ms job=675 project=10 runner=LT7jz43c ERROR: Failed to process runner builds=0 error=exit status 1 executor=shell runner=LT7jz43cUnfortunately, it’s failed to build the project. If we look at the job log, we get the following output:

It’s quite clear why the job failed. We created a basic GitLab Runner container without support for the Python language. That is why it complains about the Python Package Manager (PIP) not being found. We need Python to install the Amazon Web Services Command-Line Interface (AWS CLI) utility, which is defined in the .gitlab-ci.yml file for this project.
This is easy to fix. We can change the first line in the Dockerfile to the following:
FROM python:3.7-alpineThis will change the base image of the Docker container to a version of Linux with Python included. Now, you can rebuild the image using the exact same preceding command line and starting the container again.
If we run the pipeline for this project again, the job will succeed:

You can create much more elaborate container images, but this was a basic way to containerize a Runner.
In this section, we have created our own GitLab Runner container and registered it with a GitLab instance. In the next section, we will use a prebuilt image that GitLab provides from their site.
There are two basic flavors of prebuilt Docker containers available (Ubuntu-based and Alpine-based). The big difference between them is that the Alpine one is much smaller and has a better security track. You can find it here: https://gitlab.com/gitlaborg/gitlabrunner/blob/master/dockerfiles/alpine/Dockerfile.
You can run the container with arguments that will be passed through to the GitLab Runner binary that is started inside the container. This also enables easier runtime registration of the Runner with a GitLab instance. Remember from the Creating your own Dockerized GitLab Runner section that we baked the registration of the Runner inside the image. You can find the appropriate images on Docker Hub: https://hub.docker.com/r/gitlab/gitlab-runner/tags.
Just start a container using the following command. It will automatically download the right image:
$ mkdir /Users/shared/gitlab-runner && mkdir /Users/shared/gitlab-runner/config $ docker run -d --name gitlab-runner -v /Users/shared/gitlab-runner/config:/etc/gitlab-runner \ -v /var/run/docker.sock:/var/run/docker.sock \ gitlab/gitlab-runner:latestYou can check the logs of the running container with the following command:
$ dockers logs -f gitlab-runner ERROR: Failed to load config stat /etc/gitlab-runner/config.toml: no such file or directory builds=0The preceding output means that the gitlab-runner software is running inside the container, but it isn’t registered yet.
The next step is to register it and save the configuration file in the container (in the configuration volume you specified with -v):
docker run --rm -v /User/shared/gitlab-runner/config:/etc/gitlab-runner gitlab/gitlab-runner register \ --non-interactive \ --executor "docker" \ --docker-image python:3.7-alpine \ --url "https://gitlab-ee.joustie.nl/" \ --run-untagged="true" \ --registration-token "xxx" \ --description "docker-runner" \ --tag-list "eventmanager" \ --locked="false"If you examine the container logs (maybe you left the window open) after this, a message should appear:
... Configuration loaded builds=0This means that the Runner now has a valid configuration and is online with GitLab.
If we try to trigger the pipeline for the eventmanager-documentation project again, a job will be run:
Checking for jobs... received job=660 repo_url=https://gitlab-ee.joustie.nl/marketing/eventmanager-documentation.git runner=8cX8wWCrIn GitLab, you will see this job running:

In the log file of the container, a message will appear if the job succeeds:
Job succeeded duration=1m17.7055922s job=660 project=10 runner=8cX8wWCrThis is also visible in the job log in GitLab:

This concludes the two ways of running Docker locally with relatively simple containers:
- Building your own container
- Using a prebuilt image
How can you manage this if you have massive amounts of build jobs? You can use an orchestration system such as Kubernetes, which is the subject of the next section.
The best method of deploying a GitLab Runner container into a Kubernetes cluster is by using the GitLab Runner Helm chart.
It contains all of the configuration information that’s run using the GitLab Runner Kubernetes executor. For each new job it receives from GitLab CI/CD, it will provision a new pod within the specified namespace to run it.
You can run the install using the following command:
$ helm install --namespace gitlab --name gitlabrunner -f values.yaml gitlab/gitlab-runnerThis command can take some time to complete. After some time, you will receive the following output:
NAME: gitlabrunner LAST DEPLOYED: Tue May 21 21:11:15 2019 NAMESPACE: gitlab STATUS: DEPLOYED
RESOURCES: ==> v1/ConfigMap NAME DATA AGE gitlabrunner-gitlab-runner 5 0s
...This shows quite a bit of output, but the important part is that the status of the Helm chart is DEPLOYED.
The GitLab Runner should now be registered to the GitLab instance reachable at https://gitlab-ee.joustie.nl/.
We have run this deployment on my local Kubernetes cluster.
You can find out which Kubernetes pods are running by using the following command:
$ kubectl get pods -n gitlab NAME READY STATUS RESTARTS AGE gitlabrunner-gitlab-runner-787dddf5b5-58fzw 1/1 Running 0 2mAs you can see, the Runner was deployed in Kubernetes in the Runner list of the administrative section of GitLab:

We can run the pipeline for the eventmanager-documentation project that was introduced in Chapter 10, Create Your Product, Verifying it, and Packaging it, to demonstrate the fact that multiple Runners are spawned on the Kubernetes cluster. Here is the pipeline view in GitLab showing multiple parallel jobs:

If you look into individual jobs, you will see that it takes some time to spin up the new Runner resources in the cluster. Until it is ready, the job is polled:

After some time, a Runner is spawned in the Kubernetes cluster and the jobs are dispatched to it:

You can view a list of pods on the Kubernetes cluster and see that many pods were created:
After some time, you will see that some parallel started jobs are finishing (in green):

In the end, all of the jobs will succeed and the pipeline will be passed:

After this job, the number of GitLab Runners is reduced once more.
By doing this, we’ve shown you how to use Kubernetes to manage containers and how to handle scaling on the fly.
In this chapter, we showed you how to run GitLab Runners in containers. First, we looked at a quick way to containerize an existing Runner. Then, we showed you how to use existing Docker images that are provided by GitLab itself. Afterward, we talked about a way to manage a greater amount of containers and how you can handle this more economically with Kubernetes.
In the next chapter, we will discuss another way to scale Runners: with autoscaling.
- What are the advantages of the Docker executor?
- What is the basic build command for a Docker container?
- Which file contains the building instructions for a container?
- What is the name of a small Linux container distribution?
- What tool is used to configure a Kubernetes cluster with much more ease?
- How can you set the number of Runners to spawn by default in Kubernetes?
- Kubernetes Course from a DevOps Guru (Kubernetes and Docker), by Tao W, James Lee, and Basit Mustafa:
- Learn Docker – Fundamentals of Docker 18.x, by Gabriel N. Schenker:
- Hands-On Continuous Integration and Delivery, by Jean-Marcel Belmont:
- Containers from Scratch: https://ericchiang.github.io/post/containers-from-scratch/