From 2a4b88321879becb9acc7065cc9ffc477459792c Mon Sep 17 00:00:00 2001 From: Florian Kinder Date: Mon, 2 Nov 2026 16:11:48 +0100 Subject: [PATCH] Add bounded read-only RCON server health checks --- README.md | 12 ++++++ docker/Dockerfile | 2 + docker/Dockerfile.rootless | 2 + docker/files/docker-healthcheck.sh | 9 ++++ tests/test_healthcheck.py | 68 ++++++++++++++++++++++++++++++ 5 files changed, 93 insertions(+) create mode 100755 docker/files/docker-healthcheck.sh create mode 100644 tests/test_healthcheck.py diff --git a/README.md b/README.md index 83f35ae4..413720f1 100644 --- a/README.md +++ b/README.md @@ -95,6 +95,18 @@ This does not require the RCON connection to be exposed. docker exec factorio rcon /h ``` +### Server health + +Newly built regular and rootless images include a Docker health check. It runs the read-only `rcon /players count` command locally and requires a valid response within five seconds; an open TCP port alone is not considered healthy. No RCON port needs to be published, and no Lua command is used or achievements changed. + +```shell +docker inspect --format '{{.State.Health.Status}}' factorio +``` + +The default interval is 30 seconds, with three retries and a five-minute startup grace period. For large saves or heavy mod sets, adjust Compose `healthcheck.start_period`, `interval` and `retries` to allow for loading and save pauses. Use `healthcheck.disable: true` (or `docker run --no-healthcheck`) if you intentionally disable or replace RCON. + +Docker reports `starting`, `healthy` or `unhealthy`; it does **not** automatically restart an unhealthy container. Monitoring tools can observe the Docker health state instead of depending on a changing public-lobby game ID. This does not provide an HTTP endpoint or test internet/UDP reachability. Do not expose the Docker API or RCON publicly just to monitor health. + ### Upgrading Before upgrading backup the save. It's easy to make a save in the client. diff --git a/docker/Dockerfile b/docker/Dockerfile index 1f38a2c6..f6db4e05 100755 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -103,4 +103,6 @@ COPY --from=rcon-builder /src/rcon /bin/rcon VOLUME /factorio EXPOSE $PORT/udp $RCON_PORT/tcp +HEALTHCHECK --interval=30s --timeout=10s --start-period=5m --retries=3 CMD ["/docker-healthcheck.sh"] + ENTRYPOINT ["/docker-entrypoint.sh"] diff --git a/docker/Dockerfile.rootless b/docker/Dockerfile.rootless index a8d837d8..9fca4af0 100644 --- a/docker/Dockerfile.rootless +++ b/docker/Dockerfile.rootless @@ -97,4 +97,6 @@ EXPOSE $PORT/udp $RCON_PORT/tcp # Run as non-root user (UID 1000 is common for the first user in rootless containers) USER 1000:1000 +HEALTHCHECK --interval=30s --timeout=10s --start-period=5m --retries=3 CMD ["/docker-healthcheck.sh"] + ENTRYPOINT ["/docker-entrypoint.sh"] \ No newline at end of file diff --git a/docker/files/docker-healthcheck.sh b/docker/files/docker-healthcheck.sh new file mode 100755 index 00000000..9e1a5dfc --- /dev/null +++ b/docker/files/docker-healthcheck.sh @@ -0,0 +1,9 @@ +#!/bin/bash +set -euo pipefail + +# Avoid invoking the RCON client before startup has created its password file. +[[ -s "${CONFIG:?}/rconpw" && -r "$CONFIG/rconpw" ]] || exit 1 + +# A TCP connection alone cannot detect failed authentication or a stuck server. +response=$(timeout 5s rcon /players count) || exit 1 +[[ "$response" =~ ^Players\ \([0-9]+\): ]] diff --git a/tests/test_healthcheck.py b/tests/test_healthcheck.py new file mode 100644 index 00000000..3113a2f5 --- /dev/null +++ b/tests/test_healthcheck.py @@ -0,0 +1,68 @@ +"""Read-only RCON health probe tests, including false-positive and timeout cases.""" + +import os +from pathlib import Path +import subprocess +import tempfile +import time +import unittest + +ROOT = Path(__file__).resolve().parents[1] +PROBE = ROOT / "docker/files/docker-healthcheck.sh" + + +class HealthcheckTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.work = Path(self.temp.name) + (self.work / "rconpw").write_text("fixture-password\n") + rcon = self.work / "rcon" + rcon.write_text('''#!/bin/sh +[ "$*" = '/players count' ] || exit 99 +case "$MODE" in + healthy) printf 'Players (12):\\n\\n';; + empty) exit 0;; + denied) printf 'Authentication failed\\n';; + disconnected) exit 1;; + hang) exec sleep 30;; +esac +''') + rcon.chmod(0o755) + self.env = {**os.environ, "CONFIG": str(self.work), "PATH": f"{self.work}:{os.environ['PATH']}"} + + def run_probe(self, mode): + return subprocess.run(["bash", str(PROBE)], env={**self.env, "MODE": mode}, + capture_output=True, text=True, timeout=10) + + def test_valid_response_is_healthy_and_quiet(self): + result = self.run_probe("healthy") + self.assertEqual(result.returncode, 0, result.stderr) + self.assertEqual(result.stdout, "") + + def test_empty_denied_or_disconnected_are_unhealthy(self): + for mode in ("empty", "denied", "disconnected"): + with self.subTest(mode=mode): + self.assertNotEqual(self.run_probe(mode).returncode, 0) + + def test_missing_or_empty_password_is_unhealthy(self): + (self.work / "rconpw").unlink() + self.assertNotEqual(self.run_probe("healthy").returncode, 0) + (self.work / "rconpw").touch() + self.assertNotEqual(self.run_probe("healthy").returncode, 0) + + def test_unresponsive_server_is_bounded(self): + start = time.monotonic() + self.assertNotEqual(self.run_probe("hang").returncode, 0) + self.assertLess(time.monotonic() - start, 9) + + def test_both_image_variants_install_the_probe(self): + for name in ("Dockerfile", "Dockerfile.rootless"): + text = (ROOT / "docker" / name).read_text() + self.assertIn('CMD ["/docker-healthcheck.sh"]', text) + self.assertIn("--start-period=5m", text) + self.assertTrue(os.access(PROBE, os.X_OK)) + + +if __name__ == "__main__": + unittest.main()