Interview's MateAI Engineering
Interview's Mate

AI Engineering

LLMs, RAG, agents & evals

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
AI Engineering topics
Lesson 121/ 160
07. Deployment

Docker

Package AI services with reproducible images for local and cloud runs.

BeginnerImages · Containers · Repro3 quiz questions
Practice Generative AI Q&A
In plain wordsDiagramTheoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

Docker puts your app and everything it needs into one sealed box that runs the same way on any computer.

Think of it like…

A shipping container: whatever is inside, it has standard dimensions, so any ship, truck or crane can move it without caring about the contents, and a sealed container arrives the same as it left.

Where you’ve seen it

A FastAPI service that calls an LLM and a vector database has a Dockerfile in two stages. The build stage starts from a full Python image (about 1 GB), installs compilers and builds wheels; the runtime stage starts from a slim Python image (about 130 MB), copies only the installed packages and the app, runs as a non-root user and defines a health check and the start command. Layer order matters: copying requirements.txt and running pip install first means a code-only change reuses the cached dependency layer, so a rebuild takes 4 seconds instead of 90. A .dockerignore excludes .git, notebooks and local data so the build context shrinks from 800 MB to 12 MB. For a self-hosted model the team does not bake weights into the image: an 8B model in FP16 is 16 GB, which would make every deploy slow. Instead, the container downloads the weights at start-up (or mounts a volume). Cold-start arithmetic: pulling a 6 GB CUDA-based image at 100 MB/s takes 60 s, and loading 14 GB of weights at 500 MB/s adds 28 s, so replicas need about 90 s before they're ready, which drives the readiness-probe and autoscaling settings. The image is scanned for vulnerabilities in CI and tagged with the git commit SHA, never only latest.

Words you’ll hear

Image / container
An immutable layered template, and a running instance of it.
Multi-stage build
Using one stage to build and a clean stage to run, copying only what's needed.
Layer cache
Reuse of unchanged build steps; order instructions from least to most frequently changing.
Build context / .dockerignore
Files sent to the builder, and the list of those to exclude.

Visual diagram

Loading interactive diagram

Theory & deep dive

Writing a good Dockerfile for an AI service

Choose a base image deliberately: python:3.12-slim (about 130 MB) for CPU services; Alpine images often cause trouble with Python wheels (musl instead of glibc); for GPU workloads use NVIDIA's CUDA runtime or a framework image (PyTorch or vLLM images range from several to ten gigabytes), matching the CUDA version to the host driver. Pin the base by version or digest so rebuilds are reproducible. Structure the file: WORKDIR /app, COPY requirements.txt ., RUN pip install --no-cache-dir -r requirements.txt, then COPY . .. Because Docker caches each instruction by its inputs, a source change invalidates only the layers after it, so dependency installation is skipped. Use multi-stage builds so compilers, build caches and test tools don't ship, and .dockerignore to keep the context small and keep secrets such as .env out.

Security and operability: run as a non-root user (USER app), drop capabilities where possible, set a HEALTHCHECK or rely on orchestrator probes, use EXEC form for CMD so signals reach the process (graceful shutdown for in-flight streams), and write logs to stdout. Never COPY secrets or put them in ENV/ARG, since they persist in image layers and history; inject them at runtime. For GPU containers, install the NVIDIA Container Toolkit on the host and run with --gpus all. Pin Python dependencies with a lock file so a transitive upgrade can't change behaviour, and rebuild periodically to pick up security patches.

Layer ordering effect

Dockerfile order: base → system packages → COPY requirements.txt → pip install (90 s) → COPY . . → CMD. Editing app code reuses the first four steps from cache: rebuild 4 s. If COPY . . came before pip install, every code edit would reinstall dependencies: 90 s.

Key takeaway: Use slim pinned bases, multi-stage builds, dependency-first layer order, non-root users and runtime secret injection.

Images, models and CI/CD

Model weights: don't bake multi-gigabyte files into images. Options: download at start-up from object storage or a model hub into a mounted volume (cache it so restarts are fast), mount a shared read-only volume, or pre-pull onto nodes with a DaemonSet. Image size drives cold-start time: pulling a 6 GB image at 100 MB/s takes 60 s, and loading 14 GB of weights at 500 MB/s another 28 s; plan readiness probes, autoscaling headroom and node image caching around that (about 90 s in the example). Layer-level caching in the registry and on nodes helps, and lazy-pulling snapshotters can start containers before the full image arrives.

In CI, build with BuildKit and remote layer caches, tag images with the git SHA (plus a human-readable version), scan with a vulnerability scanner (Trivy, Grype), generate an SBOM and sign images so production only runs trusted artefacts. Promote the same image from staging to production rather than rebuilding, so what you tested is what you ship. Keep one image per service role (API, worker, scheduler) or one image with different commands, and make configuration environment-driven. Limit resources with --memory and --cpus (or Kubernetes requests and limits) so a runaway container can't starve the host, and test the image locally with the same command CI uses.

Cold-start budget

Image 6 GB ÷ 100 MB/s = 60 s. Weights 14 GB ÷ 500 MB/s = 28 s. Total ≈ 88 s, so the startup probe must allow at least 90 to 120 s, and autoscaling should add replicas well before saturation.

Key takeaway: Keep weights out of images, budget cold-start time, tag by SHA and promote the same scanned image through environments.

How it works, step by step

Step 1 of 4
Engineer

1. Write a lean Dockerfile

Pin a slim base, copy dependency files first, install, then copy code; add a non-root user and a start command.

python:3.12-slim · multi-stage
Key numbers at this step
Context
use .dockerignore

When to use it & trade-offs

What it is

Docker packages an application and its dependencies (Python version, system libraries, Python packages, start command) into an image, a layered, immutable filesystem snapshot, which runs as an isolated process called a container. For AI services this gives reproducibility (the same image runs on a laptop, in CI and in production), isolation between services with conflicting dependencies and a standard unit for orchestrators such as Kubernetes. Good AI images are small, cache-friendly (dependencies installed before code is copied), multi-stage (build tools stay out of the final image), run as a non-root user, contain no secrets and keep very large artefacts such as model weights outside the image.

Why it matters: "Works on my machine" is the classic AI deployment failure: a slightly different CUDA, tokenizer or package version changes outputs or crashes startup. Containers make the runtime part of the artefact you test and ship, speed up CI by caching layers and let you roll back to an earlier image in seconds. They also make a few AI-specific mistakes easy to commit: baking secrets into layers, shipping a 12 GB image because weights were copied in, or rebuilding all dependencies on every code change.

When to reach for it

  • Packaging APIs, workers and schedulers
  • Running the same stack locally, in CI and in production
  • Serving open models with pinned CUDA stacks

When to avoid or be careful

  • Baking secrets or model weights into image layers
  • Using :latest tags in production
  • Running containers as root with no resource limits

Packaging choices

Container image
Best for: Reproducible services on any host or orchestrator

Strengths: Portable; cacheable; rollback by tag.

Watch out: Image size and cold starts; needs registry hygiene.

Virtual environment on a VM
Best for: Single-host simple deployments

Strengths: Simple; no container runtime.

Watch out: Drift between machines; harder to scale and roll back.

Serverless function bundle
Best for: Small event-driven glue code

Strengths: No servers to manage.

Watch out: Size and runtime limits; cold starts.

Interview signals & numbers to know

When this topic comes up

  • “It works on my machine”
  • Multi-stage builds
  • Layer caching
  • Cold start of GPU pods
  • Image scanning

Benchmarks & rules of thumb

~1 GB vs ~130 MB -
full versus slim Python base image
90 s → 4 s -
dependency rebuild versus code-only rebuild with caching
60 s + 28 s -
pull a 6 GB image and load 14 GB of weights

Common mistakes & follow-ups

Common interview mistakes

  • Copying the whole repo before installing dependencies, busting the cache every time.
  • Putting an API key in an ENV line that stays in image history.
  • Shipping a 20 GB image because weights were copied in.

Likely interviewer follow-ups

  • How would you containerise an LLM API service?
  • Why are multi-stage builds useful?
  • How do you handle large model files with Docker?
Interview tip: Give the cold-start arithmetic (pull time plus weight load). It connects Docker choices to autoscaling and probe settings.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply Docker with generative AI interview Q&A and hands-on practice.

Open Generative AI Q&A →Tech Learn Q&A
Previous topic
Red Teaming
Next topic
Docker Compose