Skip to main content
Illustration: a runner manager distributing jobs to several automatically created servers

October 10, 2024 8 min read

GitLab Runner Autoscaling in the HETZNER Cloud: Docker Machine is dead, long live Fleeting

Docker Machine has reached the end of the road. My autoscaling setup for Gitlab Runners in the HETZNER Cloud gets a successor: Docker Autoscaler and the official Fleeting plugin.

Back in 2020 I described how my Gitlab Runners scale up and down automatically in the HETZNER Cloud using Docker Machine. The setup ran reliably for years – but its foundations are crumbling. Time for a fresh start with the Docker Autoscaler executor and HETZNER's official Fleeting plugin.

Previously on this blog

In the article Gitlab Runner galore! Autoscale in the HETZNER Cloud I presented my setup in May 2020: a small, permanently running broker accepts jobs from Gitlab and spins up new servers in the HETZNER Cloud on demand. Once the jobs are done, the servers are deleted again. You only pay for what actually computes.

The ingredients back then:

  • the docker+machine executor with a Docker Machine driver for HETZNER
  • a community image for the broker on a CX11
  • runner servers of type CX21 with Ubuntu 18.04
  • a central cache via MinIO on a HETZNER volume
  • a Docker registry as a pull-through cache for Docker images

It worked. With a few band-aids, admittedly: when a Docker update in December 2020 stopped the machines from starting properly, I had to pin the Docker version via engine-install-url. ¯\_(ツ)_/¯

Why a new setup?

Over the years, the problems have piled up:

  • Docker Machine is a dead end. Docker abandoned the project long ago, and Gitlab only kept it alive as its own fork. The docker+machine executor is officially deprecated.
  • The HETZNER driver is no longer maintained. The driver was a community project, and as so often with community projects, at some point upstream went quiet. Meanwhile HETZNER kept evolving its API and deprecated old parts.
  • The configuration is outdated.OffPeakPeriods and friends were replaced by [[runners.machine.autoscaling]] years ago.
  • The server types no longer exist. CX11 and CX21 have disappeared from the HETZNER portfolio.
  • One container per VM. Docker Machine runs exactly one job per server. For lots of small jobs that's a waste – every VM needs its boot time, and every job starts on a bare server.

In short: the old setup is a dead end. We need something new!

The new approach: Docker Autoscaler and Fleeting

As a successor to Docker Machine, Gitlab built a new autoscaling architecture. It consists of three building blocks:

  • docker-autoscaler executor: runs the jobs in Docker containers – as usual – but on dynamically created instances.
  • Taskscaler: lives inside the runner itself and calculates how much capacity is currently needed.
  • Fleeting plugin: the bridge to the cloud provider. For HETZNER there is now an official plugin by HETZNER itself (hetznercloud/fleeting-plugin-hetzner). No more orphaned community driver.

In principle the flow is the same as before: a small runner manager (formerly: broker) runs permanently, fetches jobs from Gitlab and has worker servers created on demand. The differences are in the details – and the details make all the difference:

 2020: Docker MachineToday: Docker Autoscaler
Executordocker+machinedocker-autoscaler
HETZNER integrationcommunity driverofficial Fleeting plugin by HETZNER
Broker / managerDocker container on CX11gitlab-runner as a system service on CPX11
Jobs per serverexactly oneconfigurable (capacity_per_instance)
Server setupDocker Machine provisions via SSHcloud-init (user_data)
Docker versionvia install script, pinned if necessarystraight from the official Docker repository
SchedulingOffPeakPeriods[[runners.autoscaler.policy]] with cron syntax
Idle reservein servers (IdleCount)in job slots (idle_count)

The most important point for me: a worker can now run several jobs at the same time. A CPX21 with four job slots is far more efficient than four separate servers that each have to boot, install Docker and pull images.

Step 1: The infrastructure

I recommend creating a dedicated project in the HETZNER Cloud for CI. That way the runners and your production servers don't get in each other's way – neither with API rate limits nor by accident when cleaning up.

In the project we need an API token with read and write permissions. I do the rest with the hcloud CLI:

# create a context for the CI project (asks for the API token)
hcloud context create gitlab-ci

# upload your own SSH key
hcloud ssh-key create --name dev --public-key-from-file ~/.ssh/id_ed25519.pub

# create the runner manager
hcloud server create \
  --name runner-manager \
  --image debian-12 \
  --type cpx11 \
  --location nbg1 \
  --ssh-key dev \
  --label runner=

On top of that comes a firewall that only lets SSH and ICMP through and applies via the label selector runner:

hcloud firewall create --name runner
hcloud firewall add-rule runner --direction in --protocol icmp --source-ips 0.0.0.0/0 --source-ips ::/0
hcloud firewall add-rule runner --direction in --protocol tcp --port 22 --source-ips 0.0.0.0/0 --source-ips ::/0
hcloud firewall apply-to-resource runner --type label_selector --label-selector runner

Afterwards, hcloud all list shows everything that exists in the project.

Step 2: Installing Gitlab Runner

On the runner manager we install Gitlab Runner the classic way from the official package repository:

curl -L "https://packages.gitlab.com/install/repositories/runner/gitlab-runner/script.deb.sh" | bash
apt-get install gitlab-runner

Unlike 2020, we no longer need a Docker container for the broker or a community image. The runner runs as a perfectly normal system service.

In Gitlab we then create a new runner (instance, group or project – as needed) and note down its authentication token.

Step 3: The configuration

The heart of it all is once again /etc/gitlab-runner/config.toml (confidential information removed):

concurrent = 10
log_level = "info"

[[runners]]
  name = "hetzner-docker-autoscaler"
  url = "*************"
  token = "*************"
  executor = "docker-autoscaler"

  [runners.docker]
    image = "alpine:latest"

  [runners.autoscaler]
    # Fleeting plugin by HETZNER – pin a fixed version for production
    plugin = "hetznercloud/fleeting-plugin-hetzner:latest"

    capacity_per_instance = 4   # jobs per worker
    max_instances = 5           # hard upper limit – this is our cost brake
    max_use_count = 0           # reuse workers indefinitely

    # only start once cloud-init has finished
    instance_ready_command = "cloud-init status --wait || test $? -eq 2"

    [runners.autoscaler.plugin_config]
      name = "runner-docker-autoscaler"   # prefix for the server names
      token = "*************"
      location = "nbg1"
      server_type = "cpx21"
      image = "debian-12"
      user_data = """#cloud-config
package_update: true
package_upgrade: true
apt:
  sources:
    docker.list:
      source: deb [signed-by=$KEY_FILE] download.docker.com/linux/debian $RELEASE stable
      keyid: 9DC858229FC7DD38854AE2D88D81803C0EBFCD88
packages:
  - ca-certificates
  - docker-ce
swap:
  filename: /var/swap.bin
  size: auto
  maxsize: 4294967296
"""

    [runners.autoscaler.connector_config]
      use_external_addr = true

    [[runners.autoscaler.policy]]
      periods = ["* * * * *"]
      timezone = "Europe/Berlin"
      idle_count = 8
      idle_time = "1h"

Then we install the plugin and restart the service:

gitlab-runner fleeting install
systemctl restart gitlab-runner

What's going on here

  • capacity_per_instance defines how many jobs a worker handles in parallel. On a CPX21 (3 vCPU, 4 GB RAM), four slots are a good starting point for typical PHP and frontend jobs. If your jobs are memory-hungry, go lower or pick a bigger server type.
  • max_instances is the upper limit for workers. Together with capacity_per_instance it determines the maximum parallelism – 20 jobs here, additionally capped by concurrent = 10.
  • user_data is cloud-init. Instead of Docker Machine fiddling around on the fresh server via SSH, the server gets itself into shape on first boot: Docker from the official repository, plus a bit of swap as a buffer. That's the end of pinning Docker versions by hand.
  • instance_ready_command makes the runner wait until cloud-init is done. For cloud-init, exit code 2 means “done, but with warnings” and is therefore accepted as well.
  • use_external_addr lets the runner reach the workers via their public IP over SSH. The plugin creates the SSH key pair for this by itself.

Policies instead of OffPeak

The old OffPeak settings are history. Instead there are [[runners.autoscaler.policy]] blocks with cron syntax. The last matching block wins. This is how I keep a reserve during the day and let everything shut down at night and on weekends:

    # default: no reserve
    [[runners.autoscaler.policy]]
      periods = ["* * * * *"]
      timezone = "Europe/Berlin"
      idle_count = 0
      idle_time = "10m"

    # weekdays 7am–7pm: keep two workers warm
    [[runners.autoscaler.policy]]
      periods = ["* 7-18 * * mon-fri"]
      timezone = "Europe/Berlin"
      idle_count = 8
      idle_time = "30m"

Important – and this confused me at first: idle_count counts job slots, not servers. With idle_count = 8 and capacity_per_instance = 4 the runner keeps two workers in reserve. Previously, IdleCount = 2 meant two servers.

Step 4: Testing and debugging

The debugging tip from back then still applies in spirit: watch the runner while it works.

journalctl --output=cat -f -u gitlab-runner

The log nicely shows how the taskscaler does its maths: how many instances are needed, when new servers are requested and when they are ready. For me it takes about a minute until a fresh worker accepts jobs.

In parallel, hcloud server list lets you watch the workers with the prefix runner-docker-autoscaler- appear and disappear.

What becomes of the old improvements

In the first article I also set up a central cache and a Docker image cache. Both still make sense, but look a bit different today.

Central cache

Back then: MinIO on a HETZNER volume, because HETZNER didn't offer S3-compatible storage. Meanwhile HETZNER offers exactly that with Object Storage. You can skip running your own MinIO server and hook the bucket straight into the runner configuration:

  [runners.cache]
    Type = "s3"
    Shared = true
    [runners.cache.s3]
      ServerAddress = "nbg1.your-objectstorage.com"
      AccessKey = "***************"
      SecretKey = "************************************"
      BucketName = "gitlab-runner-cache"
      BucketLocation = "nbg1"

Caching Docker images

The registry as a pull-through cache still works. Instead of the Docker Machine option engine-registry-mirror, you now add the mirror to /etc/docker/daemon.json in the workers' cloud-init configuration. Since workers process several jobs in a row and keep images locally, the effect is smaller than before, when every job started on a bare server.

Things to watch out for

  • Tokens: both the runner token and the HETZNER API token are stored in plain text in config.toml. Protect the file accordingly – and the API token should only be valid for the CI project.
  • Pin the plugin version::latest is convenient, but not reproducible. In production I pin a fixed version.
  • Check the firewall: verify in the Cloud Console that the automatically created workers are actually covered by the firewall. The label selector only applies if the servers carry the matching label.
  • Keep an eye on costs:max_instances, idle_count and idle_time determine the bill. Each worker also gets a public IPv4 address, which costs extra as well.

Conclusion

The new setup is tidier than the old one: no orphaned driver, no community image for the broker, no pinned Docker versions. Instead: an official plugin by HETZNER, an architecture that Gitlab actively develops, and workers that handle several jobs at once.

The basic idea has stayed the same: only pay for runners when you need them. It just no longer feels like a house of cards that collapses with the next Docker update.