forgejo-runner: give CI jobs a Docker daemon of their own

jar-lid-archive's CI needs `docker build` and `docker compose`, and job
containers had no Docker at all: config.yml carried the stock
`container.docker_host: "-"`, which is precisely "find a daemon for the
runner and do not let jobs near it".

A docker:dind sidecar now runs on forgejo-runner-box, published on
127.0.0.1 only, and jobs build against that instead of the host daemon.
Following Forgejo's own admin docs, which make the point that this is
THREE settings and not one:

  forgejo-dind.service        a privileged docker:dind on the host daemon
  container.docker_host       tcp://127.0.0.1:2376 - where the runner
                              CREATES job containers
  runner.envs.DOCKER_HOST +   tcp://forgejo-dind.docker.internal:2375 -
  container.options           how a job, from INSIDE dind, reaches it

The third is the one that is easy to miss and fails identically to
having done nothing: for a tcp:// docker_host the runner mounts nothing
into the job container, so the job still finds no daemon. The two
addresses differ because they are used from different places - the
runner is a process on the host; a job container is inside dind, where
127.0.0.1 is itself. `host-gateway` is expanded by the daemon creating
the container, which is dind, so it lands on dind's own bridge gateway.

Verified on the box, along the exact path a job takes - a container on a
user-defined network, with the same --add-host and DOCKER_HOST the
runner will set: the name resolves to 172.20.0.1, `docker version`
returns the dind server, and `docker build` succeeds. The host daemon
runs forgejo-dind and nothing else.

config.yml had to become a template to do any of this. It was previously
`generate-config` run once on first deploy and never touched again, so
the repo had no say in its contents. Every value was transcribed from
the live file and diffed against it key by key: with dind disabled, 30
of 30 identical. Two deliberate differences - runner.envs drops
A_TEST_ENV_NAME_1/2, upstream's placeholders, which were being injected
into every job here; and the upstream comment blob is gone. Because the
file is managed now it also gets a restart handler, the absence of which
has bitten this repo before.

Things deliberately chosen rather than defaulted into:

- the flag lives in the playbook, not the role defaults, so the role's
  default stays the configuration this host has always run and turning
  it off is one line. Disabling it also tears the units down rather than
  just skipping them.
- dind is a hard Requires= of forgejo-runner, and its unit stays in
  "activating" until the daemon answers. A dead dind is then one red
  unit instead of a green runner failing every job it claims.
- the healthcheck and monitored_services learned about dind for the same
  reason: runner up + dind down is the interesting failure and it was
  previously invisible.
- /var/lib/docker is a named volume, or every image is re-pulled on each
  container recreation; a weekly prune keeps that from growing forever.
- dind's network pool is pinned to 172.20.0.0/14. Docker's stock pool
  reaches into 192.168.x, and act_runner creates a network per job, so a
  job could eventually allocate this LAN's subnet and lose the route to
  every box on it.

Note this runner is SHARED - arbret, arbret-biz, arbretdos and
arbret-ops build here too, far more often, and docker_host is per-runner
not per-repo. Their workflows are unchanged but their next run pulls
images into a cold cache. Job images still need a docker client of their
own: node:{20,22}-bookworm ship none.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
counterweight 2026-09-27 22:32:08 +02:00
parent d208783fbf
commit 97c7d580bc
Signed by: counterweight
GPG key ID: 883EDBAA726BD96C
16 changed files with 699 additions and 17 deletions

View file

@ -0,0 +1,122 @@
# Forgejo Runner configuration - MANAGED BY ANSIBLE (roles/forgejo_runner).
# Local edits are overwritten on the next run. Change the role instead.
#
# Until the Docker-in-Docker work this file was NOT managed: configure.yml ran
# `forgejo-runner generate-config` once, on first deploy, and never touched the
# result again. Setting container.docker_host meant either patching YAML in
# place with a regex - the fragile thing this repo has been bitten by before -
# or templating the file. So it is templated.
#
# Every value below was transcribed from the config.yml live on
# forgejo-runner-box, which was still stock generate-config output, so applying
# this with dind disabled is a no-op. Two exceptions, both deliberate:
#
# - runner.envs lost A_TEST_ENV_NAME_1 and A_TEST_ENV_NAME_2. They are
# upstream's example placeholders and were being injected into every job on
# this runner. Nothing can depend on them.
# - the upstream comment blob is gone. The values are unchanged.
{#
Two values are assembled rather than written straight out, because each has
a dind half and a caller-supplied half and they have to merge, not compete.
#}
{% set _envs = dict(forgejo_runner_envs) %}
{% set _opts = [forgejo_runner_container_options] if forgejo_runner_container_options else [] %}
{% if forgejo_runner_dind_enabled %}
{% set _ = _envs.update({'DOCKER_HOST': 'tcp://' ~ forgejo_runner_dind_internal_host ~ ':' ~ forgejo_runner_dind_container_port}) %}
{% set _ = _opts.insert(0, '--add-host=' ~ forgejo_runner_dind_internal_host ~ ':host-gateway') %}
{% endif %}
log:
level: {{ forgejo_runner_log_level }}
job_level: {{ forgejo_runner_log_job_level }}
runner:
file: .runner
# Concurrent tasks. NOTE, with dind enabled: all capacity slots share ONE
# Docker daemon, so two jobs running at once can see and touch each other's
# containers, images and volumes through the docker CLI. Forgejo's admin docs
# call this out. It is the accepted trade for a single shared runner; drop
# this to 1 if untrusted code ever runs here.
capacity: {{ forgejo_runner_capacity }}
{% if _envs %}
# Environment for every job. DOCKER_HOST is the half of the dind setup that
# the JOB uses: the runner exports it into each job, service and step
# container, so `docker build` and `docker compose` inside a job find the
# dind daemon instead of a socket that is not there.
envs:
{% for key, value in _envs | dictsort %}
{{ key }}: {{ value }}
{% endfor %}
{% else %}
envs: {}
{% endif %}
env_file: .env
timeout: {{ forgejo_runner_job_timeout }}
# How long a `systemctl stop/restart` waits for in-flight jobs. It is 3h, so
# redeploying while a job is running does NOT return promptly - see the
# README's note on when to deploy.
shutdown_timeout: {{ forgejo_runner_shutdown_timeout }}
insecure: false
fetch_timeout: 5s
fetch_interval: 2s
report_interval: 1s
# Empty: the labels in .runner, fixed at registration, are used.
labels: []
cache:
enabled: {{ 'true' if forgejo_runner_cache_enabled else 'false' }}
dir: ""
# The address job containers use to reach the runner's cache server, NOT the
# address it listens on. Empty means autodetect, which picks this host's
# outbound address.
#
# This is the value most likely to need attention under dind. Job containers
# now live inside dind and reach the host by NAT, so the address has to be
# one that is routable from in there - this box's LAN address is, and that is
# what autodetect returns today. If actions/cache starts silently missing
# after enabling dind, look here first: pin forgejo_runner_cache_host to
# {{ ansible_default_ipv4.address | default('this host LAN address') }}.
host: "{{ forgejo_runner_cache_host }}"
port: 0
proxy_port: 0
external_server: ""
secret: ""
actions_cache_url_override: ""
container:
network: "{{ forgejo_runner_container_network }}"
enable_ipv6: false
# Stays false. The dind CONTAINER is privileged; job containers have no need
# to be, because the daemon they talk to is already running elsewhere.
privileged: false
{% if _opts %}
# --add-host resolves the dind hostname inside every job container. Docker
# expands `host-gateway` against the daemon that CREATES the container -
# which is dind - so it lands on dind's own bridge gateway, where its dockerd
# is listening. Without this the DOCKER_HOST above names something no job can
# resolve, and jobs fail exactly as if nothing had been configured.
options: '{{ _opts | join(" ") }}'
{% else %}
options:
{% endif %}
workdir_parent:
valid_volumes: {{ forgejo_runner_valid_volumes | to_json }}
{% if forgejo_runner_dind_enabled %}
# Create job, service and step containers on the dind daemon instead of this
# host's. Reached over the published loopback port, because the runner is a
# plain process on the host, not a container beside dind.
#
# Consequence worth knowing: NOTHING a workflow does now touches the host's
# Docker daemon. Images are pulled fresh into dind the first time each one is
# needed, and service containers declared by a job land in dind alongside the
# job container, which is what makes `docker compose` reach them by name.
docker_host: 'tcp://{{ forgejo_runner_dind_bind_address }}:{{ forgejo_runner_dind_host_port }}'
{% else %}
# "-" - find a daemon for the runner's own use, and do not expose it to jobs.
docker_host: '-'
{% endif %}
force_pull: false
force_rebuild: false
host:
workdir_parent:

View file

@ -0,0 +1,16 @@
# MANAGED BY ANSIBLE - roles/forgejo_runner
[Unit]
Description=Prune unused images and containers inside the Forgejo dind daemon
After={{ forgejo_runner_dind_service }}.service
Requires={{ forgejo_runner_dind_service }}.service
[Service]
Type=oneshot
# Inside the dind container, against dind's own daemon - NOT the host's. The
# host daemon still holds the dind image itself and is not touched here.
#
# Volumes are excluded on purpose; see forgejo_runner_dind_prune_filter in the
# role defaults for why a timer is the wrong place to delete those.
ExecStart=/usr/bin/docker exec {{ forgejo_runner_dind_container }} docker system prune --all --force --filter "{{ forgejo_runner_dind_prune_filter }}"
StandardOutput=journal
StandardError=journal

View file

@ -0,0 +1,12 @@
# MANAGED BY ANSIBLE - roles/forgejo_runner
[Unit]
Description=Weekly prune of the Forgejo dind image and container store
[Timer]
OnCalendar={{ forgejo_runner_dind_prune_on_calendar }}
# The box may be off at 04:30 on a Sunday; catch up rather than skip a week.
Persistent=true
RandomizedDelaySec=900
[Install]
WantedBy=timers.target

View file

@ -0,0 +1,52 @@
# MANAGED BY ANSIBLE - roles/forgejo_runner
#
# The isolated Docker daemon that Forgejo Actions jobs use. It runs ON this
# host's daemon but is a separate daemon: nothing a workflow does here can see
# or touch the host's containers, images or volumes.
[Unit]
Description=Docker-in-Docker daemon for Forgejo Actions jobs
Documentation=https://forgejo.org/docs/latest/admin/actions/docker-access/
After=docker.service
Requires=docker.service
[Service]
Type=simple
Restart=always
RestartSec=10
# dind pulls its image on first start and initialises /var/lib/docker; neither
# is fast on a cold volume, and a deadline here would just flap it.
TimeoutStartSec=0
# A container left behind by a hard kill would make `docker run --name` fail.
# Leading "-" so a clean start is not an error.
ExecStartPre=-/usr/bin/docker rm -f {{ forgejo_runner_dind_container }}
ExecStart=/usr/bin/docker run --rm --name {{ forgejo_runner_dind_container }} \
--privileged \
--publish {{ forgejo_runner_dind_bind_address }}:{{ forgejo_runner_dind_host_port }}:{{ forgejo_runner_dind_container_port }} \
--volume {{ forgejo_runner_dind_volume }}:/var/lib/docker \
--env DOCKER_TLS_CERTDIR= \
{{ forgejo_runner_dind_image }} \
dockerd \
--host=tcp://0.0.0.0:{{ forgejo_runner_dind_container_port }} \
--host=unix:///var/run/docker.sock \
--default-address-pool base={{ forgejo_runner_dind_address_pool }},size={{ forgejo_runner_dind_address_pool_size }}
# Hold the unit in "activating" until the daemon actually answers, so that
# forgejo-runner.service - which Requires= and After= this one - is never
# started against a socket that is not up yet. The runner does not retry: with
# an explicit container.docker_host it fails the connection and the job with it.
#
# Bounded by `timeout` rather than a counting loop, so a dind that never comes
# up FAILS this unit instead of hanging the boot. That is also the thing that
# catches a bad dockerd flag: the container exits, this never answers, and the
# unit goes red rather than the runner quietly losing Docker.
ExecStartPost=/usr/bin/timeout {{ forgejo_runner_dind_ready_timeout }} /bin/sh -c 'until /usr/bin/docker -H tcp://{{ forgejo_runner_dind_bind_address }}:{{ forgejo_runner_dind_host_port }} version >/dev/null 2>&1; do sleep 1; done'
ExecStop=/usr/bin/docker stop --time 30 {{ forgejo_runner_dind_container }}
StandardOutput=journal
StandardError=journal
[Install]
WantedBy=multi-user.target

View file

@ -1,8 +1,23 @@
# MANAGED BY ANSIBLE - roles/forgejo_runner
[Unit]
Description=Forgejo Runner
Documentation=https://forgejo.org/docs/latest/admin/actions/
{% if forgejo_runner_dind_enabled %}
# forgejo-dind is a hard dependency, not a nicety. With an explicit
# container.docker_host the runner does not fall back to anything: if that
# daemon is not answering, every job it picks up fails to create its container.
# Requires= also means a stopped dind stops the runner, so the failure is one
# red unit rather than a runner that looks healthy and fails every job.
#
# The dind unit stays in "activating" until its daemon answers, so After= here
# really does mean "after Docker is usable", not just "after the process
# forked".
After=docker.service {{ forgejo_runner_dind_service }}.service
Requires=docker.service {{ forgejo_runner_dind_service }}.service
{% else %}
After=docker.service
Requires=docker.service
{% endif %}
[Service]
Type=simple

View file

@ -38,10 +38,34 @@ main() {
report false "forgejo-runner is not active"
exit 1
fi
{% if forgejo_runner_dind_enabled %}
# An active runner is no longer the whole answer. With container.docker_host
# pointing at dind, a dead dind means the runner keeps claiming jobs and
# fails every one of them at container creation - green unit, red CI. So
# check the daemon jobs actually build on, not just that its unit is up:
# the unit can be active while dockerd inside it has died.
if ! systemctl is-active --quiet {{ forgejo_runner_dind_service }}; then
log_message "ERROR: {{ forgejo_runner_dind_service }} is not active"
report false "{{ forgejo_runner_dind_service }} is not active"
exit 1
fi
if ! docker -H tcp://{{ forgejo_runner_dind_bind_address }}:{{ forgejo_runner_dind_host_port }} version >/dev/null 2>&1; then
log_message "ERROR: dind daemon not answering on {{ forgejo_runner_dind_bind_address }}:{{ forgejo_runner_dind_host_port }}"
report false "dind daemon not answering"
exit 1
fi
log_message "forgejo-runner is active and the dind daemon answers"
report true "active"
exit 0
{% else %}
log_message "forgejo-runner is active"
report true "active"
exit 0
{% endif %}
}
main