Dockerfiles, Health Checks & Release Pipelines
Package an AI service and lightweight UI in a multi-stage, non-root Dockerfile with liveness and readiness health probes, automated test verification, and a GitHub Actions release pipeline in fde-04-2
A workflow that passes local unit tests can still fail in deployment due to missing system packages, bloated images, root-owned processes, or orchestrators routing traffic before dependencies are initialized.
In this module, you will package a Python service and lightweight operator UI in a multi-stage, non-root Dockerfile with explicit liveness and readiness health probes, automated pytest tests, and a GitHub Actions release-build validation pipeline in fde-04-2.
Enterprise Scenario: Northwind Freight
Northwind’s platform team is containerizing the freight-exception triage API and lightweight operator status UI. Before traffic is routed to a new container revision, the runtime must expose a fast /health liveness probe and a /ready readiness probe, run as a non-root user, and pass both unit tests and a successful container smoke test in CI.
What You Will Build
- Service and health probes: Implement a typed Python HTTP service in
src/fde_04_2/service.pywithServiceConfig, readiness state evaluation,/health,/ready, and a minimal HTML status UI. - Multi-stage non-root container: Write a
Dockerfileand.dockerignoreusing a multi-stage build and a non-root user (appuser). - Automated tests and release pipeline: Add
pytesttests intests/test_service.pyand a GitHub Actions workflow in.github/workflows/release.ymlthat runs tests, builds the Docker image, and smoke-tests the running container.
1. Health Probes, Container Hardening, and Release Pipelines
- Separating
/healthand/ready: Keep/healthlightweight so it verifies the HTTP server process is responsive. Keep/readyfocused on whether required runtime configuration and dependency readiness checks pass so traffic shifts only when the instance can serve requests. - Multi-stage builds and non-root execution: Install dependencies in a builder stage and copy only what the runtime needs into the final stage. Switch to a dedicated non-root user with
USERbefore starting the server process. - Release pipeline discipline: Run unit tests first so logic regressions fail fast, then build and smoke-test the container in CI to verify packaging, HTTP probes, and non-root execution before a separate publishing or deployment stage.
- Teaching scope boundary: This teaching module uses Python’s standard-library
http.serverand a pluggable readiness check so you can test endpoints and container builds locally with zero heavy framework overhead. Production deployments typically pair an ASGI/WSGI server with a process manager, external secret injection, and registry push credentials.
Probe and Pipeline Responsibilities
| Component | Responsibility | Failure behavior |
|---|---|---|
GET /health | Confirms process liveness and basic HTTP response | Returns 200 when process is alive |
GET /ready | Checks service config and readiness predicate | Returns 503 when not ready; 200 when ready |
GET / | Serves lightweight operator status UI | Returns 200 HTML status page |
Multi-stage Dockerfile | Builds runtime environment and runs as non-root user | Fails build if dependencies or copy steps break |
.github/workflows/release.yml | Runs pytest, builds the Docker image, smoke-tests /health and /ready, and verifies the container runs as non-root | Blocks the pipeline on test, image build, endpoint, or non-root verification failure |
2. Step-by-Step Build Walkthrough
- Create the
fde-04-2repository and project scaffold:mkdir -p fde-04-2/src/fde_04_2 fde-04-2/tests fde-04-2/.github/workflows cd fde-04-2 git init cat > .gitignore <<'EOF' .venv/ .env __pycache__/ .pytest_cache/ *.egg-info/ dist/ build/ EOF cat > .dockerignore <<'EOF' .venv/ .git/ __pycache__/ .pytest_cache/ *.egg-info/ dist/ build/ .env EOF cat > pyproject.toml <<'EOF' [build-system] requires = ["setuptools>=68"] build-backend = "setuptools.build_meta" [project] name = "fde-04-2" version = "0.1.0" description = "Dockerfiles, liveness and readiness health checks, and CI release pipelines" requires-python = ">=3.11" dependencies = ["pydantic>=2.6,<3"] [project.optional-dependencies] dev = ["pytest>=8.0,<9"] [tool.setuptools.packages.find] where = ["src"] [tool.pytest.ini_options] testpaths = ["tests"] EOF cat > .env.example <<'EOF' APP_ENV=development SERVICE_NAME=northwind-triage PORT=8080 READY_FLAG=true EOF python3 -m venv .venv source .venv/bin/activate python -m pip install --upgrade pip python -m pip install -e ".[dev]" cp .env.example .env - Implement the service, health probes, and status UI in
src/fde_04_2/service.py:"""HTTP service with /health and /ready probes and a lightweight operator UI.""" from __future__ import annotations import html import json import os from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from typing import Callable from urllib.parse import urlparse from pydantic import BaseModel, ConfigDict, Field, field_validator ReadinessCheckFn = Callable[[], tuple[bool, str]] def _require_non_blank(value: str, field_name: str) -> str: cleaned = value.strip() if not cleaned: raise ValueError(f"{field_name} must not be blank") return cleaned class ServiceConfig(BaseModel): """Runtime configuration for the containerized service.""" model_config = ConfigDict(extra="forbid", strict=True) service_name: str = Field(default="northwind-triage", min_length=1) environment: str = Field(default="development", min_length=1) host: str = Field(default="0.0.0.0", min_length=1) port: int = Field(default=8080) @field_validator("service_name", "environment", "host") @classmethod def _validate_strings(cls, value: str, info) -> str: return _require_non_blank(value, info.field_name) @field_validator("port") @classmethod def _validate_port(cls, value: int) -> int: if isinstance(value, bool) or not isinstance(value, int): raise ValueError("port must be an integer, not bool") if value < 0 or value > 65535: raise ValueError("port must be between 0 and 65535") return value def config_from_env() -> ServiceConfig: """Load ServiceConfig from environment variables.""" raw_port = os.getenv("PORT", "8080").strip() try: parsed_port = int(raw_port) except ValueError as exc: raise ValueError(f"Invalid PORT value: {raw_port!r}") from exc return ServiceConfig( service_name=os.getenv("SERVICE_NAME", "northwind-triage"), environment=os.getenv("APP_ENV", "development"), host=os.getenv("HOST", "0.0.0.0"), port=parsed_port, ) def default_readiness_check() -> tuple[bool, str]: """Check readiness based on READY_FLAG environment setting.""" raw_flag = os.getenv("READY_FLAG", "true").strip().lower() if raw_flag in {"1", "true", "yes", "on"}: return True, "ready" return False, "dependency or startup check not ready" def render_status_html(config: ServiceConfig, ready: bool, detail: str) -> str: """Render a minimal HTML page with all dynamic values HTML-escaped.""" badge = "READY" if ready else "NOT READY" service_name = html.escape(config.service_name) environment = html.escape(config.environment) safe_detail = html.escape(str(detail)) return ( '<!doctype html><html lang="en"><head><meta charset="utf-8">' f"<title>{service_name} Status</title></head><body>" f"<h1>{service_name}</h1>" f"<p>Environment: {environment}</p>" f"<p>Readiness: <strong>{badge}</strong> ({safe_detail})</p>" "</body></html>" ) def _safe_readiness_check(readiness_fn: ReadinessCheckFn) -> tuple[bool, str]: """Convert readiness-check exceptions into a controlled not-ready result.""" try: ready, detail = readiness_fn() return bool(ready), str(detail) except Exception: # Avoid exposing exception details that may contain secrets or internals. return False, "readiness check failed" def create_handler_class( config: ServiceConfig, readiness_fn: ReadinessCheckFn = default_readiness_check, ) -> type[BaseHTTPRequestHandler]: """Create an HTTP handler bound to config and a readiness check function.""" class ServiceHandler(BaseHTTPRequestHandler): def _send_json(self, status_code: int, payload: dict[str, object]) -> None: body = json.dumps(payload).encode("utf-8") self.send_response(status_code) self.send_header("Content-Type", "application/json; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def _send_html(self, status_code: int, html: str) -> None: body = html.encode("utf-8") self.send_response(status_code) self.send_header("Content-Type", "text/html; charset=utf-8") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) def do_GET(self) -> None: path = urlparse(self.path).path if path == "/health": self._send_json( 200, {"status": "ok", "service": config.service_name}, ) return if path == "/ready": ready, detail = _safe_readiness_check(readiness_fn) code = 200 if ready else 503 self._send_json( code, { "ready": bool(ready), "service": config.service_name, "detail": detail, }, ) return if path == "/": ready, detail = _safe_readiness_check(readiness_fn) page = render_status_html(config, ready, detail) self._send_html(200, page) return self._send_json(404, {"error": "not_found", "path": path}) def log_message(self, format: str, *args: object) -> None: return return ServiceHandler def create_server( config: ServiceConfig, readiness_fn: ReadinessCheckFn = default_readiness_check, ) -> ThreadingHTTPServer: """Instantiate a ThreadingHTTPServer for the service.""" handler_cls = create_handler_class(config, readiness_fn=readiness_fn) return ThreadingHTTPServer((config.host, config.port), handler_cls) def main() -> None: """Run the HTTP server using environment configuration.""" config = config_from_env() server = create_server(config, readiness_fn=default_readiness_check) try: server.serve_forever() finally: server.server_close() if __name__ == "__main__": main() - Write a multi-stage non-root
Dockerfile:# syntax=docker/dockerfile:1 FROM python:3.11-slim AS builder WORKDIR /app COPY pyproject.toml ./ COPY src ./src RUN pip install --no-cache-dir --upgrade pip \ && pip install --no-cache-dir --prefix=/install . FROM python:3.11-slim AS runtime ENV PYTHONDONTWRITEBYTECODE=1 \ PYTHONUNBUFFERED=1 \ PYTHONPATH=/install/lib/python3.11/site-packages \ PATH="/install/bin:${PATH}" \ PORT=8080 \ SERVICE_NAME=northwind-triage \ APP_ENV=production \ READY_FLAG=true WORKDIR /app RUN groupadd --system --gid 10001 appgroup \ && useradd --system --uid 10001 --gid 10001 --no-create-home appuser COPY --from=builder /install /install USER appuser EXPOSE 8080 CMD ["python", "-m", "fde_04_2.service"] - Add unit and HTTP probe tests in
tests/test_service.py:"""Tests for /health, /ready, status UI, and service configuration.""" from __future__ import annotations from contextlib import contextmanager import json import threading import urllib.error import urllib.request import pytest from pydantic import ValidationError from fde_04_2.service import ServiceConfig, config_from_env, create_server def _get_json(url: str) -> tuple[int, dict[str, object]]: try: with urllib.request.urlopen(url, timeout=2.0) as resp: return resp.status, json.loads(resp.read().decode("utf-8")) except urllib.error.HTTPError as exc: return exc.code, json.loads(exc.read().decode("utf-8")) def _get_html(url: str) -> tuple[int, str]: with urllib.request.urlopen(url, timeout=2.0) as resp: return resp.status, resp.read().decode("utf-8") @contextmanager def _running_service(config: ServiceConfig, readiness_fn): server = create_server(config, readiness_fn=readiness_fn) port = server.server_address[1] thread = threading.Thread(target=server.serve_forever, daemon=True) thread.start() try: yield f"http://127.0.0.1:{port}" finally: server.shutdown() thread.join(timeout=2.0) server.server_close() def test_health_ready_and_ui_endpoints() -> None: config = ServiceConfig(service_name="northwind-triage", host="127.0.0.1", port=0) with _running_service(config, readiness_fn=lambda: (True, "all checks green")) as base_url: health_code, health_body = _get_json(f"{base_url}/health") assert health_code == 200 assert health_body["status"] == "ok" ready_code, ready_body = _get_json(f"{base_url}/ready") assert ready_code == 200 assert ready_body["ready"] is True html_code, html_text = _get_html(f"{base_url}/") assert html_code == 200 assert "northwind-triage" in html_text assert "READY" in html_text def test_ready_returns_503_when_not_ready_while_health_stays_200() -> None: config = ServiceConfig(service_name="northwind-triage", host="127.0.0.1", port=0) with _running_service(config, readiness_fn=lambda: (False, "warming index")) as base_url: health_code, _ = _get_json(f"{base_url}/health") assert health_code == 200 ready_code, ready_body = _get_json(f"{base_url}/ready") assert ready_code == 503 assert ready_body["ready"] is False assert "warming index" in str(ready_body["detail"]) def test_rejects_boolean_or_out_of_range_port() -> None: with pytest.raises(ValidationError): ServiceConfig(port=True) # type: ignore[arg-type] with pytest.raises(ValidationError): ServiceConfig(port=-1) with pytest.raises(ValidationError): ServiceConfig(port=70000) def test_status_ui_escapes_untrusted_dynamic_values() -> None: config = ServiceConfig( service_name='<script>alert("x")</script>', environment='<img src=x onerror=alert(1)>', host="127.0.0.1", port=0, ) with _running_service( config, readiness_fn=lambda: (False, '<svg onload="alert(1)">unsafe</svg>'), ) as base_url: status, page = _get_html(f"{base_url}/") assert status == 200 assert "<script>" not in page assert "<img" not in page assert "<svg" not in page assert "<script>" in page assert "<img" in page assert "<svg" in page def test_readiness_exception_returns_503_and_health_stays_live() -> None: def broken_readiness(): raise RuntimeError("database password must not leak") config = ServiceConfig(host="127.0.0.1", port=0) with _running_service(config, readiness_fn=broken_readiness) as base_url: health_code, health_body = _get_json(f"{base_url}/health") ready_code, ready_body = _get_json(f"{base_url}/ready") assert health_code == 200 assert health_body["status"] == "ok" assert ready_code == 503 assert ready_body["ready"] is False assert ready_body["detail"] == "readiness check failed" assert "password" not in str(ready_body) def test_status_ui_handles_readiness_exception_safely() -> None: def broken_readiness(): raise RuntimeError("internal database details") config = ServiceConfig(host="127.0.0.1", port=0) with _running_service(config, readiness_fn=broken_readiness) as base_url: status, page = _get_html(f"{base_url}/") assert status == 200 assert "NOT READY" in page assert "readiness check failed" in page assert "internal database details" not in page def test_unknown_route_returns_json_404() -> None: config = ServiceConfig(host="127.0.0.1", port=0) with _running_service(config, readiness_fn=lambda: (True, "ready")) as base_url: status, body = _get_json(f"{base_url}/missing") assert status == 404 assert body["error"] == "not_found" def test_config_from_env_rejects_invalid_port(monkeypatch) -> None: monkeypatch.setenv("PORT", "not-a-port") with pytest.raises(ValueError, match="Invalid PORT"): config_from_env() def test_health_and_status_ui_content_types() -> None: config = ServiceConfig(host="127.0.0.1", port=0) with _running_service(config, readiness_fn=lambda: (True, "ready")) as base_url: with urllib.request.urlopen(f"{base_url}/health", timeout=2.0) as response: json_type = response.headers.get_content_type() with urllib.request.urlopen(f"{base_url}/", timeout=2.0) as response: html_type = response.headers.get_content_type() assert json_type == "application/json" assert html_type == "text/html" - Configure GitHub Actions test and Docker build pipeline in
.github/workflows/release.yml:name: Test and Docker Release-Build Validation on: push: pull_request: permissions: contents: read jobs: test-and-build: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v4 - name: Set up Python uses: actions/setup-python@v5 with: python-version: "3.11" - name: Install package and test dependencies run: | python -m pip install --upgrade pip python -m pip install -e ".[dev]" - name: Run unit tests run: python -m pytest -v - name: Build Docker image run: docker build -t fde-04-2:ci . - name: Smoke-test container health endpoints and non-root user run: | docker run -d --name fde-04-2-smoke -p 8080:8080 fde-04-2:ci trap 'docker rm -f fde-04-2-smoke >/dev/null 2>&1 || true' EXIT for attempt in $(seq 1 20); do if curl --fail --silent http://127.0.0.1:8080/health >/dev/null; then break fi sleep 1 done curl --fail http://127.0.0.1:8080/health curl --fail http://127.0.0.1:8080/ready test "$(docker exec fde-04-2-smoke id -u)" != "0"
3. Common Pitfalls and Operational Hygiene
- Conflating
/healthand/ready: Making/healthfail on temporary dependency slowdowns can trigger unnecessary container restarts, while making/readyalways return200can send live traffic before startup initialization finishes. - Trusting readiness callbacks and dynamic HTML values: Convert readiness exceptions into a controlled not-ready response without exposing internal exception details, and HTML-escape every dynamic value rendered in the operator page.
- Running container processes as
root: Always create a dedicated non-root user and switch to it withUSERbefore launching the application entrypoint. - Skipping image build and container smoke verification in CI: Unit tests alone do not catch broken
COPYpaths, missing runtime packages, or runtime startup failures. Build the image, start a container, and probe its HTTP endpoints.
4. Completion Criteria
ServiceConfig,create_server, andrender_status_htmlserve/health,/ready(200when ready,503when not ready), and the HTML status page.Dockerfileuses a multi-stage build and runs as a non-root user.python -m pytest -v,docker build, and the container smoke test (health/readiness HTTP probes plus non-root UID verification) succeed locally and in GitHub Actions, andfde-04-2is pushed to GitHub.
Build this
In fde-04-2, build a minimal Python HTTP service in src/fde_04_2/service.py (with /health liveness and /ready readiness endpoints and a lightweight status/demo HTML page), write a multi-stage Dockerfile running as a non-root user, add unit and HTTP handler tests in tests/test_service.py, and configure .github/workflows/release.yml.
- Implement
/health(liveness check confirming the process is responsive) and/ready(readiness check verifying required configuration and dependency state before accepting traffic). - Write a multi-stage
Dockerfilethat installs Python dependencies in a builder stage, copies only runtime artifacts into a slim runtime image, and runs the service as a dedicated non-root user. - Add
pytesttests intests/test_service.pycovering liveness, readiness when dependencies are ready vs. unready, and UI/API responses, and configure GitHub Actions to run tests and build the Docker image on push and pull requests.
Test your understanding
- What is the difference between a liveness check (
/health) and a readiness check (/ready) for an AI service? - Why use a multi-stage
Dockerfileand a non-root user for containerizing an application? - When should
/readyreturn a non-200 status code even if/healthreturns200 OK? - Why include a Docker build check alongside
pytestin your CI release pipeline?
Reveal self-review answers (attempt the questions first)
- Liveness vs. readiness: Liveness (
/health) checks whether the application process is alive and not deadlocked, whereas readiness (/ready) checks whether required config, models, or upstream dependencies are initialized enough to serve traffic safely. - Multi-stage builds and non-root users: Multi-stage builds keep compilers, build caches, and temporary artifacts out of the final runtime image, while running as a non-root user limits container breakout blast radius if a vulnerability is exploited.
- When readiness fails while liveness passes: If the web process is running normally but required configuration is missing or a critical downstream dependency is not ready,
/readyshould fail so load balancers or orchestrators hold traffic without restarting a healthy process unnecessarily. - Docker build in CI: Running
docker buildin CI catches brokenCOPYpaths, missing system libraries, incompatible base images, or permission issues before a release artifact is published.
Questions or notes on this module?