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
TUT 03 · WORKED TUTORIALS (START HERE) · 2,024 WORDS (11 MIN)

Build once, inspect, transfer and release the same artifact

The source commit identifies code and configuration. uv.lock and hash-pinned requirements identify resolved Python dependencies. A Docker image ID identifies the loaded image configuration and its content-addressed layers.

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"

Purpose: replace ad hoc target rebuilding with a traceable release. Prerequisites: local tests pass, the approved target runs the reference stack, backup/restore works and schema compatibility has been reviewed. Environment: a reviewed source checkout on an isolated builder, optional approved GitHub Actions repository, and a separate target host. Inputs: source revision, target architecture, release record, previous image identity and approved maintenance window. Status: the existing local checks are executed evidence; the workflow and target transfer below require installation in the selected repository/host and their own execution receipts.

1. Understand the artifact identities

The source commit identifies code and configuration. uv.lock and hash-pinned requirements identify resolved Python dependencies. A Docker image ID identifies the loaded image configuration and its content-addressed layers. A registry manifest digest identifies the registry's manifest object. A compressed exported archive has its own file checksum. Record all applicable identities rather than assuming they are interchangeable.

This tutorial uses a Docker archive, which can be delivered over SSH without publishing a registry package or giving the deployment host a registry push token. Its checksum detects alteration only when the expected checksum arrives through a trusted release record; an attacker who can replace both archive and checksum can forge that comparison. Preserve build provenance and approval separately. The supplied pytest -q ~/playground/automation-service/test_service.py expects a registry repository@sha256 identity and refuses remote Docker contexts. Use that helper only with an actual reviewed registry digest, not a substituted local image ID.

2. Build and export manually on an approved builder

Run from the VM workspace (`~/playground`) on the builder after verifying that this is the reviewed checkout. Choose the architecture of the actual target. A build made for arm64 is not automatically runnable on an amd64 VM; multi-platform builds require separate testing for each target.

bash
set -euo pipefail
if git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
    MASTERY_REV=$(git rev-parse --verify HEAD)
else
    MASTERY_REV=$(python3 -c "import hashlib,pathlib; print('bundle-'+hashlib.sha256(pathlib.Path('dist/manifest-sha256.json').read_bytes()).hexdigest())")
fi
MASTERY_IMAGE="server-mastery-release:$MASTERY_REV"
mkdir -m 700 -p .recovery
mkdir -m 700 .recovery/release-output
cd ~/playground/automation-service
uv sync --frozen
if [ ! -e .env ]; then uv run python setup_lab.py; fi
nginx -t && ss -tulpn
docker build --platform linux/amd64 -t "$MASTERY_IMAGE" .
docker image inspect "$MASTERY_IMAGE" --format '{{.Id}}' > ../../.recovery/release-output/image-id.txt
docker image save "$MASTERY_IMAGE" | gzip > ../../.recovery/release-output/image.tar.gz
cd ../../.recovery/release-output
python3 - <<'PY'
from pathlib import Path
import hashlib,json
p=Path('image.tar.gz')
r={'archive':'image.tar.gz','sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'image_id':Path('image-id.txt').read_text().strip(),'platform':'linux/amd64'}
Path('artifact.json').write_text(json.dumps(r,indent=2)+'\n')
print(r)
PY

git rev-parse uses the reviewed repository commit when available. A non-Git source archive takes the explicit alternate branch and identifies the packaged manifest by SHA-256 with a bundle prefix. Keep that manifest and the approved archive checksum together; do not describe the bundle identifier as a Git commit. The commands create new .env and .recovery/release-output state exclusively; if those already exist, inspect and use the existing known lab configuration or a fresh builder directory. Do not overwrite existing secrets to repeat a build.

The exported image contains application code and pinned installed dependencies; it must not contain .env, database dumps or signing keys. Review .dockerignore and Dockerfile before building. Run the completed image in staging with the same database/worker flow before promotion. The [Docker save](https://docs.docker.com/reference/cli/docker/image/save/) and [load](https://docs.docker.com/reference/cli/docker/image/load/) references define archive behavior.

Return to the VM workspace (`~/playground`) before continuing. The export block ended in .recovery/release-output, so run:

bash
cd ../..
pwd
ls tutorials examples

Before transferring the manually exported archive, run the same blocking vulnerability policy. The archive remains a quarantined candidate until this check passes. This uses the official Trivy container and reads the archive through a read-only mount; it does not receive the Docker socket or deployment credentials. Run from the VM workspace (`~/playground`):

bash
set -euo pipefail
docker pull aquasec/trivy:0.74.0
docker image inspect aquasec/trivy:0.74.0 --format '{{json .RepoDigests}}' > .recovery/release-output/scanner-digests.json
docker run --rm \
  --mount "type=bind,src=$PWD/.recovery/release-output,dst=/scan,readonly" \
  aquasec/trivy:0.74.0 image --input /scan/image.tar.gz \
  --scanners vuln --severity CRITICAL,HIGH --exit-code 1 --format json \
  > .recovery/release-output/scan.json

A nonzero result stops promotion. A successful archive export is not approval to transfer/deploy it. The official [Trivy image documentation](https://trivy.dev/latest/docs/target/container_image/) describes archive scanning. Record the actual scanner digest, report and vulnerability database date. An unpatched container base image often reports unfixed HIGH base-system findings; this strict policy therefore blocks it. Do not bypass the gate to finish the exercise. Remediate the base/runtime or obtain a narrowly scoped, time-limited security decision for the actual deployment; no such exception is granted by this tutorial.

3. Add a protected manual build workflow

The following complete example can be saved as .github/workflows/release-artifact.yml in an approved repository. Installing it and starting hosted jobs requires the repository owner's authorization and billing review. It has no host SSH credential and performs no deployment or registry publication. It allows a deliberate manual trigger rather than giving an untrusted pull request production access.

yaml
name: Build reviewed server artifact
on:
  workflow_dispatch:
permissions:
  contents: read
jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 20
    steps:
      - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262
      - uses: actions/setup-python@a26af69be951a213d495a4c3e4e4022e16d87065
        with:
          python-version: '3.12'
      - uses: astral-sh/setup-uv@d0cc045d04ccac9d8b7881df0226f9e82c39688e
        with:
          version: '0.12.3'
      - name: Install native lifecycle prerequisites
        run: |
          sudo apt update
          sudo apt install -y postgresql postgresql-client libpq-dev age openssl
          export PATH="$(pg_config --bindir):$PATH"
          printf '%s\n' "$(pg_config --bindir)" >> "$GITHUB_PATH"
          for tool in initdb pg_ctl pg_dump pg_restore age age-keygen openssl; do
            command -v "$tool" || exit 1
          done
      - name: Install and verify
        working-directory: ~/playground/automation-service
        run: |
          uv sync --frozen
          uv run python setup_lab.py
          nginx -t && ss -tulpn
      - name: Build candidate
        run: docker build --platform linux/amd64 -t server-mastery-release:${{ github.sha }} ~/playground/automation-service
      - name: Scan candidate
        uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1
        with:
          image-ref: server-mastery-release:${{ github.sha }}
          format: table
          output: trivy.txt
          exit-code: '1'
          severity: CRITICAL,HIGH
      - name: Export verified image
        run: |
          mkdir -p .recovery/release-output
          docker image inspect server-mastery-release:${{ github.sha }} --format '{{.Id}}' > .recovery/release-output/image-id.txt
          docker image save server-mastery-release:${{ github.sha }} | gzip > .recovery/release-output/image.tar.gz
          python3 - <<'PY'
          from pathlib import Path
          import hashlib,json,os
          p=Path('.recovery/release-output/image.tar.gz')
          r={'source_commit':os.environ['GITHUB_SHA'],'archive':'image.tar.gz','sha256':hashlib.sha256(p.read_bytes()).hexdigest(),'image_id':Path('.recovery/release-output/image-id.txt').read_text().strip(),'platform':'linux/amd64'}
          Path('.recovery/release-output/artifact.json').write_text(json.dumps(r,indent=2)+'\n')
          PY
      - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
        with:
          name: reviewed-server-image
          path: .recovery/release-output/
          retention-days: 7
      - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02
        if: always()
        with:
          name: validation-records
          path: |
            proof/verification-output.txt
            trivy.txt

Pins identify retrieved action commits; review upstream code and update them intentionally. The scanner pin corresponds to the official [Trivy action](https://github.com/aquasecurity/trivy-action) release0.35.0. A vulnerability finding or unavailable vulnerability database stops release promotion. Do not turn a failing scan into a success by globally suppressing its exit status. Review findings, update the base/dependencies or record a narrowly justified, time-limited exception through your security process.

Before triggering the workflow, select the reviewed branch/commit in GitHub's Actions interface. After it completes, retain the run URL, commit, scan output, test output and artifact metadata. Download reviewed-server-image; confirm its source_commit equals the approved revision. A successful workflow definition parser is not a hosted execution receipt. Keep deployment authorization in a protected environment or explicit operator approval; this build identity needs no production secrets.

4. Verify and load on the selected target

On the LAPTOP/BUILDER, after approval of this precise candidate and maintenance action, create the remote artifact directory through the verified SSH connection, then transfer the files in order:

bash
ssh -i ~/.ssh/mastery-v5-lab "$MASTERY_ADMIN@$MASTERY_HOST" 'bash -s' <<'REMOTE'
umask 077
mkdir -p "$HOME/mastery-v5-artifact"
chmod 700 "$HOME/mastery-v5-artifact"
REMOTE
scp -i ~/.ssh/mastery-v5-lab .recovery/release-output/image.tar.gz .recovery/release-output/artifact.json "$MASTERY_ADMIN@$MASTERY_HOST:~/mastery-v5-artifact/"

On the REMOTE host, enter it, verify the expected record through the trusted approval channel, then validate file bytes and load:

bash
cd ~/mastery-v5-artifact
python3 - <<'PY'
from pathlib import Path
import hashlib,json,re
r=json.loads(Path('artifact.json').read_text())
assert r['archive']=='image.tar.gz'
assert re.fullmatch(r'sha256:[0-9a-f]{64}',r['image_id'])
assert r['platform']=='linux/amd64'
assert hashlib.sha256(Path('image.tar.gz').read_bytes()).hexdigest()==r['sha256']
print('Archive checksum and metadata shape passed')
PY
sudo docker image load --input image.tar.gz
MASTERY_IMAGE_ID=$(python3 -c "import json; print(json.load(open('artifact.json'))['image_id'])")
sudo docker image inspect "$MASTERY_IMAGE_ID" --format '{{.Id}}'

Expected: the loaded image exists by the exact expected ID. The metadata's architecture must match uname -m/the provider machine architecture; use linux/arm64 for a separately tested ARM target. Loading is a local daemon mutation and does not execute the application. If checksum or identity fails, stop before deployment and retrieve the approved artifact again. Do not rebuild on the target and call it the same artifact.

5. Apply a maintenance release and retain rollback

Return to the REMOTE example directory. First finish a verified backup and record schema compatibility. Capture the old API image ID using the existing container before changing anything:

bash
cd ~/playground/automation-service
MASTERY_OLD_CONTAINER=$(sudo docker compose ps -q api)
sudo docker inspect "$MASTERY_OLD_CONTAINER" --format '{{.Image}}' > .previous-image-id

A blank container ID means there is no running prior release; inspect the inventory rather than guessing rollback. Copy the reviewed new schema/code configuration separately as a new source-release directory if it changed; keep .env and database-volume/project ownership consistent with the selected deployment. Never let a new directory accidentally create a different database project and hide the intended dataset.

For this archive route, create compose.artifact.yaml with these exact contents:

yaml
services:
  init:
    image: ${APP_IMAGE:?set the verified local image ID}
  seed:
    image: ${APP_IMAGE:?set the verified local image ID}
  api:
    image: ${APP_IMAGE:?set the verified local image ID}
  worker:
    image: ${APP_IMAGE:?set the verified local image ID}

Set APP_IMAGE to the verified value from the artifact record, then perform the reviewed maintenance sequence:

bash
export APP_IMAGE="$MASTERY_IMAGE_ID"
sudo --preserve-env=APP_IMAGE docker compose -f compose.yaml -f compose.artifact.yaml config --quiet
sudo --preserve-env=APP_IMAGE docker compose -f compose.yaml -f compose.artifact.yaml stop --timeout 40 api worker
sudo --preserve-env=APP_IMAGE docker compose -f compose.yaml -f compose.artifact.yaml up -d --pull never --wait db
sudo --preserve-env=APP_IMAGE docker compose -f compose.yaml -f compose.artifact.yaml run --rm --no-deps roleinit
sudo --preserve-env=APP_IMAGE docker compose -f compose.yaml -f compose.artifact.yaml run --rm --no-deps init
sudo --preserve-env=APP_IMAGE docker compose -f compose.yaml -f compose.artifact.yaml run --rm --no-deps seed
sudo --preserve-env=APP_IMAGE docker compose -f compose.yaml -f compose.artifact.yaml up -d --no-deps --no-build --pull never --wait --wait-timeout 120 api worker
curl --fail-with-body --max-time 5 http://127.0.0.1:18768/health/ready

This sequence deliberately stops writers before migrations. It can interrupt requests. If migration fails, keep the maintenance state, preserve logs and diagnose; starting old code against an unknown schema is not an automatic repair. The seed step does not un-revoke an old token. Confirm the actual API/worker image IDs equal APP_IMAGE and complete the public authenticated job workflow before accepting the release. Keep the previous image and protected configuration until the rollback window closes.

For a reviewed backward-compatible schema, execute rollback against the existing database without rerunning old migrations:

bash
export APP_IMAGE=$(cat .previous-image-id)
sudo docker image inspect "$APP_IMAGE" --format '{{.Id}}'
sudo --preserve-env=APP_IMAGE docker compose -f compose.yaml -f compose.artifact.yaml stop --timeout 40 api worker
sudo --preserve-env=APP_IMAGE docker compose -f compose.yaml -f compose.artifact.yaml up -d --no-deps --no-build --pull never --wait --wait-timeout 120 api worker
curl --fail-with-body --max-time 5 http://127.0.0.1:18768/health/ready
set -a
. ./.env
set +a
read -r -p 'Saved public-workflow job UUID from tutorial02: ' MASTERY_JOB_ID
export MASTERY_JOB_ID
sudo --preserve-env=LAB_TOKEN,MASTERY_JOB_ID docker compose exec -T -e LAB_TOKEN -e MASTERY_JOB_ID api python - <<'PYROLLBACK'
import os,httpx
r=httpx.get('http://127.0.0.1:8000/jobs/'+os.environ['MASTERY_JOB_ID'],headers={'Authorization':'Bearer '+os.environ['LAB_TOKEN']},timeout=5)
r.raise_for_status()
assert r.json()['status']=='succeeded'
assert r.json()['result']=={'words':3,'characters':24}
print('Saved public workflow result survived compatible rollback')
PYROLLBACK

That expected result belongs to tutorial02's exact public workflow evidence text. Supply that recorded job ID, not an arbitrary job. Repeat a fresh external workflow using a newly issued short-lived test credential and revoke it afterward as in tutorial02. The previous external test token was deliberately revoked and should remain denied. If schema compatibility is not established, stop and use the rehearsed forward fix or separate-host recovery procedure.

Troubleshooting, cleanup and assessment

A failed build is a source/dependency problem before it is a deployment problem. A scan failure is a finding to resolve. A missing loaded image indicates transfer/daemon targeting trouble. A ready process serving wrong data suggests the wrong project/database/configuration. A503 after migration points to schema, connection or privilege state. Diagnose from recorded identities and first errors before changing multiple components.

Retain approved release records and bounded logs under the agreed policy. Remove only explicitly identified obsolete image/archive artifacts after verifying no running or rollback deployment depends on them. Never use docker system prune as the release cleanup procedure. Registry publication is an optional delivery variant requiring its own repository scope, credentials, provenance and retention; this archive path does not silently grant publishing authority.

You pass when you can trace the deployed image back to a reviewed source revision and test/scan run, detect an altered archive, demonstrate intended maintenance, recover a compatible failed release and identify exactly which retained artifact makes rollback possible. Another operator must be able to repeat the release from the approved artifact without rebuilding it or asking where its configuration came from.

ACTIVE-RECALL MASTERY CHECKPOINT · TUT 03

Lock in what you just learned (3 quick questions)

PASS 2/3 FOR +30 XP
Q1.What makes a "build once, promote deliberately" artifact pipeline safer than running git pull on production?
Q2.When a newly promoted release fails its post-deploy health probe, what is the safest immediate action?
Q3.Why record commit SHA, build digest, and health probe outputs in a release evidence log?
Answered 0 / 3