Skip to main content
CRUCIBLE
Legacy Reference Archive: This 44-chapter book reference has been distilled into Academy A01 (8 Executable Modules) with Tier-Adaptive Productive Failure, Kore/Puck voice, and live Firecracker labs.
Open Academy A01 →
COURSE 0 · SERVER BUILDING & LIFECYCLE MASTERY

Zero-to-Production Linux, Containers, Networking & Recovery

PROGRESS: 0 / 72 (0%)0/44L · 0Q · 0VM
CH 06 · PART II · CONTAINERS, LIVE DEPLOY & OPS (CH 06–08) · 857 WORDS (5 MIN)

6 Package the application and run PostgreSQL

An image is a packaged filesystem and execution configuration. A container is a running instance with isolation provided by the host. A volume stores data independently of an application container's writable layer.

FULL WAR-ROOM →
INTERACTIVE DELIVERY CONTRACT · CLICK ANY STAGE

Build Once, Promote Deliberately: Immutable Artifact & Volume Boundary

Why container layers stay disposable while named volumes and versioned migrations preserve state.

verifiesdeploysmountsPinned CommitGit SHA + LockfileCI Gate & DigestTests · Lint · SHA-256Ephemeral AppRead-only FS · Env SecretsDurable VolumeEncrypted Backups
SELECTED LAYER · PINNED COMMIT
Single source of truth with pinned dependency hashes so builds are bit-for-bit reproducible.
Common failure: Floating latest tags or unpinned packages causing "worked yesterday" production breaks.
$ python3 labs/foundations.py --text "build once verify always"

Outcome: run the API, worker, and database as distinct processes with explicit configuration. Prerequisites: local project completion and Docker with Compose. Environment: your laptop or a disposable Linux VM. Cost: local CPU, memory, and image storage.

Image container and volume

An image is a packaged filesystem and execution configuration. A container is a running instance with isolation provided by the host. A volume stores data independently of an application container's writable layer. Removing an application container should not delete the database. Removing the database volume can.

The Dockerfile installs locked dependencies, copies the application, creates a non-root user, and starts Uvicorn. The Compose file defines separate database, initialization, API, and worker services. The API is published only to the host's loopback address; the database has no published port. Services communicate by their Compose names on a private network.

localhost inside the API container means that container, not your laptop and not the database container. The database hostname is db. This distinction explains many first-container connection failures.

Run the stack

From the example directory, create .env with setup_lab.py if it does not already exist. Then:

bash
docker compose config --quiet
docker compose up -d --build
docker compose ps
docker compose logs --tail=50 api worker
curl --fail-with-body --retry 20 --retry-connrefused \
  --retry-delay 1 --retry-max-time 60 --max-time 3 \
  http://127.0.0.1:18768/health/ready

Use config --quiet for validation: printing the expanded configuration can reveal secrets. The API and worker wait for schema initialization; initialization waits for database readiness. Starting a process is not the same as being ready to serve. See [Compose startup order](https://docs.docker.com/compose/how-tos/startup-order/).

Expect the initializer to exit successfully and the API, worker, and database to remain running. Submit the same requests from Chapter 3 using port 18768 instead of 8000. Use the token from this lab's .env. You do not need to expose a database port to inspect it; run psql through docker compose exec.

Configuration and credentials

DATABASE_URL configures the driver, identity, destination, and database name. Its credentials must not be logged. The generated passwords use URL-safe hexadecimal characters, avoiding accidental parsing problems in the example. For arbitrary credentials, use a structured URL builder or correct encoding rather than concatenating unescaped strings.

The initialization script creates a non-superuser application role. A separate one-off role initialization service creates the role if absent, then Alembic creates or upgrades tables as lab_owner; a separate seed step installs the bootstrap credential. The API and worker use restricted lab_app privileges. Changing .env later does not automatically change an existing database role's password. Rotation requires a deliberate database change and coordinated client update.

The example Compose project has a fixed, distinctive name. Before running it on a machine with an existing copy, inspect the project and avoid accidentally replacing someone else's lab. For another independent instance, choose a different project name and host port and use a separate .env.

Resource and storage behavior

The application containers have memory and process limits, a read-only root filesystem, and a temporary directory. Their logs rotate. Persistent jobs live in PostgreSQL's named volume. Database sizing and disk alerts still need operational work; container memory limits do not manage database retention for you.

If a build fails, inspect the first failed layer. If database initialization fails with “No space left on device,” inspect host and Docker storage capacity. Do not run broad prune commands on a shared computer. They can remove unrelated caches, images, or recovery data. Stop the lab and arrange scoped capacity changes separately.

The workspace includes compose.ephemeral.yaml for disposable testing with a memory-backed database. It was introduced to work around a full Docker storage volume during verification. It is not a persistence configuration: database contents disappear when that container is removed. Always state when using it in evidence.

Restart and recovery exercise

Create a known job and wait for success. Restart only the API and worker:

bash
docker compose restart api worker

Read the same job ID and verify its result remains. Stop the worker, submit a new job, then restart it and verify completion. Separately stop the database and verify the API reports readiness failure while liveness remains meaningful. Restart the database and check recovery. Use the database outage drill only in your isolated lab.

A healthcheck marks status; it does not necessarily restart a container automatically. The restart policy responds to process exit. External monitoring or an orchestrator may take other actions. Understand which component is responsible instead of assuming every “unhealthy” state heals itself.

Clean shutdown

bash
docker compose down

This removes the lab's containers and network while preserving named volumes. Do not add --volumes unless you intentionally want to delete that project's database after checking the target and backups. For the memory-backed proof override, removal destroys its temporary data regardless of named-volume retention.

Exit exercise

From a clean checkout and fresh lab configuration, build the image, initialize the schema, complete a job, restart application containers, and read the result. Explain the difference between rebuilding an image, recreating a container, restarting a process, and deleting a volume. Record image IDs, application versions, and the exact configuration used.

ACTIVE-RECALL MASTERY CHECKPOINT · CH 06

Lock in what you just learned (3 quick questions)

PASS 2/3 FOR +30 XP
Q1.What is the fundamental relationship between a container image, a running container, and a named volume?
Q2.Why should production container images run as a non-root user and drop unnecessary Linux capabilities?
Q3.Why set explicit memory/CPU limits and restart policies on containerized services?
Answered 0 / 3