HTMLCSSJAVASCRIPTANGULARINTERVIEW QUESTIONSSQLPYTHONJAVAPHPHOW TOW3.CSSCC++C#BOOTSTRAPREACTNEXTJSMYSQLJQUERYEXCELXMLDJANGONUMPYPANDASNODEJSDSATYPESCRIPTANGULARJSGITPOSTGRESQLMONGODBASPAIRGOKOTLINSWIFTSASSVUEGEN AIAGENTIC AIPROMPT ENGINEERINGDOCKERKUBERNETESSPRINGSPRING BOOTUNIXSCIPYAWSCYBERSECURITYDATA SCIENCEINTRO TO PROGRAMMINGINTRO TO HTML & CSSBASHRUSTTOOLS
AI-Powered Full Stack Tutorial 0/70 lessons ~6 min read Lesson 57“React, Next.js, Node, PostgreSQL, LLMs, RAG, agents, and production AI apps”
Docker, Containers and Local Development Environments
CI on TechLearningPro was green.
Course progress0%
Focus
16 guided sections
Practice signal
Concept-first lesson
Career prep
Foundation builder
AI-Powered Full Stack Development · Lesson 57 · Full-Stack Security, Testing and Deployment
Lesson Overview
CI on TechLearningPro was green. A new engineer still could not mark a lesson complete. Their laptop had no PostgreSQL, so the API had been pointed at a file database "for the afternoon." The tutor looked fine because the fake gateway lived in the same Node process. The first time they pulled a branch that expected the vector extension and a separate fixture model, the player spun and the progress write failed a constraint the file database had never enforced. The pipeline had tested an image. The laptop had tested a different computer.
A container image is a packed filesystem plus the command that starts the process. A container is a running instance of that image. Compose is the file that starts the set of containers a full-stack product needs on one machine: the API, the lesson player, PostgreSQL, and a fixture model that speaks HTTP and holds no credential. Docker is the tool this lesson uses to build and run them. The idea is older than the brand: ship the runtime with the app so "my machine" is a description of the image, not of whoever cloned the repo.
/learn/docker is the containers course: layers, registries, networking, and image hygiene in depth. This lesson is the TechLearningPro local stack those skills sit under, including the rule the CI lesson just set. The image does not contain a provider key. Local mode is TUTOR_MODE=fixture. The same image digest the pipeline records is the image Compose can run.
The next lesson chooses where that image runs in the cloud, and when a container is the wrong runtime. You need the local stack first so the choice is about production constraints, not about whether the app starts.
Planning assumptions:
Local PostgreSQL is a Compose service with a password that exists only on the laptop. The value local_dev_only in the example is a marker, not a production secret, and it must not be reused in any deployed environment.
The fixture model is a tiny HTTP process in the repo. It does not call a provider and it does not read a key.
Illustrative local budget: API container memory 512 MB, Postgres 1 GB, fixture model 128 MB. Those are lab ceilings so a runaway prompt log cannot fill the disk. Replace them when you measure a real machine.
Bind-mounting source is for the inner loop. The CI image copies source in and does not mount the laptop.
Learning Objectives
By the end of this lesson you will be able to:
Define image, container, layer, registry, volume, network, and healthcheck in product language.
Explain why a green CI job can still disagree with a laptop that is not running the image.
Write a multi-stage Dockerfile that compiles TypeScript, runs as a non-root user, and does not copy env files.
Compose the API, the web player, PostgreSQL, and a fixture model on one private network.
Keep TUTOR_MODE=fixture as the local default so a provider credential is unnecessary.
Refuse to start the API when a live-key prefix is present in the environment.
Use a healthcheck so Compose does not send traffic to Postgres or the API before they can answer.
Ignore node_modules, .env, and git metadata in the build context.
Separate the dev compose file (bind mounts, published ports) from the release image (immutable files, no bind mount).
Read a container log without printing connection strings or prompts.
Tear the stack down, including anonymous volumes, when the lab ends.
Point at /learn/docker for the layer and registry depth this lesson deliberately does not repeat.
/learn/docker if you want the engine internals. You can finish this lesson with Docker Desktop or a compatible engine installed, plus the ability to read a Dockerfile.
You do not need a cloud account or a provider key.
Detailed Core Concepts
What a container changes
Without an image, the README is the environment: install Node 22, install Postgres 16, create a database, export four variables, hope the extension exists. Each of those steps can be half-done. With an image, the API's filesystem already contains the runtime and the compiled JavaScript. Postgres is a second image, pinned by digest in production and by a major tag in the lab, with a note to pin the digest before the file is a release control.
The container is not a virtual machine you administer by SSH. If you need a shell to make the app true, the image is wrong. Change the Dockerfile, rebuild, and run again. That habit is what makes CI and the laptop the same artifact.
Term
Meaning here
Image
Built filesystem and start command, identified by digest
Container
A running image with its own process, filesystem changes, and network address
Layer
A cached step in the build. Copy the lockfile before the source so installs cache
Registry
Where CI pushes the digest and production pulls it
Volume
Persistent disk for Postgres data. The container's writable layer is not a database
Network
The Compose project network. Service names are DNS names
Healthcheck
A command whose success means "ready," not merely "process started"
Context
The files sent to the builder. Smaller is faster and safer
The local stack for this product
Four processes, four responsibilities:
Service
Owns
Does not own
web
The lesson player, calling the API
Provider credentials, completion rules
api
Auth checks, progress writes, tutor orchestration
Pixel layout, long-term backups
postgres
Durable progress and constraints
Generated tutor prose as truth
fixture-model
A fixed draft or a typed failure over HTTP
A real model, a key, learner data
The browser on the host reaches web and, in dev, api through published ports. fixture-model is not published to the host in the release compose file. Only the API network can call it. That keeps a curious browser tab from treating the fixture as an open proxy you might later point at a real provider.
Dev loop versus release image
The inner loop bind-mounts your source into a container that runs the TypeScript watcher. That container is allowed to differ from production in one way: it compiles on start. It is not allowed to differ in dependencies. It installs from the same lockfile. The release image copies compiled output, sets NODE_ENV=production, and has no watcher and no mount of your home directory.
A common failure is mounting node_modules from the laptop into a Linux container. Native addons built on macOS do not run in the image. Let the image install its own modules. Mount the source, not the laptop's node_modules.
Fixture model as a sidecar
The fixture sidecar replaces the in-process fake when you want the wire shape: the API calls http://fixture-model:8080/complete with a timeout. The sidecar returns the same union the model port already uses: { ok: true, text } or { ok: false, reason }. Switching TUTOR_MODE to live is a production concern and a secret-store concern. The local compose file does not have that mode. If someone exports a live key in the shell and Compose interpolates it, the API process refuses to boot. The check is in the next section.
Data that must survive a restart, and data that must not
Postgres data lives in a named volume. Tutor drafts do not need a volume. Container logs are not the system of record. A prompt that included a learner excerpt must not be written to a world-readable bind mount "so I can tail it." Log ids, prompt version, latency, and token counts, the same fields the API lesson already chose.
Architecture and Request Flow
flowchart LR
subgraph host [Laptop]
Browser[Browser]
end
subgraph net [Compose network]
Web[web]
API[api]
DB[(postgres)]
Fix[fixture-model]
end
Browser -->|published port| Web
Browser -->|published port in dev| API
Web --> API
API --> DB
API -->|HTTP no credential| Fix
text
compose up
-> postgres healthy
-> fixture-model healthy
-> api boots, rejects tlp_live_ prefix, waits for postgres
-> web serves the player
-> POST /progress writes a quiz fact
-> POST /tutor calls fixture-model and returns a draft or a typed fallback
compose down -v
-> containers stop
-> the named volume can be removed when the lab is over
Trust boundary: the laptop is a developer workstation. It may hold synthetic data. It may not hold a copy of production. The fixture sidecar is inside the trust of the API only because it cannot reach a provider. The moment the sidecar is configured with a key, it becomes a second secret store and a second egress path. Do not do that on the local stack.
Step-by-step Implementation
Files live under deploy/local/. The API boot check lives in packages/api/src/boot.ts.
Step 1: Ignore secrets and host junk
deploy/local/.dockerignore
dockerignore
.git
node_modules
.env
.env.*
!.env.example
**/*.pem
dist
The exception !.env.example lets the example file into the context if a tool needs it. The image stage below still does not COPY it into the runtime filesystem. .env never enters the context, so it cannot be copied by accident.
# Create a user so the process is not root if the app is compromised.
RUN useradd --create-home --uid 10001 appuser
COPY --from=build /app/dist ./dist
COPY --from=deps /app/node_modules ./node_modules
COPY package.json ./
USER appuser
EXPOSE 3000
CMD ["node", "dist/packages/api/src/main.js"]
TUTOR_MODE=fixture is baked as the default. A compose environment block can override it. The boot check rejects the live prefix either way. No ARG copies a key into a layer. Build-args are visible in image history.
The check looks for the same fictional prefix as the CI scanner. It does not log providerKey. On failure the process exits 1 and Compose restarts until the backoff stops, which is the signal you want: the stack is not "up" if the mode is wrong.
local_dev_only is a laptop password published in this lesson on purpose so nobody mistakes it for a vault entry. Production compose, if you ever have one, does not contain a password. It references the secret manager. The database port publish is a dev convenience. A release network does not publish Postgres to the host.
Step 5: Fixture sidecar and health
The sidecar is a second image. It has no provider SDK and no env file. FIXTURE_MODE=ok returns a fixed draft. FIXTURE_MODE=timeout returns the typed failure so you can practice the player fallback without a real outage.
A 503 on boot failure is what Compose and the CI smoke check both read. The body has a reason code, not a connection string.
Step 6: Dev override, then run and clean up
deploy/local/compose.dev.yaml bind-mounts source for the API only. It does not mount node_modules, and it does not change TUTOR_MODE.
yaml
services:
api:
volumes:
- ../../packages:/app/packages:ro
environment:
TUTOR_MODE: fixture
bash
docker compose -f deploy/local/compose.yaml -f deploy/local/compose.dev.yaml up --build
docker compose -f deploy/local/compose.yaml ps
# Progress route returns a fact. Tutor route returns a draft from the sidecar.
docker compose -f deploy/local/compose.yaml down --volumes
down --volumes deletes pgdata. Use it at the end of the lab. Omit --volumes if you need the synthetic rows tomorrow. Do not copy pgdata from a production snapshot onto this volume.
Health is GET /health on the API returning { "ok": true, "mode": "fixture" } with no dependency passwords in the body. The Postgres check is pg_isready, which does not print the URL.
Security
Authentication is still the API's job. The container network does not authenticate learners. Publishing port 3000 on a laptop is fine. Publishing it on a shared dev server without the session check is not.
Authorization does not move into Compose. A container that can read Postgres must still send tenant predicates. Being "inside Docker" is not a trust decision.
Least privilege. The runtime user is uid 10001. The container does not need SYS_ADMIN. Do not add privileged: true to make a mount work.
Input validation at boot: mode, database URL presence, live-prefix rejection. The URL is not logged.
Secrets. None are required for fixture mode. If a future lesson injects a key, use a runtime secret mount, not a layer. .dockerignore is what keeps today's .env out of the context.
Tenant isolation. The local database holds one synthetic tenant. Do not restore a customer dump to pgdata.
Egress. The fixture container has no provider URL. A default Compose network can still reach the internet if the host can. A locked-down lab can set internal: true on a network used only by the sidecar when you are ready to debug DNS. Start with the simple project network. Do not "fix" a timeout by giving the sidecar your host credential environment.
Error Handling
Symptom
Likely cause
What you do
API exits immediately
decideBoot returned live_key_present or bad_mode
Unset the key. Set TUTOR_MODE=fixture. Read the reason code, not a dumped env
API waits forever
Postgres healthcheck failing
docker compose logs postgres. Fix the volume permissions. Do not point the API at a host database to cheat
Tutor panel empty
Fixture sidecar down, API returned unavailable
The player still shows the lesson. Restart the sidecar. Confirm the API timeout is finite
Port already allocated
A host Postgres or an old stack owns 5432
Stop the other process or change the host port, not the container port the API uses by DNS
Native module crash
Laptop node_modules was mounted
Remove the mount. Rebuild
Disk fills
pgdata plus container logs of full prompts
Log sizes and ids. down --volumes only if the data is synthetic
Compose restart policies are for crashes, not for a misconfiguration you should see. restart: unless-stopped on a boot rejection hides the lesson. Leave restart off in the lab file so the exit code stays visible.
Add a test that a missing database URL is missing_database even when mode is fixture. The image itself is tested by building it in CI after the unit tests, then running decideBoot inside docker run with an explicit env and no network. That test is the proof the laptop and CI share code. It does not need a registry.
A Playwright run from lesson 55 can target http://localhost:5173 once compose ps shows healthy. Keep that browser job on the fixture stack.
Performance and Cost
Local containers spend laptop RAM and disk, which developers feel immediately, and CI minutes, which the team pays.
Multi-stage builds drop the compiler from the runtime image. Smaller images pull faster in CI and have less software to patch.
Copy the lockfile in its own layer so npm ci caches when only lesson text changes.
Do not use the release image as the dev watcher. Rebuilding a full image on every keystroke is the slow loop. Bind-mount source in a dev override file.
Set a memory limit on the fixture sidecar. A log bug should not take the machine down.
Postgres on a laptop volume is slower than a native install on some disks. That is acceptable for correctness. It is not a benchmark of production.
Pull base images by digest in CI so a rebuilt node:22-bookworm-slim tag does not change the API digest without a lockfile change. The lab file uses the tag for readability and says so, the same way the workflow lesson treated action tags.
Cost of the fixture sidecar is zero tokens. If someone points FIXTURE_MODEL_URL at a provider, the local stack becomes a billing path. The boot check exists so that change cannot be silent.
Knowledge Check
1. What problem does the local stack solve?
It makes the API, the player, PostgreSQL, and the fixture model the same shape CI runs, so a missing extension or a fake in-process shortcut is visible before review. It does this without a provider key.
2. What alternatives exist, and when would you choose each?
Compose fits this multi-process product on a laptop. A single node process plus a hosted dev database fits a one-service prototype and drifts the day you need the extension. A full cluster on the laptop fits platform engineers rehearsing orchestration and is too much for the tutor lab. A remote dev environment fits teams that refuse local Docker, and it still needs the same image and the same secret rules.
3. Which data, identity, and trust boundaries matter?
The API owns authorization. The fixture model has no key and is not published as a public proxy. Postgres on the laptop holds synthetic data in a named volume. The image build context excludes .env. The process user is not root.
4. What can fail, and how should the system respond?
Boot rejects a live key, a non-fixture mode, or a missing database URL and exits. A sidecar timeout becomes the typed tutor fallback. The lesson still renders. A healthcheck failure delays depends_on instead of crashing into a connection storm. down --volumes is how you throw away synthetic data on purpose.
5. How would you test quality, security, performance, and cost?
Unit-test decideBoot. Build the image in CI and run it with fixture env and no network. Confirm .env is absent from docker image history by never copying it. Watch image size and startup time. Confirm the local path makes zero provider calls by leaving the key unset and asserting the sidecar URL is the Compose DNS name.
Hands-on Assignment
Lab note. Fixture mode only. The database password in the compose file is local_dev_only. Do not reuse it anywhere else. Do not restore production data.
Problem. Bring up TechLearningPro's four-service local stack and prove the API will not boot if a live key is injected.
Tasks.
Draw the Compose network. Mark which ports are published to the host and which stay internal.
Add the Dockerfile, .dockerignore, decideBoot, and compose.yaml from this lesson.
Run the boot tests, then docker compose up --build and show a healthy API and a tutor draft from the sidecar.
Inject PROVIDER_KEY=tlp_live_exampleblocked in a throwaway shell and show the API exits with live_key_present. Unset it afterward.
Write six controls: non-root user, dockerignore for .env, fixture default, healthchecks, unpublished fixture port, synthetic data only.
Tear the stack down. Say whether you deleted the volume and why.
Deliverable. Diagram, the files with no real secrets, test output, compose ps or an equivalent health note, and a trade-off note on bind-mount dev versus the immutable image.
Challenge. A teammate wants the sidecar on the public internet so a designer can hit it from a phone, and wants the production prompt log mounted to the desktop. Refuse both. Describe the port binding and the log fields you would allow instead.
Rubric. Conceptual accuracy and architecture 20%. Working implementation and code quality 25%. Security, privacy, and responsible AI 20%. Testing, reliability, and observability 20%. Documentation and decision rationale 15%.
Common Mistakes
Copying .env into the image. Symptom: a key shows up in docker image history or in a layer diff. Cause: COPY . . with a careless dockerignore. Fix: ignore env files, pass runtime config, rotate if a real key was copied.
Running as root. Symptom: a compromised process can rewrite the image filesystem and package manager state. Cause: the official Node image's default user was left in place. Fix: USER appuser.
Publishing Postgres and the fixture to 0.0.0.0 on a shared machine. Symptom: another host writes your synthetic database or abuses the sidecar. Cause: dev ports copied into a long-lived environment. Fix: publish to localhost, or do not publish internal services.
Mounting laptop node_modules. Symptom: the container crashes on a native binding. Cause: a bind mount that felt faster. Fix: install inside the image.
Using latest for Postgres in a shared lab. Symptom: Monday's machine migrates a volume Friday's machine cannot open. Cause: an unpinned tag moved. Fix: pin a major version in the lab and a digest in CI.
Storing tutor prompts on a bind-mounted log. Symptom: learner text sits on disk in a backup. Cause: debug logging left on. Fix: log ids and sizes.
Pointing the local API at a production database. Symptom: a migration or a bad query hits real learners. Cause: one DATABASE_URL in the shell. Fix: local volume only. Production credentials are not on the laptop.
Treating a started process as a ready database. Symptom: the API crashes on boot with a connection refused, then restart-loops. Cause: no healthcheck. Fix: pg_isready and depends_on.condition.
SSHing into the container to apply a fix. Symptom: the next rebuild erases the fix and CI never had it. Cause: the container was treated as a pet server. Fix: change the Dockerfile or the source and rebuild.
Leaving volumes after a lab that used realistic personal data. Symptom: a customer-like dump remains on disk. Cause: down without --volumes, or a dump that should never have been there. Fix: synthetic data only, then delete the volume.
Summary
The local environment is a Compose stack that runs the same API image CI will digest: non-root, fixture tutor, PostgreSQL with real constraints, and a sidecar that cannot hold a provider key. Bind mounts are for the edit loop. They are not a second way to inject secrets or host node_modules. /learn/docker covers image internals this lesson used without re-teaching. The cloud lesson takes this image and asks which managed runtime is allowed to run it.