Production HTTPS Compose stack

You build the production Compose stack that serves the API through Caddy over HTTPS and waits for a successful migration before startup.

Ticket

Build the production Compose deployment for the Go API. Caddy terminates HTTPS and proxies requests to the API, a one-shot service applies database migrations, and the API exposes separate liveness and readiness handlers.

The health package exports exactly the declarations the tests call:

go
import (
    "context"
    "net/http"
    "time"
)

type Check func(ctx context.Context) error

func Healthz() http.Handler

func Readyz(timeout time.Duration, checks map[string]Check) http.Handler

The order service needs a public HTTPS entry point, but traffic should not reach the API before its database schema is ready. The next exercise, "Nightly mysqldump and one restore test", uses this production stack to run and verify database backups.

Acceptance criteria

  • backend/Caddyfile uses {$API_DOMAIN} as its site address and proxies requests to api:8080 with reverse_proxy. Leave automatic HTTPS enabled: do not use an http:// site address, auto_https off, or tls internal.
  • backend/Caddyfile configures the reverse proxy's upstream health check with health_uri /readyz.
  • backend/compose.prod.yml publishes ports 80 and 443 from the Caddy service, mounts ./Caddyfile at /etc/caddy/Caddyfile, mounts the named volume caddy_data at /data, and makes Caddy depend on the API.
  • backend/compose.prod.yml does not publish API, worker, MySQL, Redis, or Redpanda ports on all host interfaces. Any host port mappings for these services must bind to 127.0.0.1.
  • backend/compose.prod.yml defines a migrate service using an image whose name begins with migrate/migrate. It runs as a one-shot job without restarting, mounts ./db/migrations, and depends on MySQL with condition: service_healthy. The API depends on the migration service with condition: service_completed_successfully.
  • The migration command in backend/compose.prod.yml contains -path, a mysql:// database URL, and up.
  • The API health check in backend/compose.prod.yml uses the shell-free CMD form and invokes the binary with its -healthcheck flag.
  • backend/.env.example contains API_DOMAIN=localhost.
  • internal/health: Healthz() always returns HTTP 200, sets a Content-Type beginning with application/json, and returns JSON containing {"ok":true}.
  • internal/health: when the mysql, redis, and kafka checks all succeed, Readyz() returns HTTP 200, a status field of "ok", and "ok" for each dependency in the checks object.
  • internal/health: when the redis and kafka checks fail while mysql succeeds, Readyz() returns HTTP 503, a status field of "unavailable", and a sorted failing list containing ["kafka","redis"]. The healthy mysql check must remain marked "ok".
  • internal/health: readiness responses never include internal dependency error text. A failure containing dial tcp, 10.0.3.7, or hunter2 must not expose those strings in the response.
  • internal/health: a dependency check that waits for its context to expire after a 50 ms timeout is reported as unavailable. With the test's slow kafka check, the response is HTTP 503, failing contains ["kafka"], and the handler completes in less than one second.
  • internal/health: readiness checks execute concurrently. Three checks that each take 150 ms must complete together in less than 320 ms, with an HTTP 200 response when they succeed.
  • internal/health: Healthz() does not invoke dependency checks. A call to /healthz leaves the check count at zero; a subsequent /readyz call invokes the configured check exactly once.

Constraints

  • Give each readiness check its own timeout context using the timeout supplied to Readyz().
  • Run readiness checks concurrently. The three-check timing case must complete in less than 320 ms.
  • A check that respects its context must be bounded by its timeout. The supplied 50 ms timeout case must return within one second.
  • Any host port mappings for services other than Caddy must bind to 127.0.0.1.
  • Do not modify the provided tests.

Design direction

Keep dependency checks and HTTP response construction in backend/internal/health/health.go. Use Check as the common function type so the handler does not need to know whether a check uses MySQL, Redis, or Kafka. Keep dependency client construction in backend/cmd/api/health.go. Add the -healthcheck execution mode in backend/cmd/api/healthcheck.go.

Register /healthz with health.Healthz() and /readyz with health.Readyz(2*time.Second, checks). Replace the old inline health route with a call to registerHealth(router). Configure checks only for dependencies whose corresponding environment variables are present. Use the context-aware ping methods of database/sql, go-redis, and franz-go.

Keep liveness independent of dependencies. A process can be alive while MySQL is unavailable. Caddy should use readiness so it can avoid sending traffic to an API whose dependencies are unavailable.

Use the migration service as a startup gate. It should wait for healthy MySQL, mount the existing migration files read-only, and exit after applying migrations. The API and worker should both wait for healthy infrastructure and successful migration completion. This separates container health from application schema readiness.

Keep Caddy as the public reverse proxy. Its named volumes should preserve certificate data and configuration across restarts. The API's health check must invoke its binary directly because the distroless image has no shell. Any layout that meets the contract passes.

How to check your work

Run the Go tests first, then run the production stack check from the same directory:

bash
cd backend
make test W=7B3
./scripts/check-w7-b3.sh

The helper starts the production Compose stack using .env.example and checks service health, HTTPS endpoints, the HTTP-to-HTTPS redirect, and migration completion. It uses curl -k for the local certificate. Confirm that https://localhost/healthz returns HTTP 200 and https://localhost/readyz reports readiness.

When a test fails, read the first failing assertion. It identifies the file or response field that does not match the contract.

Finished Exercise 7.6?

Implementation

Run locally

Write the code in your editor inside zomato-prep, then work through this list.

  1. Health handlers return the expected status codes and JSON.
  2. Readiness checks run concurrently with independent timeouts.
  3. Failed dependencies are identified without exposing error text.
  4. Caddy proxies HTTPS traffic and checks /readyz.
  5. Migrations complete before the API starts.
  6. The production stack check passes.

Commands

terminal
cd backend && make test W=7B3
terminal
cd backend && ./scripts/check-w7-b3.sh

Tests

  • TestW7B3_CaddyfileProxiesTheConfiguredDomainToTheApi in backend/internal/deploy/w7b3_test.go
  • TestW7B3_CaddyHealthChecksTheApiThroughReadyz in backend/internal/deploy/w7b3_test.go
  • TestW7B3_CaddyServiceExposesWebPortsAndPersistsCertificates in backend/internal/deploy/w7b3_test.go
  • TestW7B3_OnlyCaddyIsPublishedToTheInternet in backend/internal/deploy/w7b3_test.go
  • TestW7B3_MigrationsRunAsAOneShotMigrateServiceBeforeTheApi in backend/internal/deploy/w7b3_test.go
  • TestW7B3_MigrateDatabaseUrlComesFromTheEnvFile in backend/internal/deploy/w7b3_test.go
  • TestW7B3_ApiHasAHealthcheckThatNeedsNoShell in backend/internal/deploy/w7b3_test.go
  • TestW7B3_EnvExampleDefaultsToALocalDomain in backend/internal/deploy/w7b3_test.go
  • TestW7B3_HealthzIsAlwaysOkAndJSON in backend/internal/health/health_test.go
  • TestW7B3_ReadyzIsOkWhenEveryDependencyIsHealthy in backend/internal/health/health_test.go
  • TestW7B3_ReadyzReturns503NamingEveryFailingDependency in backend/internal/health/health_test.go
  • TestW7B3_ReadyzNeverLeaksErrorText in backend/internal/health/health_test.go
  • TestW7B3_ReadyzFailsASlowDependencyAfterTheTimeout in backend/internal/health/health_test.go
  • TestW7B3_ReadyzRunsChecksConcurrently in backend/internal/health/health_test.go
  • TestW7B3_HealthzNeverCallsDependencyChecks in backend/internal/health/health_test.go