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 02 · WORKED TUTORIALS (START HERE) · 2,929 WORDS (16 MIN)

Move the reference service onto an approved Ubuntu host

Write down the account/project ID from your provider console, approved region and machine size, administrator public IP/CIDR, SSH public-key file, instance name and retirement date.

FULL WAR-ROOM →
INTERACTIVE REQUEST FLOW · CLICK ANY HOP TO INSPECT LIVE

Production Request Path: HTTPS Edge -> App -> PgBouncer -> Postgres

Trace every hop from a browser TLS 1.3 connection to an indexed PostgreSQL row lookup.

HTTPSQLPooledNGINX EdgeTLS 1.3 · :8443 / :443FastAPI Worker127.0.0.1 :8000PgBouncer PoolTX Mux · :6432PostgreSQL 15B-Tree · :5432
SELECTED LAYER · NGINX EDGE
Terminates HTTPS, enforces timeouts and rate limits, and reverse-proxies clean HTTP to loopback.
Common failure: HTTP 502 Bad Gateway when upstream keepalive_timeout is shorter than proxy idle timeout.
$ nginx -t

Purpose: take the same application from a prepared release bundle to an externally reachable HTTPS service, then operate, recover, migrate and retire it. Prerequisites: the local walkthrough, an explicitly approved disposable VM/account, owned DNS zone, SSH public key, console recovery, synthetic data and an agreed cost/retention plan. Environment: a fresh Ubuntu 24.04 LTS VM with systemd; a separate laptop terminal. Commands labeled REMOTE change that VM. Status: reviewed target procedure; this walkthrough does not claim it created your account, changed DNS or executed a public deployment.

1. Obtain the required values before creating anything

Write down the account/project ID from your provider console, approved region and machine size, administrator public IP/CIDR, SSH public-key file, instance name and retirement date. Obtain the hostname and authoritative DNS zone from the domain owner's DNS console. Obtain the backup destination and its access policy from the backup owner. Identify the person who can recover the provider account and decrypt backups independently of the VM.

If you do not yet have a hosting account, create one through the provider's official sign-up page, complete its verification/billing requirements, enable its supported MFA, save recovery codes in your approved password manager and create an isolated project for this exercise. Review the quoted price, backup/transfer charges and alert thresholds before creating a resource. A billing alert is not necessarily a hard spending cap. Do not use an organization's production project as a convenient tutorial sandbox.

Use Bash for this tutorial's interactive commands. On a Mac whose default shell is zsh, run bash first; read -r -p below is Bash syntax. On your laptop, generate a dedicated SSH key only if you do not already have an approved key:

bash
mkdir -p ~/.ssh
chmod 700 ~/.ssh
ssh-keygen -t ed25519 -f ~/.ssh/mastery-v5-lab -C mastery-v5-lab

Choose a passphrase. Keep the private key on the laptop; upload only the .pub file through the provider's key-management control. Do not overwrite an existing key if the command reports one. Register your public key while creating the VM. Select the fresh Ubuntu 24.04 image and record the exact instance ID, public address, attached disk IDs and firewall ID after creation.

In the provider firewall, permit TCP22 from your administrator source only, TCP80/443 for intended clients and no inbound5432 or18768. If enabling IPv6, create corresponding reviewed rules; otherwise omit AAAA records. Confirm the out-of-band console can be opened. The exact console controls differ by provider, so compare resource identifiers before every mutation. This is an account-specific input, not a guessed shell constant.

2. Establish administrative access and inspect the host

Set laptop variables using the actual reviewed values. The prompts below intentionally require your input rather than shipping a hostname that could accidentally be used:

bash
read -r -p 'Approved VM IPv4/hostname: ' MASTERY_HOST
read -r -p 'Provider image SSH user (for example ubuntu): ' MASTERY_ADMIN
ssh -i ~/.ssh/mastery-v5-lab "$MASTERY_ADMIN@$MASTERY_HOST"

Verify the first SSH host-key fingerprint through the provider console before accepting it. An unexpected changed fingerprint may mean a rebuild or the wrong server; investigate before removing a known-host entry. Once connected, the following commands are REMOTE:

bash
hostnamectl
id
cat /etc/os-release
lsblk -o NAME,SIZE,TYPE,MOUNTPOINTS
ss -lnt
sudo -v

Expected: the recorded Ubuntu VM, intended user, expected disks and working administrative authorization. If the image provides only root, create a named administrator through the current root console/session:

bash
adduser mastery-admin
usermod -aG sudo mastery-admin
install -d -m 0700 -o mastery-admin -g mastery-admin /home/mastery-admin/.ssh

Choose the account password interactively. In a second LAPTOP terminal, copy only the dedicated public key:

bash
scp -i ~/.ssh/mastery-v5-lab ~/.ssh/mastery-v5-lab.pub "root@$MASTERY_HOST:/tmp/mastery-v5.pub"

Back in the REMOTE root session, inspect that public key and install it:

bash
cat /tmp/mastery-v5.pub
install -m 0600 -o mastery-admin -g mastery-admin /tmp/mastery-v5.pub /home/mastery-admin/.ssh/authorized_keys

From the LAPTOP, open ssh -i ~/.ssh/mastery-v5-lab "mastery-admin@$MASTERY_HOST", run id and sudo -v, and verify both succeed. Then set MASTERY_ADMIN=mastery-admin in the laptop terminal. Keep the root/console session until this succeeds. Do not remove or disable existing access as part of an unverified bootstrap.

On this fresh VM, review available updates, apply them and perform any required reboot before introducing data. Ubuntu's apt list --upgradable, sudo apt update and sudo apt upgrade make the changes visible. Reboot only this approved VM, reconnect and verify its recorded identity. Keep console recovery available if network access fails. A successful local systemctl call cannot prove remote recovery access.

3. Install Docker from its official repository

These commands are for the fresh REMOTE Ubuntu host. If existing Docker/containerd packages or unrelated containers are present, stop the tutorial and inspect ownership; do not uninstall a shared runtime. Use Docker's [Ubuntu installation reference](https://docs.docker.com/engine/install/ubuntu/) to check support before applying to a different release.

bash
sudo apt update
sudo apt install ca-certificates curl gnupg age python3 unzip
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
. /etc/os-release
printf '%s\n' \
  'Types: deb' \
  'URIs: https://download.docker.com/linux/ubuntu' \
  "Suites: ${UBUNTU_CODENAME:-$VERSION_CODENAME}" \
  'Components: stable' \
  "Architectures: $(dpkg --print-architecture)" \
  'Signed-By: /etc/apt/keyrings/docker.asc' | sudo tee /etc/apt/sources.list.d/docker.sources > /dev/null
sudo apt update
sudo apt install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
sudo systemctl enable --now docker
sudo docker version
sudo docker compose version

Keep using sudo docker on this remote host. We do not add the application account to the docker group. Engine administration is effectively privileged. Record installed versions and the package source in the release record. Before public traffic, remember that Docker-published ports can bypass assumptions based solely on UFW; verify actual exposure and the provider firewall. Our database remains on the private Compose network, and the API publishes loopback only.

4. Transfer a reviewed release without copying laptop secrets

On the LAPTOP, obtain your prepared release bundle, compare its SHA-256 to the locally retained release record and inspect the archive contents. The source bundle intentionally excludes .env, private keys, databases and virtual environments. Transfer that bundle over the reviewed SSH connection:

bash
scp -i ~/.ssh/mastery-v5-lab ./dist/Server-Building-Mastery-v5-Complete-Bundle.zip "$MASTERY_ADMIN@$MASTERY_HOST:~/"

On the REMOTE host, create a new directory and extract the trusted bundle:

bash
mkdir -m 700 ~/mastery-v5-release
unzip ~/Server-Building-Mastery-v5-Complete-Bundle.zip -d ~/mastery-v5-release
cd ~/playground/automation-service
umask 077
python3 setup_lab.py
sudo docker compose config --quiet
sudo docker compose up -d --build --wait --wait-timeout 120
curl --fail-with-body --max-time 5 http://127.0.0.1:18768/health/ready

This first deployment builds on the target for learning. Tutorial03 supplies the build-once artifact workflow for subsequent controlled delivery. Keep the generated remote .env on the target and in its approved secret-recovery mechanism; do not reuse the laptop token. Do not paste the expanded Compose configuration into a report. Verify image ID, schema version, container state and the same complete authenticated workflow used locally.

One way to run host client snippets without installing a second host dependency tree is to temporarily port-forward the API over SSH from the laptop: ssh -i ~/.ssh/mastery-v5-lab -L 18769:127.0.0.1:18768 "$MASTERY_ADMIN@$MASTERY_HOST". Use a dedicated approved test credential transferred through your secret manager, not a screenshot or command-line literal. The private tunnel proves the API path; public HTTPS is checked next. A production client should receive only the scope it needs.

Before opening public traffic, apply the strict image gate on the REMOTE host, still in the example directory. This is required for the first deployment as well as later releases:

bash
set -euo pipefail
umask 077
mkdir -p .recovery
sudo docker image save server-mastery-lab:5.0 > .recovery/prelive-image.tar
sudo docker pull aquasec/trivy:0.74.0
sudo docker run --rm \
  --mount "type=bind,src=$PWD/.recovery/prelive-image.tar,dst=/scan/image.tar,readonly" \
  aquasec/trivy:0.74.0 image --input /scan/image.tar \
  --scanners vuln --severity CRITICAL,HIGH --exit-code 1 --format json \
  > .recovery/prelive-scan.json

A nonzero result stops this public-deployment path. A stale unpatched base image often has reported unfixed HIGH findings, so this gate is expected to block it. Resolve the findings with a supported remediated image or obtain the actual target's narrow security decision; this tutorial grants no exception. Keep the candidate private while investigating. Continue DNS/public HTTPS only after the release is accepted under the reviewed policy.

5. Connect a real hostname and HTTPS

In the authoritative DNS console, create an A record for the approved hostname pointing to the VM IPv4. If you deliberately use IPv6, validate the origin path and add its AAAA record. Record original values and TTL before modifying a record. Never repoint an existing unrelated site. From the laptop use dig YOUR_HOSTNAME A and, when applicable, dig YOUR_HOSTNAME AAAA. Replace that placeholder with the hostname you actually own. Check an independent resolver and allow cache convergence according to the previous TTL.

Install Caddy on the REMOTE fresh host. The following downloads key/source files before installing from the documented stable package repository:

bash
sudo apt install debian-keyring debian-archive-keyring apt-transport-https curl gnupg
curl -1sLf https://dl.cloudsmith.io/public/caddy/stable/gpg.key -o /tmp/mastery-caddy-key
curl -1sLf https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt -o /tmp/mastery-caddy-source
less /tmp/mastery-caddy-source
gpg --dearmor < /tmp/mastery-caddy-key | sudo tee /usr/share/keyrings/caddy-stable-archive-keyring.gpg > /dev/null
sudo install -m 0644 /tmp/mastery-caddy-source /etc/apt/sources.list.d/caddy-stable.list
sudo chmod o+r /usr/share/keyrings/caddy-stable-archive-keyring.gpg
sudo apt update
sudo apt install caddy

The official [Caddy installation guide](https://caddyserver.com/docs/install) describes package/service behavior. Installation starts a system service; this fresh host must not already host unrelated Caddy sites. The key is a package-signing key, not a secret. Review repository trust according to your policy.

Read the actual hostname into a variable and create a dedicated configuration:

bash
read -r -p 'Approved public hostname: ' MASTERY_DOMAIN
printf '%s {\n    request_body {\n        max_size 64KB\n    }\n    reverse_proxy 127.0.0.1:18768\n    log\n}\n' "$MASTERY_DOMAIN" > /tmp/mastery-Caddyfile
sudo caddy validate --config /tmp/mastery-Caddyfile --adapter caddyfile
sudo cp /etc/caddy/Caddyfile /etc/caddy/Caddyfile.before-mastery
sudo install -m 0644 /tmp/mastery-Caddyfile /etc/caddy/Caddyfile
sudo systemctl reload caddy
sudo systemctl status caddy --no-pager

Expected: configuration validation passes, service remains active and certificate issuance succeeds. From the LAPTOP, run curl --fail-with-body --max-time 10 "https://$MASTERY_DOMAIN/health/live" after setting MASTERY_DOMAIN there as well. Variables do not automatically cross an SSH boundary. Do not use -k; that disables the certificate verification you are trying to prove. Test HTTPS with a valid hostname, missing-token denial, authorized submission and final job completion. To make that external test concrete, create a one-hour read/write credential on the REMOTE host without printing it to the terminal:

bash
cd ~/playground/automation-service
umask 077
mkdir -p .recovery
set -a
. ./.env
set +a
sudo --preserve-env=LAB_TOKEN docker compose exec -T -e LAB_TOKEN api python - <<'PYTOKEN' > .recovery/external-client.json
import json,os,httpx
r=httpx.post('http://127.0.0.1:8000/credentials',headers={'Authorization':'Bearer '+os.environ['LAB_TOKEN']},json={'scopes':['jobs:read','jobs:write'],'ttl_seconds':3600},timeout=5)
assert r.status_code==201,r.status_code
print(json.dumps(r.json()))
PYTOKEN

On the LAPTOP, from your Crucible VM workspace (~/playground), retrieve that temporary credential over the verified SSH path and execute an actual public workflow:

bash
umask 077
mkdir -p .recovery
scp -i ~/.ssh/mastery-v5-lab "$MASTERY_ADMIN@$MASTERY_HOST:playground/automation-service/.recovery/external-client.json" .recovery/external-client.json
read -r -p 'Approved public hostname: ' MASTERY_DOMAIN
export MASTERY_DOMAIN
~/playground/automation-service/.venv/bin/python - <<'PYPUBLIC'
import json,os,time,uuid,httpx
from pathlib import Path
credential=json.loads(Path('.recovery/external-client.json').read_text())
base='https://'+os.environ['MASTERY_DOMAIN']
h={'Authorization':'Bearer '+credential['token'],'Idempotency-Key':str(uuid.uuid4())}
with httpx.Client(base_url=base,timeout=10) as c:
    assert c.get('/health/live').status_code==200
    assert c.post('/jobs',headers={'Idempotency-Key':'public-denied'},json={'text':'synthetic'}).status_code==401
    r=c.post('/jobs',headers=h,json={'text':'public workflow evidence'})
    assert r.status_code==202,r.status_code
    job=r.json()
    for _ in range(30):
        r=c.get('/jobs/'+job['id'],headers=h);r.raise_for_status()
        if r.json()['status'] in {'succeeded','failed'}:break
        time.sleep(.5)
    assert r.json()['status']=='succeeded',r.json()
    Path('.recovery/public-job.json').write_text(json.dumps(r.json()))
print({'public_job':job['id'],'result':'passed'})
PYPUBLIC

This credential is a secret despite its short lifetime. Keep its file private and remove it according to the exercise retention policy. Revoke it when the test ends rather than waiting for expiry. On the REMOTE host, inside the same example directory with LAB_TOKEN loaded:

bash
MASTERY_CREDENTIAL_ID=$(python3 -c "import json; print(json.load(open('.recovery/external-client.json'))['id'])")
export MASTERY_CREDENTIAL_ID
sudo --preserve-env=LAB_TOKEN,MASTERY_CREDENTIAL_ID docker compose exec -T -e LAB_TOKEN -e MASTERY_CREDENTIAL_ID api python - <<'PYREVOKE'
import os,httpx
r=httpx.delete('http://127.0.0.1:8000/credentials/'+os.environ['MASTERY_CREDENTIAL_ID'],headers={'Authorization':'Bearer '+os.environ['LAB_TOKEN']},timeout=5)
assert r.status_code==204,r.status_code
print('External test credential revoked')
PYREVOKE

Repeat the saved public GET using that credential and require401. A failed revocation remains an open security check.

If certificates fail, inspect sudo journalctl -u caddy --since '15 minutes ago' --no-pager, DNS A/AAAA, provider firewall80/443, other listeners, system time and challenge reachability. A working loopback health response does not establish public DNS/TLS. The minimal proxy is a controlled lab edge; before adversarial customer traffic add the reviewed identity/access gateway and appropriate connection, concurrency and unauthenticated abuse controls.

6. Operate, patch and recover the actual target

Compose restart policies start the application after the Docker daemon starts. Before declaring reboot recovery, schedule an approved VM reboot, reconnect and verify Docker, Caddy, readiness and a saved job. Record downtime. A restarted process with an empty database does not satisfy recovery.

Inspect sudo docker compose ps, bounded service logs, df -h, df -i, free -m and sudo journalctl -u docker -u caddy --since '1 hour ago'. Check disk growth, failed jobs, queue age, database connection pressure and latest usable backup. Maintain an operating calendar and named responder. Follow tutorial04 for the exact protected scraper/receiver configuration and fault/recovery delivery commands, on a private monitoring host or approved local installation; verify both firing and resolved delivery to the actual responder before acceptance. The native local receiver receipt does not validate your remote receiver.

Use the encrypted dump procedure in tutorial01 on the target, but send ciphertext to the approved independent backup destination. Keep the decryption identity on a separately controlled recovery system, and prove an operator can retrieve it when this VM is unavailable. Transfer ciphertext with scp over a verified host key to a pre-created restricted archive directory; confirm SHA-256 at both ends. Do not place an unencrypted .env or private age identity in a public bucket.

For fresh-host recovery, create a second approved VM with the same OS/architecture and recorded runtime. Follow steps1–4 to establish access, copy the same reviewed source/configuration and generate this replacement host's own .env. Load and verify the recorded image archive using tutorial03 step4 on that replacement host. Then establish the baseline Compose tag as an alias of that already-verified local image, without rebuilding:

bash
MASTERY_IMAGE_ID=$(python3 -c "import json,pathlib; print(json.loads((pathlib.Path.home()/'mastery-v5-artifact/artifact.json').read_text())['image_id'])")
sudo docker image inspect "$MASTERY_IMAGE_ID" --format '{{.Id}}'
sudo docker image tag "$MASTERY_IMAGE_ID" server-mastery-lab:5.0

Record the exact image ID; the convenience tag can move and is not itself immutable evidence. Obtain the trusted ciphertext at .recovery/lab.dump.age and retrieve the private age identity independently to .recovery/identity.agekey with 0600 permissions. The following is REMOTE replacement-host execution, inside its example directory, with only an empty newly created lab dataset:

bash
set -euo pipefail
umask 077
mkdir -p .recovery
sudo docker compose up -d --no-build --wait --wait-timeout 120 db
sudo docker compose run --rm --no-deps roleinit
age -d -i .recovery/identity.agekey -o .recovery/recovered.dump .recovery/lab.dump.age
sudo docker compose exec -T db pg_restore -U lab_owner -d lab --no-owner --no-acl --exit-on-error < .recovery/recovered.dump
sudo docker compose exec -T db psql -U lab_owner -d lab -v ON_ERROR_STOP=1 -c 'GRANT USAGE ON SCHEMA public TO lab_app; GRANT SELECT,INSERT,UPDATE,DELETE ON ALL TABLES IN SCHEMA public TO lab_app;'
sudo docker compose run --rm --no-deps seed
sudo docker compose up -d --no-deps --no-build --wait --wait-timeout 120 api worker
curl --fail-with-body --max-time 5 http://127.0.0.1:18768/health/ready

Do not run init before this restore: the dump reconstructs its own schema. A nonempty target, decryption failure or restore error stops acceptance; preserve it for diagnosis and provision another explicitly named empty dataset rather than dropping unknown tables. The seed command installs the replacement host's new bootstrap token after restoring old credential rows. Imported credentials remain a separate revocation decision. Source the replacement .env in a protected terminal and use the exact saved-job reader from tutorial01, supplying the original recorded job ID/result. Require its recovered result and duplicate identity. Also submit a fresh synthetic job and require completion before cutover.

Keep external side effects disabled during reconciliation. Compare the latest recovered committed event to the agreed RPO, and measure RTO from the actual incident/drill start to user-workflow verification. Do not route DNS until access, data, compatibility and queue behavior pass. If recovery fails, preserve both datasets, diagnose the first failure and return traffic to the still-valid old service only after checking consistency. Never overwrite the source host merely to prove recovery.

7. Migrate, retire and close the account inventory

Migration is a reviewed cutover, not merely changing an IP. Stop new writes or use a deliberately tested replication/migration method, capture the final recovery point, restore/reconcile on the replacement, validate it, shift approved traffic and monitor. Preserve the old host during the agreed rollback window. Account for queued jobs and external effects so two workers do not repeat business actions. A TTL change does not instantly remove cached addresses.

Retirement requires exact resource IDs and retained data decisions. Stop schedules and new submissions, settle accepted work, verify the final archive and its key, revoke unused service credentials, remove the approved DNS mapping and close the origin's listeners. On the retiring host, sudo docker compose down preserves the volume. Verify absence of intended traffic and record the precise volume/disk/image dependencies before permanent removal.

Then review the provider inventory: VM, attached/root disks, snapshots/backups, reserved addresses, firewall, DNS, registry artifacts, object storage, API credentials and monitoring schedules. Delete only owner-approved IDs after retention and rollback windows end. Check the provider's billing/resource inventory afterward. Removing the VM does not automatically establish that every dependent charge or access path is gone. Keep the redacted completion record and archived release; retain or revoke the dedicated SSH key according to its remaining authorized uses.

Verification, troubleshooting, cleanup and assessment

The public deployment passes only when a client outside the VM resolves the intended hostname, verifies trusted HTTPS, is denied without credentials, completes a job with a scoped credential and reads the saved result after an approved restart. Monitoring must reach its actual recipient; backup recovery must work on a separate host using independently available keys. Record environment, commands, versions, expected/actual results, failure and cleanup for every check.

A beginner should be able to explain where each input came from and which machine executes each command. The independent capstone requires diagnosing one fault in each layer, completing a compatible release/rollback, measuring recovery and producing a precise retirement inventory. Unexecuted remote checks remain pending in the project profile. Cleanup removes only the approved exercise resources; it never authorizes broad deletion of snapshots, volumes, keys or existing account configuration.

ACTIVE-RECALL MASTERY CHECKPOINT · TUT 02

Lock in what you just learned (3 quick questions)

PASS 2/3 FOR +30 XP
Q1.After hardening SSH on a remote Ubuntu host, why test a brand-new SSH login in a second terminal BEFORE closing your current session?
Q2.Which NGINX command validates syntax and upstream blocks BEFORE reloading live traffic?
Q3.Why should backend services (FastAPI :8000, PostgreSQL :5432) bind to 127.0.0.1 instead of 0.0.0.0 on a single-host server?
Answered 0 / 3