Zum Inhalt springen

Lektion 25 · Projects

Final project: ship and monitor a small service

Take a small service from Git to containers, CI, a deployment description and monitoring on your own computer, with Python checkpoints and a rubric.

Kestrel Crate Co. is a fictional delivery company. A small internal service answers one question: where is this parcel? It runs on one developer's laptop. Nobody knows how to rebuild it, and the team learns about failures only when someone complains. Your job is to make it repeatable and observable.

By the end, you will have a repository that builds and checks the service automatically, runs it in a container, describes how to deploy it to a local cluster and shows its health in Prometheus and Grafana. You will also break it on purpose, watch an alert fire and write down how to recover. The company and all parcel data are invented.

The Python checkpoints run in your browser and practice the logic behind monitoring. They only compare printed results. The site cannot grade your project, and it does not run Docker, CI, Kubernetes or Prometheus. Do those parts with real tools on your own computer.

What you need first

This project joins the steps of the DevOps Engineer path:

You need Docker with Compose, Git and Python. For the deployment milestone, use a local cluster tool such as kind or minikube. CI needs a repository on a hosting service. A private one is a sensible choice, and you should check its current free limits first. You do not need a paid cloud account.

The brief

  1. The service has three routes: /parcels/{id} returns invented parcel data or 404, /health returns 200, and /metrics returns Prometheus metrics.
  2. Each request writes one log line to standard output, without personal data.
  3. Metrics include a request counter labeled by route and status, and a request duration histogram.
  4. Automated tests run with one command.
  5. The container runs as a non-root user and uses a version tag you choose.
  6. CI runs the tests, builds the image and checks that the container answers.
  7. A deployment description defines replicas, health probes and resource requests.
  8. Compose starts the service, Prometheus and Grafana together.
  9. At least two alerts exist: service unreachable and high error ratio.
  10. A runbook explains each alert, and you have tested both. No secrets are in Git.

Milestones

1. Start with a repository you can trust

Write the service in any language you know. In Python, you can use the official prometheus_client library for metrics. Keep a few parcels in a JSON file. Add a failure switch for practice: when the environment variable FAIL_MODE is 1, parcel requests return 500 while the other routes keep working. It must be off by default. Add tests, a .gitignore and a README, then commit.

Why: every later step starts from this repository. A safe failure switch lets you test alerts without damaging anything.

Hint: use the route pattern /parcels/{id} as a metric label, never the actual address. Group unknown paths under one label. Each new label value creates another time series.

Done when: a fresh clone passes its tests by following only the README.

Checkpoint 1. Logs help you explain what a metric shows. Parse a simple log format and skip damaged lines.

Python Parse a log line

Your task: Write parse_line(line). A valid line has exactly four fields separated by spaces: method, path, status and duration. Status is digits only, from 100 to 599. Duration is digits followed by ms. Return the tuple (method, path, status, duration) with status and duration as integers. Return None for any other line. Extra whitespace around or between fields is allowed.

Hint

Check the number of fields before unpacking them, and check text before converting it.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

def parse_line(line):
    parts = line.split()
    if len(parts) != 4:
        return None
    method, path, status, duration = parts
    number = duration[:-2]
    if not duration.endswith("ms"):
        return None
    if not all(text and text.isascii() and text.isdigit() for text in (status, number)):
        return None
    if not 100 <= int(status) <= 599:
        return None
    return (method, path, int(status), int(number))

2. Put the service in a container

Write a Dockerfile with a specific base image tag, copy only what the program needs and switch to a non-root user. Install dependencies from a file with pinned versions. Make the server listen on 0.0.0.0 inside the container. Add a .dockerignore. Publish the port only to your own computer, for example -p 127.0.0.1:8000:8000.

Why: the same image can run in CI, in Compose and in your local cluster.

Hint: make sure the program stops cleanly when Docker sends SIGTERM.

Done when: you can build from a clean clone, call all three routes and read request logs with docker logs.

3. Let CI check every change

Create a workflow that runs on pushes and pull requests. This outline assumes unittest tests in a tests folder, that tests need your requirements.txt and that the service uses port 8000. Adapt it to your project. Check the current major versions of the actions you use.

YAML
name: ci
on: [push, pull_request]
permissions:
  contents: read
jobs:
  check:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - run: python3 -m pip install -r requirements.txt
      - run: python3 -m unittest discover -s tests
      - run: docker build -t tracker:ci .
      - run: docker run -d --name tracker -p 127.0.0.1:8000:8000 tracker:ci
      - run: curl --fail --retry 10 --retry-delay 2 --retry-all-errors http://127.0.0.1:8000/health
      - if: failure()
        run: docker logs tracker

Why: a smoke test catches an image that builds but cannot start.

Hint: break a test on a branch and confirm that the workflow turns red. A check that has never failed has not been proven.

Done when: a good change passes and a deliberately broken one fails with a useful message.

This pipeline integrates and checks. It does not deploy to your laptop, because hosted runners cannot reach it. Your deployment in this project is a command you run yourself.

4. Describe the deployment

Write Kubernetes manifests for a Deployment and a Service. Ask for two replicas. Add readiness and liveness probes on /health, CPU and memory requests, a memory limit and a security setting that requires a non-root user. If your image names its user by text, also set a numeric user id. Use a versioned image name such as tracker:1.0.0. With kind, load the local image with kind load docker-image. Other tools have their own loading steps.

Then practice Terraform on one small resource that you can safely destroy, such as the cluster namespace through the Kubernetes provider. Pin the provider version, point it at your local cluster context, read the plan and then apply it. Commit the lock file, but never commit state files.

Why: a written description can be reviewed, repeated and compared with what is running.

Hint: check your current cluster context before every kubectl apply or terraform apply.

Done when: you can delete the local deployment, recreate it from the repository, update to a new tag and roll back.

5. Monitor it

Add Prometheus and Grafana to a Compose file next to your service. This monitors the Compose copy, which keeps the setup simple. Give the images specific version tags, publish ports on 127.0.0.1 and set a Grafana admin password through an ignored .env file. If your service is named tracker, Prometheus can scrape tracker:8000.

Define the alerts in a rules file, and list that file under rule_files in the Prometheus configuration. These examples assume the job name tracker and the counter http_requests_total:

YAML
groups:
  - name: tracker
    rules:
      - alert: TrackerDown
        expr: up{job="tracker"} == 0
        for: 1m
      - alert: TrackerHighErrorRatio
        expr: |
          sum(rate(http_requests_total{job="tracker", status=~"5.."}[5m]))
            / sum(rate(http_requests_total{job="tracker"}[5m])) > 0.05
        for: 2m

Health checks and scrapes can hide parcel failures if you count them, because many successful requests lower the ratio. Count only parcel routes, or filter by route in both parts of the division. Build a dashboard with request rate, error ratio and 95th percentile duration. Prometheus shows alert states on its own. Sending notifications needs Alertmanager, which is an extension here.

Why: a useful alert reflects trouble that users notice and lasts long enough to deserve attention.

Hint: run promtool check config and promtool check rules before restarting.

Done when: the target is up and the graphs change when you send requests.

Checkpoint 2. Calculate an error ratio and handle the case with no traffic.

Python Error ratio

Your task: Write error_ratio(counts). counts is a dictionary from integer status code to number of requests. Return the share of requests with status 500 to 599, rounded to 4 decimal places. Return None when the total number of requests is 0.

Hint

Add up every status in the 500 range, not only 500.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

def error_ratio(counts):
    total = sum(counts.values())
    if total == 0:
        return None
    errors = sum(number for status, number in counts.items() if 500 <= status <= 599)
    return round(errors / total, 4)

Checkpoint 3. A histogram stores cumulative counts. You can find which bucket contains a percentile.

Python Find the percentile bucket

Your task: Write percentile_bucket(buckets, percent). buckets is a list of (upper_bound, cumulative_count) pairs sorted by bound, and the last count is the total. percent is an integer from 1 to 100. Return the first upper bound whose count is at least percent percent of the total. Compare with integers: count * 100 >= total * percent. Return None for an empty list or a total of 0.

Hint

Walk through the buckets in order and return at the first one that is large enough.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

def percentile_bucket(buckets, percent):
    if not buckets or buckets[-1][1] == 0:
        return None
    total = buckets[-1][1]
    for bound, count in buckets:
        if count * 100 >= total * percent:
            return bound

This returns a bucket boundary only. PromQL's histogram_quantile goes further and estimates a value inside the bucket, so your numbers can differ.

6. Break it, watch it, recover

Send a steady stream of requests with a short script aimed only at your own local service. Turn on FAIL_MODE and recreate the service container. Watch the error alert move from inactive to pending to firing. Turn the switch off and watch it recover. Then stop the service to test the unreachable alert. Record the times. The error alert will not follow the failure instantly, because it looks at a time window.

For each alert, write a runbook entry: what it means, how to confirm it, which logs and graphs to check, how to recover and how to know recovery worked.

Why: until you see an alert fire, you cannot know that it works.

Hint: keep traffic running during recovery. With no requests, a ratio gives you no useful evidence that the service works again.

Done when: you have tested both alerts, followed your own runbook and fixed any unclear step.

Checkpoint 4. Model how a hold time delays an alert. This is a simplified version of the idea behind for, counted in evaluations instead of time.

Python Alert states

Your task: Write alert_states(values, threshold, hold). For each value, in order, add one state to a list and return the list. A value breaches when it is not None and is strictly greater than threshold. A value that does not breach gives inactive and resets the streak. A breaching value gives firing when the current streak of breaches is at least hold long, otherwise pending. hold is 1 or more.

Hint

Keep a counter that grows on each breach and returns to zero otherwise.

Press Run (or Ctrl + Enter) to see the result here.

✅ Correct. Your result matches. ❌ Not yet. Check the output and try again. The answer could not be checked. Please try again.

Expected result


        

One possible solution

def alert_states(values, threshold, hold):
    states = []
    streak = 0
    for value in values:
        if value is not None and value > threshold:
            streak += 1
            states.append("firing" if streak >= hold else "pending")
        else:
            streak = 0
            states.append("inactive")
    return states

Check your work

Criterion What good looks like
Repository A fresh clone works from the README; no secrets, state files or build output
Container Specific tags, non-root user, small build context, clean stop
CI Tests and smoke test run on changes, and you have seen them fail correctly
Deployment Can be recreated, updated and rolled back; probes and resources are set
Monitoring Labels have limited values; graphs show traffic, errors and duration
Alerts Both were triggered on purpose and cleared after recovery
Documentation The runbook has exact checks and a way to confirm recovery

Common mistakes

Do not use parcel ids, user ids or full addresses as metric labels. The number of time series can grow without limit and strain Prometheus. Never put secrets or personal data in labels or logs.

An error ratio cannot report everything. With no traffic or no scrape, it may show no result. Keep the separate up alert. Also know that up cannot alert when the scrape target disappears from the configuration, and Prometheus cannot report its own total outage.

Take it further

  • Add Alertmanager and send notifications to a local test receiver.
  • Provision your Grafana data source and dashboard from files.
  • Add an alert for slow requests and justify its threshold.
  • Run Prometheus inside your cluster so it monitors the Kubernetes copy.

Check your understanding

Quick check · 5 questions

of 5 answered You scored / 5 · perfect!

  1. 1. Why does CI start the container after building it?

    A smoke test finds problems such as a missing file, a bad command or the wrong listening address.
  2. 2. Which is a poor metric label?

    Every new id creates more time series.
  3. 3. What does for: 2m do in an alert rule?

    The alert is pending during this time. The query range is set separately.
  4. 4. What is the best evidence that an alert works?

    A syntax check cannot show that metric names, labels and thresholds match your real system.
  5. 5. What should you do with Terraform state files in this project?

    State needs protection, but Terraform also needs it to track resources, so do not delete it casually.

Summary

  • Start from a tested repository and build a repeatable container.
  • Make CI prove that the image starts, and watch it fail once.
  • Describe deployments in files and check the cluster context before applying.
  • Measure traffic, errors and duration with labels that have limited values.
  • Trigger every alert safely, then improve its runbook.
  • Remember what your local setup does not prove: production security, scale and availability.

Back to the path: DevOps Engineer learning path

Verfolge deinen Fortschritt

Erstelle ein kostenloses Konto, hake Lektionen ab und mach auf jedem Gerät dort weiter, wo du aufgehört hast.