Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 3 of 6 · Lab · 30 min · revision 2

Lab: Deploy Behind a Custom Domain with HTTPS and Health Checks

Add liveness, readiness and version routes to the notes API, build an image tagged with its Git SHA and version, push it to a registry and deploy it by digest with Docker Compose behind Caddy, which serves HTTPS for a domain name and routes only to a ready instance; then see what changes for a real domain and a managed platform.

Contentsand lesson path

What you will learn

  • Package a service or web app as a versioned, immutable artifact (for example a container image or a static bundle) for a target platform.
  • Expose health and readiness checks and release a new version with zero downtime (rolling, blue-green or canary), then roll back a bad release.

Prerequisites: Containerization

01. Goal and setup

You will deploy the notes API the way a small production service runs: a versioned image pulled from a registry by digest, configured from the environment, with its secret mounted as a file, behind a reverse proxy that serves HTTPS for a domain name and routes only to a ready instance. Everything runs locally; step 7 covers a real domain.

You need Docker Engine 25 or later with the Compose plugin (Docker Desktop includes both), curl, and the notes-api folder from lesson 2 with its virtual environment active. Ports 5000, 8080 and 8443 must be free. The lab was tested with Docker Engine 29.8, Compose 5.5, Caddy 2.11.7, registry:3.1.2, python:3.12-slim, FastAPI 0.146 and uvicorn 0.54; the images need about 400 MB of disk. The finished folder:

Folder layout
notes-api/
├── app/
│   ├── __init__.py
│   ├── main.py          health, readiness and version routes
│   ├── probe.py         the container's health check
│   └── settings.py      from lesson 2
├── caddy/Caddyfile      the reverse proxy
├── config/prod.env      non-secret production settings
├── secrets/             ignored by Git; holds llm_api_key from lesson 2
├── compose.yaml
├── Dockerfile
├── .dockerignore
└── requirements.txt
Terminal
cd notes-api
python -m pip install "fastapi==0.146.0" "uvicorn==0.54.0"
Expected output (last line, shortened; other packages are listed too)
Successfully installed ... fastapi-0.146.0 ... uvicorn-0.54.0

02. Step 1: Add liveness, readiness and version routes

Create app/main.py. It reuses get_settings() from lesson 2:

Python · app/main.py
import logging
import os
import time
from contextlib import asynccontextmanager
from pathlib import Path

from fastapi import FastAPI, Query, Request, Response
from fastapi.responses import JSONResponse

from app.settings import get_settings

VERSION = os.environ.get("APP_VERSION", "dev")  # set at build time, see the Dockerfile
GIT_SHA = os.environ.get("GIT_SHA", "unknown")
DRAIN_FLAG = Path("/tmp/drain")  # touch this file to take the instance out of rotation

log = logging.getLogger("notes")
ready_at = float("inf")

NOTES = [
    {"id": 1, "title": "Rotate the staging key", "tags": ["ops", "security"]},
    {"id": 2, "title": "Pin the base image", "tags": ["build"]},
    {"id": 3, "title": "Write the rollback runbook", "tags": ["ops"]},
    {"id": 4, "title": "Add a readiness check", "tags": ["reliability"]},
    {"id": 5, "title": "Ideas for next quarter", "tags": []},
]


@asynccontextmanager
async def lifespan(app: FastAPI):
    global ready_at
    settings = get_settings()  # invalid configuration stops the process here
    logging.basicConfig(level=settings.log_level, format="%(levelname)s %(message)s")
    ready_at = time.monotonic() + settings.warmup_seconds
    log.info("starting version=%s sha=%s env=%s", VERSION, GIT_SHA, settings.app_env)
    yield
    log.info("stopping version=%s", VERSION)


app = FastAPI(title="Notes API", lifespan=lifespan)


@app.middleware("http")
async def tag_version(request: Request, call_next):
    try:
        response = await call_next(request)
    except Exception:
        log.exception("unhandled error on %s %s", request.method, request.url.path)
        response = JSONResponse({"detail": "Internal Server Error"}, status_code=500)
    response.headers["X-App-Version"] = VERSION
    return response


@app.get("/livez")
def livez() -> dict[str, str]:
    return {"status": "alive"}  # the process answers; nothing else is checked


@app.get("/readyz")
def readyz(response: Response) -> dict[str, object]:
    problems = []
    if time.monotonic() < ready_at:
        problems.append("warming up")
    if DRAIN_FLAG.exists():
        problems.append("draining")
    if problems:
        response.status_code = 503
        return {"status": "not ready", "problems": problems}
    return {"status": "ready"}


@app.get("/version")
def version() -> dict[str, str]:
    return {"version": VERSION, "git_sha": GIT_SHA}


@app.get("/api/notes")
def list_notes(limit: int = Query(default=5, ge=1, le=50)) -> list[dict]:
    return NOTES[:limit]
  • /livez answers whenever the process can handle a request. Platforms that restart instances, such as Kubernetes, read a failed liveness check as restart me, so keep it trivial: if it called the model provider, an outage there would get every instance restarted, which fixes nothing.
  • /readyz answers should I get traffic now? It returns 503 while the instance warms up (WARMUP_SECONDS stands in for loading a model or an index) and while it drains before shutdown (the /tmp/drain flag). It may also test a dependency the instance cannot work without, but if every instance shares it, all of them turn unready together.
  • /version reports the version and commit baked into the image at build time.
  • The middleware adds X-App-Version to every response, including the 500 it returns for an unhandled error, which it logs at ERROR. Lab 4 uses both.

Docker runs a health check as a command inside the container. Add app/probe.py, which exits with status 1 unless /readyz answers 200:

Python · app/probe.py
"""Exit 0 if this instance is ready; the Dockerfile HEALTHCHECK runs it."""

import sys
import urllib.request

try:
    urllib.request.urlopen("http://127.0.0.1:8000/readyz", timeout=2)
except Exception:  # connection refused, timeout or a 503 from /readyz
    sys.exit(1)

Try the routes locally. In terminal 1, start the app on any free port with a ten-second warm-up; the .env file from lesson 2 supplies the other settings:

Terminal 1
WARMUP_SECONDS=10 uvicorn app.main:app --port 8010
Terminal 2
for path in livez readyz version; do curl -s -w '\n' "http://127.0.0.1:8010/$path"; done
sleep 10; curl -s -w '\n' http://127.0.0.1:8010/readyz
Expected output in terminal 2
{"status":"alive"}
{"status":"not ready","problems":["warming up"]}
{"version":"dev","git_sha":"unknown"}
{"status":"ready"}

Alive at once, ready ten seconds later, and dev because no build has set the version yet. Stop the server with Ctrl+C.

03. Step 2: Build a versioned image

Pin the runtime dependencies, keep local files out of the build context and write the Dockerfile. The containerization skill covered the instructions; what is new is the pinned base image and the build metadata:

requirements.txt
fastapi==0.146.0
pydantic==2.14.1
pydantic-settings==2.16.0
uvicorn==0.54.0
.dockerignore
.git
.env
.venv/
__pycache__/
secrets/
config/
caddy/
*.crt
Dockerfile
# Pin the base image by digest so a rebuild cannot pick up different layers.
ARG BASE_DIGEST=sha256:a6e34c598f2467ed0e9a8d349809fcd8b5c603269512df273a0bb1784edc11b1
FROM python:3.12-slim@${BASE_DIGEST}

ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
WORKDIR /srv
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app/ app/

# Build metadata: not secret, and the same in every environment.
ARG APP_VERSION=dev
ARG GIT_SHA=unknown
ENV APP_VERSION=${APP_VERSION} GIT_SHA=${GIT_SHA}
LABEL org.opencontainers.image.version=${APP_VERSION} \
      org.opencontainers.image.revision=${GIT_SHA}

USER 10001
EXPOSE 8000
HEALTHCHECK --interval=5s --timeout=2s --retries=2 \
            --start-period=30s --start-interval=1s \
  CMD ["python", "-m", "app.probe"]
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", \
     "--no-access-log"]
  • The base image is pinned by digest; get the current one with docker buildx imagetools inspect python:3.12-slim (yours will differ). requirements.txt pins the direct dependencies; for fully repeatable builds, pin the transitive ones too with a lock file, for example from uv pip compile --generate-hashes.
  • APP_VERSION and GIT_SHA become environment variables for /version and OCI labels. They are not secret and are the same in every environment, so baking them in is right, unlike lesson 2's settings.
  • .dockerignore keeps .env, secrets/ and the per-environment config/ folder out of the build context, so no COPY can pick them up.
  • The health check calls the readiness route, because plain Docker and Compose only report health and never restart a container for it. --start-interval (Docker Engine 25 and later) checks every second during start-up.

Commit, then build from that commit with two tags:

Terminal
echo 'caddy-root.crt' >> .gitignore
git add -A && git commit -qm "Health routes and container image"
SHA=$(git rev-parse --short HEAD)
docker build -t localhost:5000/notes-api:1.0.0 -t localhost:5000/notes-api:sha-$SHA \
  --build-arg APP_VERSION=1.0.0 --build-arg GIT_SHA=$SHA .
docker image ls localhost:5000/notes-api
docker image inspect localhost:5000/notes-api:1.0.0 --format '{{json .Config.Labels}}' \
  | python -m json.tool
Illustrative output (build log shortened; your SHA and image ID differ)
...
#10 naming to localhost:5000/notes-api:sha-abb14cc done
#10 DONE 1.2s
IMAGE                                  ID             DISK USAGE   CONTENT SIZE   EXTRA
localhost:5000/notes-api:1.0.0         f83ee4b0579d        203MB         48.9MB
localhost:5000/notes-api:sha-abb14cc   f83ee4b0579d        203MB         48.9MB
{
    "org.opencontainers.image.revision": "abb14cc",
    "org.opencontainers.image.version": "1.0.0"
}

One image ID, two names. The tags include the registry host, localhost:5000, because that is where they will be pushed. With the containerd image store, the default for new installations of recent Docker versions, the local ID equals the digest the registry will report; with the older store they differ, and only the registry digest counts.

04. Step 3: Push to a registry and pin the digest

Run a private registry locally and push both tags. Docker allows plain HTTP for registries on localhost; a real registry needs docker login and HTTPS, and the commands are otherwise the same.

Terminal
docker run -d --name local-registry -p 5000:5000 registry:3.1.2
docker push localhost:5000/notes-api:1.0.0
docker push localhost:5000/notes-api:sha-$SHA
export API_IMAGE=$(docker image inspect localhost:5000/notes-api:1.0.0 \
  --format '{{index .RepoDigests 0}}')
echo "$API_IMAGE"
Illustrative output (digests shortened; container ID and digests differ)
f93cbd84ea83e2fa2ec95f6facbce6348ff08457a5055b9f6e43d2dde32f78c6
...
1.0.0: digest: sha256:f83ee4b0579d276e… size: 856
...
sha-abb14cc: digest: sha256:f83ee4b0579d276e… size: 856
localhost:5000/notes-api@sha256:f83ee4b0579d276e5501eadcf952e2af10f39ebffca…

Both pushes report the same digest. API_IMAGE now holds the digest reference, and that, not a tag, is what you deploy: if someone pushes another image as 1.0.0 tomorrow, this deployment is unaffected. In CI, the digest comes from the build step's output and goes into the release record from lesson 1.

05. Step 4: Describe the deployment

The deployment combines the artifact with one environment's configuration. Create the non-secret production settings (the secret file secrets/llm_api_key exists from lesson 2), the Compose file and the proxy configuration:

config/prod.env
APP_ENV=prod
LOG_LEVEL=INFO
LLM_BASE_URL=https://llm.example.com
LLM_MODEL=claude-sonnet-5-5
WARMUP_SECONDS=5
YAML · compose.yaml
services:
  api:
    image: ${API_IMAGE:?set API_IMAGE to the image reference to deploy}
    env_file: config/prod.env
    secrets:
      - llm_api_key
    restart: unless-stopped

  proxy:
    image: caddy:2.11.7-alpine
    ports:
      - "8080:80"
      - "8443:443"
    volumes:
      - ./caddy:/etc/caddy:ro
      - caddy_data:/data
    depends_on:
      api:
        condition: service_healthy

secrets:
  llm_api_key:
    file: ./secrets/llm_api_key

volumes:
  caddy_data:
caddy/Caddyfile
{
	skip_install_trust
}

api.localhost {
	tls internal
	log {
		output stdout
		format json
	}
	reverse_proxy api:8000 {
		health_uri /readyz
		health_interval 2s
		health_timeout 1s
		lb_try_duration 5s
	}
}
  • ${API_IMAGE:?…} refuses to start without the digest reference instead of falling back to some default.
  • env_file supplies configuration and secrets mounts the key at /run/secrets/llm_api_key, where secrets_dir finds it. The API publishes no port, so only the proxy can reach it.
  • depends_on with service_healthy starts Caddy once the API's health check passes.
  • api.localhost is the domain name. tls internal issues its certificate from Caddy's own local authority, since no public authority can verify a name that exists only on your machine. health_uri makes Caddy call /readyz every 2 seconds and stop routing to an upstream that does not answer 200; lb_try_duration lets a request wait up to 5 seconds for a healthy upstream.
  • Caddy listens on ports 80 and 443 in its container, published as 8080 and 8443. The caddy_data volume keeps its certificates and authority across restarts.

Start everything and wait until it is healthy:

Terminal
docker compose up -d --wait
docker compose ps --format 'table {{.Service}}\t{{.Status}}'
docker compose logs api
Illustrative output (progress lines shortened; timings vary)
...
 Container notes-api-api-1 Waiting
 Container notes-api-api-1 Healthy
 Container notes-api-proxy-1 Started
 Container notes-api-proxy-1 Healthy
SERVICE   STATUS
api       Up 11 seconds (healthy)
proxy     Up 1 second
api-1  | INFO:     Started server process [1]
api-1  | INFO:     Waiting for application startup.
api-1  | INFO starting version=1.0.0 sha=abb14cc env=prod
api-1  | INFO:     Application startup complete.
api-1  | INFO:     Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)

--wait returned only after the warm-up and a passing health check. The log line shows which build runs and that the secret file and production settings validated; a missing or unreadable key would have stopped start-up, and up --wait would have failed.

06. Step 5: Reach the API over HTTPS

Your machine does not yet trust Caddy's local authority. Copy its root certificate out of the container, then call the API through the proxy, once over HTTPS and once over plain HTTP. Names under .localhost resolve to your own machine.

Terminal
docker compose cp proxy:/data/caddy/pki/authorities/local/root.crt caddy-root.crt
curl -i --cacert caddy-root.crt https://api.localhost:8443/version
echo
curl -i http://api.localhost:8080/version
curl -sS https://api.localhost:8443/version
Illustrative output (curl progress and some lines left out; dates differ)
HTTP/2 200
alt-svc: h3=":443"; ma=2592000
content-type: application/json
date: Mon, 19 Oct 2026 14:27:45 GMT
server: uvicorn
via: 1.1 Caddy
x-app-version: 1.0.0
content-length: 39

{"version":"1.0.0","git_sha":"abb14cc"}
HTTP/1.1 308 Permanent Redirect
Connection: close
Location: https://api.localhost/version
Server: Caddy
Date: Mon, 19 Oct 2026 14:27:45 GMT
Content-Length: 0

curl: (60) SSL certificate problem: unable to get local issuer certificate
More details here: https://curl.se/docs/sslcerts.html
  • With the root certificate, curl verified the chain and spoke HTTP/2 over TLS; via: 1.1 Caddy and server: uvicorn show the request passed through the proxy to the app.
  • Plain HTTP gets a permanent redirect to HTTPS. The Location has no port because Caddy assumes clients use the standard port 443, as they will on a real server.
  • Without the root certificate, curl refuses the connection (error 60), which is correct: an unverified certificate proves nothing. Never work around it with -k in scripts; trust the specific authority, as --cacert does.

07. Step 6: Watch readiness take an instance out of rotation

Put the instance into drain mode, as a platform does just before it stops an instance, and call the API through the proxy:

Terminal
docker compose exec api touch /tmp/drain
sleep 4
curl -i --cacert caddy-root.crt 'https://api.localhost:8443/api/notes?limit=1'
docker compose logs proxy --no-log-prefix --since 30s \
  | grep -oE 'status code out of tolerances|no upstreams available' | sort | uniq -c
docker compose exec api rm /tmp/drain
sleep 3
curl -s -w '\n' --cacert caddy-root.crt 'https://api.localhost:8443/api/notes?limit=1'
Illustrative output (counts and dates vary)
HTTP/2 503
alt-svc: h3=":443"; ma=2592000
server: Caddy
content-length: 0
date: Mon, 19 Oct 2026 14:28:02 GMT

      1 no upstreams available
      5 status code out of tolerances
[{"id":1,"title":"Rotate the staging key","tags":["ops","security"]}]

Within one check interval Caddy saw /readyz return 503 and took the only upstream out of rotation. The request waited 5 seconds (lb_try_duration) and then got a 503 from Caddy itself: server: Caddy, no x-app-version. Once the flag was gone, the next check passed and traffic flowed again, without a restart. With two or more instances, the same mechanism lets one drain or warm up while the others serve, which is how lab 4 switches versions while traffic keeps flowing.

08. Step 7: A real domain on a real server

On the internet, DNS must send the name to your server or platform, and the certificate must come from a public authority. These records are illustrative; the names and addresses are reserved for documentation:

DNS records (illustrative)
; zone example.com
api.example.com.   300  IN  A      203.0.113.10       ; your server's IPv4 address
api.example.com.   300  IN  AAAA   2001:db8::10       ; and its IPv6 address, if any
www.example.com.   300  IN  CNAME  notes-web.example.net.  ; a name a platform gave you
  • A and AAAA records map a name to an IP address: use them for a server you run.
  • A CNAME maps your name to another name: use it for a hostname a platform gives you, so the platform can change its addresses without you. The apex (example.com itself) cannot be a CNAME; use the platform's A records there, or your DNS provider's ALIAS, ANAME or CNAME-flattening feature.

On your own server, publish ports 80 and 443, use api.example.com as the site address and delete tls internal. Caddy then obtains and renews a certificate from Let's Encrypt or ZeroSSL by itself, provided the record points at the server, ports 80 and 443 are reachable from the internet and caddy_data persists. On a managed platform you add the domain in its settings, create the record it shows you, and it issues the certificate, usually within minutes. Either way, verify from outside:

Terminal (illustrative)
dig +short api.example.com
curl -sI https://api.example.com/readyz | head -1
curl -svo /dev/null https://api.example.com/readyz 2>&1 | grep -i 'issuer:'
Expected output (illustrative; the issuer depends on the authority used)
203.0.113.10
HTTP/2 200
*  issuer: C=US; O=Let's Encrypt; CN=<intermediate>

Leave the stack running for lab 4, which builds on it, or stop it with docker compose down.

09. Troubleshooting

10. Check your understanding

Practice check · 3 questions

Proxies, health checks and domains

Questions about the deployment you built in this lab.

Q1. Caddy's active health check gets 503 from /readyz on the only upstream. What does a client get?
Q2. A managed platform asks you to point api.example.com at notes-7f3k.example.net. Which record do you create?
Q3. Why does the Dockerfile HEALTHCHECK in this lab probe /readyz rather than /livez?
Practice only: not graded, not saved, not evidence.

11. Apply it: stretch tasks

Take your practice project live: deploy your image by digest, set configuration as environment variables and the secret as a reference to the platform's secret store, and point the platform's readiness check at /readyz and its liveness check, if any, at /livez. Add your custom domain, create the record it asks for, wait for the certificate, and save the curl -sI and issuer outputs from step 7 in your notes.

Stretch: add header Strict-Transport-Security "max-age=31536000" to the site block, and give /readyz a one-second check of a dependency your service cannot work without. Decide what readiness should do when every instance shares that dependency.

12. Review prompt

Without looking back, explain:

  1. What /livez, /readyz and /version each report, and what a platform does when the first two fail.
  2. Why the deployment references the image by digest and how you obtained that digest.
  3. What tls internal, health_uri and lb_try_duration each do in the Caddyfile.
  4. Which DNS record you use for a server you run and which for a platform's hostname, and what Caddy needs before it can obtain a public certificate.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

8 questions · about 6 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check