Skip to content

1. Capstone · Deliver a Python health service ​

Home · Full index · Troubleshooting

Build this in a separate scratch repository. Copy each named block into the path shown. The service has no third-party dependencies, so you can verify the application and runner before introducing uv, caching or package registries. The repository that holds this guide contains Markdown only.

1.1 Create the service and tests ​

app.py

python
import argparse
import json
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer


def response_for(path):
    if path == "/healthz":
        return 200, {"status": "ok"}
    if path == "/readyz":
        return 200, {"ready": True}
    return 404, {"error": "not found"}


class HealthHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        status, payload = response_for(self.path)
        body = json.dumps(payload).encode("utf-8")
        self.send_response(status)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--bind", default="127.0.0.1")
    parser.add_argument("--port", type=int, default=8080)
    args = parser.parse_args()
    with ThreadingHTTPServer((args.bind, args.port), HealthHandler) as server:
        server.serve_forever()


if __name__ == "__main__":
    main()

test_app.py

python
import json
import threading
import unittest
from http.server import ThreadingHTTPServer
from urllib.error import HTTPError
from urllib.request import urlopen

from app import HealthHandler


class HealthTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        server = ThreadingHTTPServer(("127.0.0.1", 0), HealthHandler)
        cls.addClassCleanup(server.server_close)
        worker = threading.Thread(target=server.serve_forever, daemon=True)
        worker.start()
        cls.addClassCleanup(worker.join, 3)
        cls.addClassCleanup(server.shutdown)
        cls.base_url = f"http://127.0.0.1:{server.server_port}"

    def test_health(self):
        with urlopen(f"{self.base_url}/healthz", timeout=3) as response:
            self.assertEqual(response.status, 200)
            self.assertEqual(json.load(response), {"status": "ok"})

    def test_ready(self):
        with urlopen(f"{self.base_url}/readyz", timeout=3) as response:
            self.assertEqual(response.headers.get_content_type(), "application/json")
            self.assertEqual(json.load(response), {"ready": True})

    def test_unknown_route(self):
        with self.assertRaises(HTTPError) as caught:
            urlopen(f"{self.base_url}/missing", timeout=3)
        with caught.exception as response:
            self.assertEqual(response.code, 404)
            self.assertEqual(json.load(response), {"error": "not found"})


if __name__ == "__main__":
    unittest.main()

Run python3 -m unittest -v from the repository root. Expect three passing tests. This is a teaching HTTP server. Keep it inside the lab.

1.2 Verify in Gitea first ​

.gitea/workflows/health-ci.yml

yaml
name: Gitea health service CI
on: [push, pull_request]
jobs:
  syntax:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
      - run: python3 -m py_compile app.py test_app.py
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
      - run: python3 -m unittest -v
  gate:
    needs: [syntax, test]
    runs-on: ubuntu-latest
    steps:
      - run: echo "Syntax and HTTP checks passed"

The job image needs Git, a checkout-compatible Node runtime and Python 3. Push this to a disposable branch and save one successful run. Then edit test_ready to expect False. The HTTP test job should fail and the gate should be skipped. Restore the test and capture the passing run.

1.3 Containerize and smoke-test ​

Dockerfile

dockerfile
FROM python:3.12-slim
WORKDIR /app
COPY app.py .
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
USER 10001:10001
EXPOSE 8080
CMD ["python", "app.py", "--bind", "0.0.0.0", "--port", "8080"]

Run docker build --tag app:ci . and use B02. Change the endpoint path once to see a failing smoke test and verify that the container disappears. For a durable release pipeline, review and pin a base-image digest.

1.4 Publish the image that passed smoke tests ​

.github/workflows/health-release.yml

yaml
name: Health service release
on:
  pull_request:
    branches: [main]
  push:
    branches: [main]
permissions:
  contents: read
jobs:
  test:
    runs-on: ubuntu-latest
    timeout-minutes: 10
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
      - uses: actions/setup-python@v5
        with:
          python-version: '3.12'
      - run: python -m unittest -v
  publish:
    needs: test
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    timeout-minutes: 15
    permissions:
      contents: read
      packages: write
    steps:
      - uses: actions/checkout@v4
        with:
          persist-credentials: false
      - name: Build and smoke-test
        id: candidate
        shell: bash
        run: |
          set -euo pipefail
          image="ghcr.io/${GITHUB_REPOSITORY,,}:$GITHUB_SHA"
          docker build --tag "$image" .
          container_id=$(docker run --detach --publish 127.0.0.1::8080 "$image")
          trap 'docker rm -f "$container_id" >/dev/null' EXIT
          endpoint=$(docker port "$container_id" 8080/tcp)
          if ! curl --fail --silent --show-error \
            --connect-timeout 2 --max-time 3 --retry 8 --retry-delay 1 --retry-all-errors \
            "http://$endpoint/readyz" |
            python3 -c 'import json, sys; assert json.load(sys.stdin)["ready"] is True'; then
            docker logs "$container_id"
            exit 1
          fi
          printf 'image=%s\n' "$image" >> "$GITHUB_OUTPUT"
      - uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}
      - name: Push and record digest
        env:
          IMAGE: ${{ steps.candidate.outputs.image }}
        shell: bash
        run: |
          set -euo pipefail
          docker push "$IMAGE"
          repository="${IMAGE%:*}"
          reference=$(docker image inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' "$IMAGE" |
            awk -v prefix="$repository@" 'index($0, prefix) == 1 { print; exit }')
          digest="${reference##*@}"
          [[ "$digest" =~ ^sha256:[a-f0-9]{64}$ ]]
          printf 'Published %s\n' "$reference" >> "$GITHUB_STEP_SUMMARY"

First try a PR and check that the publish job is skipped. Protect main and configure GHCR package write access before merging. On a passing main push, save the full digest reference from the summary. GHCR image visibility and permissions are package settings. Use cluster pull credentials if the package is private.

1.5 Bootstrap disposable staging ​

k8s/staging.yaml

Replace the placeholder image with the first tested digest. Create the disposable staging namespace before applying the file. Use a cluster that can run the image's architecture and pull from the registry. The hosted runner builds an amd64 image in this example.

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: health-api
  namespace: staging
spec:
  replicas: 1
  revisionHistoryLimit: 3
  progressDeadlineSeconds: 120
  selector:
    matchLabels:
      app: health-api
  template:
    metadata:
      labels:
        app: health-api
    spec:
      automountServiceAccountToken: false
      securityContext:
        seccompProfile:
          type: RuntimeDefault
      containers:
        - name: app
          image: ghcr.io/example/health-api@sha256:0000000000000000000000000000000000000000000000000000000000000000
          ports:
            - name: http
              containerPort: 8080
          securityContext:
            runAsNonRoot: true
            allowPrivilegeEscalation: false
            readOnlyRootFilesystem: true
            capabilities:
              drop: [ALL]
          resources:
            requests:
              cpu: 25m
              memory: 32Mi
            limits:
              cpu: 250m
              memory: 64Mi
          readinessProbe:
            httpGet:
              path: /readyz
              port: http
          livenessProbe:
            httpGet:
              path: /healthz
              port: http
---
apiVersion: v1
kind: Service
metadata:
  name: health-api
  namespace: staging
spec:
  selector:
    app: health-api
  ports:
    - name: http
      port: 8080
      targetPort: http

From a shell pointing at the lab cluster, use D01. Then apply kubectl apply -f k8s/staging.yaml and run kubectl -n staging rollout status deployment/health-api --timeout=180s. In a separate terminal run kubectl -n staging port-forward service/health-api 18080:8080. Use D04 with STAGING_URL=http://127.0.0.1:18080.

1.6 Promote and prove recovery ​

  1. Record the running digest as the known-good image.
  2. Make a small source change, test it and get a second digest from the trusted publish job.
  3. Deploy the second digest using D02 if your hosted runner can reach staging. For an isolated homelab, run the equivalent kubectl -n staging set image deployment/health-api app="$NEW_IMAGE" from your local staging context, then wait for rollout.
  4. Run the smoke test and record the timings and response.
  5. Test D05 with the first digest. Compare the live image and retest application behavior. Restart a port-forward if its backing Pod was replaced.
EvidenceInclude
Gate failureDeliberate test failure and skipped publish or gate
Successful buildCommit SHA, test status and smoke-test output
Image promotionPrevious digest, new digest and verified rollout
RecoveryRestored digest and successful readiness response

Keep the write-up brief and label this as a lab deployment.