iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
📝

Pitfalls and Solutions in Self-Hosted CI/CD: Mastering 15 Runners on a Shared Docker Environment (Part 7)

に公開
2026/02/15

What you will learn from this article

  • Common issues and mitigation patterns in self-hosted runner environments
  • How to prevent resource contention on a shared Docker daemon
  • The story of port allocation doomed by the Birthday Paradox
  • Investigation techniques for when "CI that was working suddenly breaks"

Introduction

In part 2, I wrote about E2E test automation using WebAuthn and Mailpit. The tests themselves worked fine. The problem was the CI infrastructure.

Saru has 4 frontends and 4 backend APIs. E2E tests are executed independently for each portal, plus cross-portal tests (coordination tests between portals). When running these in parallel, seven or more jobs run simultaneously.

Initially, I used GitHub-hosted runners, but E2E tests require a database, Keycloak, and a mail server, involving the startup of many Docker containers. With GitHub-hosted runners, the setup time for each run was significant, and the cost-efficiency for parallel execution was poor.

Therefore, I migrated to self-hosted runners. That decision was correct, but a host of new types of problems emerged.

This article records the problems I encountered in the self-hosted CI environment and their solutions chronologically. I hope this serves as a reference for those adopting a similar configuration.

1. Docker Desktop/WSL2 was too unstable

Initial configuration

At first, I ran the runners using Docker Desktop (WSL2 backend) on Windows. The configuration was simple:

Windows Host
  └─ WSL2
      └─ Docker Desktop
          └─ GitHub Actions Runner × N

The problem was that "containers would die randomly." During E2E tests, the PostgreSQL container would suddenly disappear, or Keycloak would stop responding. docker inspect revealed they were being killed with Exit Code: 137 (SIGKILL).

Tracing the cause, the virtualization layer of Docker Desktop/WSL2 was the issue:

Container → Docker Engine → WSL2 → Hyper-V → Windows

WSL2 itself runs as a lightweight Hyper-V VM, with Docker running on top of that. When memory pressure increases, WSL2 triggers the OOM Killer, causing Docker containers to be killed indiscriminately.

Migration to a Hyper-V VM

As a solution, I set up an Ubuntu VM directly on Hyper-V, bypassing WSL2:

Container → Docker Engine → Ubuntu VM → Hyper-V → Windows
Item Value
VM Name saru-ci-runner
OS Ubuntu 24.04
vCPU 16
Memory 64GB
Disk 200GB
Network External Switch (Bridge)

Hyper-V VMs have fewer virtualization layers and more stable memory management than WSL2. WSL2 uses dynamic memory allocation to "share with the host" (up to 50% of host RAM or 8GB by default), but Hyper-V VMs assign fixed memory, lowering the risk of being killed by the OOM Killer.

I deployed 15 GitHub Actions Runners as systemd services on top of this:

# saru-hyperv-1 to saru-hyperv-15
for i in $(seq 1 15); do
  sudo systemctl status actions.runner.ko-chan-saru.saru-hyperv-$i
done

15 runners share a single Docker daemon. This "sharing" would later cause many problems.

2. Port collisions due to the Birthday Paradox

Problem

In E2E tests, each job starts its own PostgreSQL, Keycloak, frontend, and backend. To ensure ports did not collide, I calculated port numbers from the GitHub Actions RUN_ID:

# Initial implementation (problematic)
PORT_OFFSET=$(( RUN_ID % 3000 ))
POSTGRES_PORT=$(( 10000 + PORT_OFFSET ))

This seemed to work at first, but because 15 runners share a single Docker daemon, ports for concurrently running jobs could collide.

It is the same structure as the Birthday Paradox. With 3000 possible port offsets, if there are 5 parallel jobs, the probability of a collision is about 0.33% (1 - 3000!/(3000^5 × 2995!)). This seems trivial, but with CI running dozens of times a day, it would collide several times a week. And when ports collide, you get an incomprehensible error: "The container started, but the service is unreachable."

Solution: RUNNER_NAME-based allocation

I changed the method to assign ports deterministically based on the runner name rather than the random RUN_ID:

# Extract runner number from runner name (e.g., saru-hyperv-7 → 7)
if [[ "${RUNNER_NAME}" =~ saru-hyperv-([0-9]+) ]]; then
  RUNNER_NUM=${BASH_REMATCH[1]}
else
  RUNNER_NUM=$(( (RUN_ID % 15) + 1 ))
fi

# Allocate a 200-port block to each runner
RUNNER_BLOCK=$((RUNNER_NUM * 200))
PORTAL_OFFSET=$((PORTAL_INDEX * 10))

# Frontend/Backend: 20000 + (RUNNER_NUM × 200) + (PORTAL_INDEX × 10) + {0,1,2,3}
BASE_PORT=20000
OFFSET=$((RUNNER_BLOCK + PORTAL_OFFSET))
PORTAL_PORT=$((BASE_PORT + OFFSET + 1))
API_PORT=$((BASE_PORT + OFFSET + 2))

# Infrastructure: 30000 + (RUNNER_NUM × 1000) + {0,100,200,...} + PORTAL_INDEX
BASE_INFRA_PORT=30000
INFRA_RUNNER_BLOCK=$((RUNNER_NUM * 1000))
POSTGRES_PORT=$((BASE_INFRA_PORT + INFRA_RUNNER_BLOCK + PORTAL_INDEX))
KEYCLOAK_PORT=$((BASE_INFRA_PORT + INFRA_RUNNER_BLOCK + 100 + PORTAL_INDEX))

The key is using the constraint that "each runner only executes one job at a time." Since the port block is uniquely determined by the runner number, collisions cannot occur in principle:

Runner Frontend Range Infrastructure Range
saru-hyperv-1 20200–20313 31000–31510
saru-hyperv-2 20400–20513 32000–32510
... ... ...
saru-hyperv-15 23000–23113 45000–45510

I also confirmed that all ports remain within 65535.

3. docker system prune kills containers from other jobs

Problem

I included a Docker cleanup step at the end of the CI job:

# ⚠️ This was the problem
- name: Cleanup
  run: docker system prune -f

docker system prune deletes all stopped containers. Because 15 runners share a single Docker daemon, a cleanup step from one job destroys containers that are actively being used by another job.

This is particularly troublesome right after starting a container. If prune runs right after starting a container with Docker Compose or run, but before the health check passes, the starting container is misidentified as "stopped" and is deleted.

Solution: Targeted cleanup

# ✅ Safe cleanup
# docker system prune and docker container prune are prohibited
# because they destroy containers from concurrent jobs
# Only delete dangling images older than 24 hours
docker image prune -f --filter "until=24h" 2>/dev/null || true

For container deletion, I only target containers associated with my RUN_ID. To avoid accidentally deleting persistent containers (such as saru-postgres-integ), I filter by name pattern:

# Delete only this job's containers (protect persistent containers)
RUN_ID="${{ github.run_id }}"
for container in $(docker ps -a --format '{{.Names}}' \
  | { grep "^saru-" | grep -v "saru-postgres-integ\|saru-keycloak-dev\|saru-mailpit-dev" || true; }); do
  if [[ ! "$container" =~ "${RUN_ID}" ]]; then
    docker rm -f "$container" 2>/dev/null || true
  fi
done

Lesson: In a shared Docker daemon environment, docker system prune is a forbidden move. Thoroughly restrict deletions to specific scopes.

4. Quiet crashes due to insufficient PostgreSQL shared memory

Problem

I encountered a phenomenon where the PostgreSQL container would crash immediately after starting in CI. pg_isready would succeed for a moment, but the subsequent psql command would fail with a "container is not running" error.

✓ pg_isready -U test → success
✗ psql -U test -c "CREATE DATABASE ..." → container is not running

This is extremely confusing. PostgreSQL restarts internally after initdb, so if pg_isready passes just before that restart, the process does not exist by the time the next command executes.

However, the real cause was different. The default /dev/shm size in Docker (64MB) was insufficient for PostgreSQL.

Solution

docker run -d \
  --name saru-postgres-ci \
  --shm-size=256m \  # ← This is important
  --restart=unless-stopped \
  -e POSTGRES_USER=test \
  -e POSTGRES_PASSWORD=test \
  -p 15432:5432 \
  --health-cmd "pg_isready -U test" \
  postgres:16-alpine \
  postgres -c max_connections=200

By specifying --shm-size=256m, I ensure sufficient shared memory space for PostgreSQL. Especially during parallel tests (with -parallel 2 or more), PostgreSQL requires more shared buffers, and 64MB is simply not enough.

This issue is of the "happens occasionally" type and only reproduces under high test load. It took a full day to identify the root cause.

You can check whether the OOM Killer is the cause using docker inspect:

docker inspect "${CONTAINER}" --format '{{.State.OOMKilled}}'
# If true, out of memory is the cause

5. Persistent PostgreSQL container pattern

Problem

Initially, each job started and stopped its own PostgreSQL container. However:

  • Container startup takes 10–15 seconds every time
  • Ports are not immediately released upon stopping, leading to conflicts on the next startup
  • Container lifecycle management is complex (forgetting to stop, zombie containers, etc.)

Solution: Persistent container + Job-specific database

Combined with the --shm-size=256m from section 4, I changed to a method where the container remains running and temporary databases are created and deleted for each job:

# Start PostgreSQL container if not running (initial run only)
- name: Start persistent PostgreSQL
  run: |
    POSTGRES_CONTAINER="saru-postgres-integ"
    if ! docker ps --format '{{.Names}}' | grep -qx "${POSTGRES_CONTAINER}"; then
      docker run -d \
        --name "${POSTGRES_CONTAINER}" \
        --shm-size=256m \
        --restart=unless-stopped \
        -e POSTGRES_USER=test \
        -p 15432:5432 \
        postgres:16-alpine
    fi

    # Create a database for this job
    DB_NAME="integ_${{ github.run_id }}"
    docker exec "${POSTGRES_CONTAINER}" \
      psql -U test -h 127.0.0.1 -c "CREATE DATABASE \"${DB_NAME}\" OWNER test;"

# Delete only the database when the job ends
- name: Cleanup database
  if: always()
  run: |
    docker exec saru-postgres-integ \
      psql -U test -h 127.0.0.1 \
      -c "DROP DATABASE IF EXISTS \"integ_${{ github.run_id }}\";"

    # Clean up old databases left by failed jobs
    STALE_DBS=$(docker exec saru-postgres-integ psql -U test \
      -d postgres -h 127.0.0.1 -tAc \
      "SELECT datname FROM pg_database WHERE datname LIKE 'integ_%';")
    for DB in $STALE_DBS; do
      docker exec saru-postgres-integ psql -U test \
        -d postgres -h 127.0.0.1 \
        -c "DROP DATABASE IF EXISTS \"${DB}\";"
    done

There are 3 key points:

  1. --restart=unless-stopped: The container automatically recovers even if the VM restarts
  2. Use Job ID for database name: Prevents interference between parallel jobs
  3. Cleaning Stale databases: Regularly removes debris left behind by failed jobs

6. Reasons for forcing TCP connection in psql

Problem

When executing psql inside a PostgreSQL container, Unix sockets are used if no connection method is specified. However, PostgreSQL goes through an initdb → restart cycle upon initial startup, and the Unix socket disappears momentarily during the restart:

# ⚠️ Unix socket (default): Potential failure during restart
docker exec postgres psql -U test -c "SELECT 1"

# ✅ TCP connection: Retry works even during restart
docker exec postgres psql -U test -h 127.0.0.1 -c "SELECT 1"

Adding -h 127.0.0.1 forces a TCP connection, making errors easier to understand (a clear "connection refused" rather than an ambiguous error stating the socket file was not found).

Lesson: Always add -h 127.0.0.1 when calling psql in CI scripts.

7. Docker network pool exhaustion

Problem

One day, all E2E jobs suddenly started failing. The error message was:

Error response from daemon: could not find an available,
non-overlapping IPv4 address pool among the defaults to
assign to the network

Docker Compose creates a bridge network for every project. Docker defaults to assigning a /16 subnet from the range of 172.17.0.0/16 to 172.31.0.0/16, limiting the number of creatable networks to about 30. With 15 runners performing E2E tests concurrently and each job creating multiple networks, the pool is exhausted quickly.

Solution

# Remove old networks (protect those associated with the current RUN_ID)
RUN_ID="${{ github.run_id }}"
for net in $(docker network ls --format '{{.Name}}' | { grep "^saru-ci-" || true; }); do
  if [[ ! "$net" =~ "${RUN_ID}" ]]; then
    containers=$(docker network inspect "$net" \
      --format '{{len .Containers}}' 2>/dev/null || echo "in-use")
    if [ "$containers" = "0" ]; then
      docker network rm "$net" 2>/dev/null || true
    fi
  fi
done

Delete unused old networks at the start of each job. Instead of using docker network prune, filter by name and delete only those with 0 connected containers.

8. Preventing OTP conflicts

Problem

In E2E tests, I test OTP (One-Time Password) authentication. Each E2E job shares the same Mailpit instance, and I search for emails via the Mailpit API to retrieve OTP codes.

The issue is that if multiple jobs log in with the same email address (e.g., system-admin@saru.local) simultaneously, multiple OTP emails for the same recipient arrive in Mailpit. While timestamp filtering prevents this to some extent, it cannot fully prevent conflicts at the millisecond level.

Solution: Job-specific email addresses

matrix:
  portal:
    - name: system-auth
      system_email: "system-admin@saru.local"
    - name: system-entities
      system_email: "system-entities@saru.local"
    - name: system-products
      system_email: "system-products@saru.local"
    - name: system-misc
      system_email: "system-misc@saru.local"

By having each job use a different system administrator account (email address), OTP email retrieval no longer conflicts. Register multiple system administrators in the backend seed data.

9. Pitfalls of the hashFiles syntax

Problem

I got stuck trying to use dynamic paths in hashFiles() for GitHub Actions:

# ⚠️ This does not work (string concatenation cannot be used inside hashFiles)
key: ${{ runner.os }}-turbo-${{ hashFiles('apps/' + matrix.app + '/**') }}

Only literal strings can be used as arguments for hashFiles(). Expressions are not evaluated.

Solution

# ✅ Use the format() helper
key: ${{ runner.os }}-turbo-${{ matrix.app }}-${{ hashFiles(format('apps/{0}/**', matrix.app), 'packages/**', 'pnpm-lock.yaml', 'turbo.json') }}

Use the format() function to assemble the path first, then pass the result to hashFiles(). This is not mentioned in the GitHub Actions documentation, but I found it in community discussions (#25718).

10. Migration round-trip testing

In CI, I perform a "migration round-trip" test every time:

# Up → Down 1 step → Re-Up
DATABASE_URL="..." go run ./cmd/migrate -action up
DATABASE_URL="..." go run ./cmd/migrate -action down -steps 1
DATABASE_URL="..." go run ./cmd/migrate -action up

This ensures that:

  • Down migrations are not broken
  • Patterns like "Up → Down renders Up impossible" are detected
  • Safety is guaranteed in case a rollback is required in production

11. Automated diagnosis on failure

To make it easier to identify the cause when CI fails, I collect diagnostic information in the if: failure() step of the job:

- name: Diagnose PostgreSQL on failure
  if: failure()
  run: |
    # Container status
    docker inspect "${POSTGRES_CONTAINER}" --format '{{.State.Status}}'

    # Active connections
    docker exec "${POSTGRES_CONTAINER}" psql -U test -h 127.0.0.1 \
      -c "SELECT datname, count(*) FROM pg_stat_activity GROUP BY datname;"

    # Container logs (last 30 lines)
    docker logs "${POSTGRES_CONTAINER}" --tail 30

    # Host memory status
    free -h

Just having this eliminates the loop of "CI failed → check logs → don't know the cause → re-run and pray".

12. Disk management

Since 15 runners share the same 200GB disk, disk management is crucial:

strategy:
  max-parallel: 2  # Limit concurrency to prevent disk exhaustion

Each job consumes about 2GB for node_modules installation, frontend builds, Playwright browser caches, etc. Running 8 jobs simultaneously consumes 16GB, and when combined with Docker images and build caches, 200GB fills up in no time. I also have periodic cleanup scripts in place for various items like CI artifacts, Runner _temp folders, and build caches.

Summary: Lessons from self-hosted CI

Lesson Details
Shared resources collide Docker daemon, ports, network, disk
Deterministic over random Use RUNNER_NUM base instead of RUN_ID % N for port allocation
prune is a weapon No docker system prune in shared environments
Persistent container + Temp DB Simplifies container lifecycle management
Force TCP Use -h 127.0.0.1 for psql to avoid Unix socket traps
Leave diagnostic info on failure Automate root cause identification with if: failure()
Don't trust Docker defaults Explicitly specify --shm-size and max_connections

Self-hosted CI brings flexibility and speed not found in GitHub-hosted environments. However, it also brings the complexity of managing your own infrastructure. As a solo developer, you are the only one who can fix the CI when it breaks. Therefore, it is important to pursue "why" when a problem occurs and build mechanisms to prevent recurrence. All the countermeasures introduced here were born from actual failures.

Discussion