Skip to content

Containers and Docker

Phase 5 · Shipping and operating · 13 min read · 3 Atlas cases linked

What you'll be able to do

  • Explain what an image contains, what a container runs, and why a container is not a virtual machine.
  • Build and run a small Python API, map its port, and identify where persistent data belongs.
  • Arrange Dockerfile instructions for useful cache reuse and spot common security and state mistakes.

Why package an environment

Your notebook works, then fails elsewhere: a different Python version, OS library, or CUDA component changes what runs. A requirements.txt covers Python packages, not the whole environment. A container image packages an application with its runtime and filesystem dependencies. Pin versions and test the build; floating dependencies can still change tomorrow.

A container is an isolated process using the host kernel. Linux namespaces separate views of processes and networking; cgroups limit resources. A VM runs a guest kernel. On macOS and Windows, Docker Desktop typically runs Linux containers inside a Linux VM, so the kernel they share is that VM's. Containers start from an image, a read-only template. Running one image twice creates separate writable layers and process state.

Images stack read-only filesystem layers under a thin writable container layer. A union filesystem presents them as one view. A registry distributes images; docker pull retrieves one and docker push publishes one. Treat images as versioned artifacts and containers as disposable.

Build a tiny Python API

Put this in app.py. It needs only Python's standard library:

from http.server import BaseHTTPRequestHandler, HTTPServer

class Handler(BaseHTTPRequestHandler):
    def do_GET(self):
        body = b'{"status":"ok"}'
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

HTTPServer(("0.0.0.0", 8000), Handler).serve_forever()

Put this beside it in Dockerfile:

FROM python:3.12-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1
COPY app.py ./
RUN useradd --create-home appuser
USER appuser
EXPOSE 8000
CMD ["python", "app.py"]

FROM selects a base. WORKDIR sets the directory for later commands. COPY adds a file; RUN executes at build time. ENV sets runtime defaults. USER drops root privileges. EXPOSE documents a port; it does not publish it. CMD supplies the default startup command. ENTRYPOINT defines a fixed executable; CMD can provide its default arguments.

The server listens on 0.0.0.0 so container-network traffic can reach it. On 127.0.0.1, only processes inside that container could connect. Production needs an appropriate server and shutdown behavior.

docker build -t tiny-api:demo .
docker run --rm --name api -d -p 127.0.0.1:8000:8000 tiny-api:demo
docker ps
docker logs api
# request from the host; if the connection fails, wait a second and retry
python -c 'import urllib.request; print(urllib.request.urlopen("http://127.0.0.1:8000").read())'
docker exec api python -c 'print("inside container")'
docker stop api

The -p mapping is host-address:host-port:container-port; here it exposes port 8000 only on the host's loopback address. ps lists containers, logs reads output, exec starts a process inside one, and stop terminates it. The request from the host should print b'{"status":"ok"}', which exercises both the port mapping and the handler. Use --env NAME=value for ordinary runtime configuration and -v host-path:container-path for a bind mount. Command-line secrets may appear in shell history or process listings.

Build layers and cache misses

Docker reuses build work when an instruction and its inputs have not changed. If one step changes, later steps may rebuild. Package installation is often much slower than copying code.

For an API with pinned packages in requirements.txt, this ordering wastes work:

FROM python:3.12-slim
WORKDIR /app
COPY . .
RUN python -m pip install --no-cache-dir -r requirements.txt
CMD ["python", "app.py"]

Change one line of app.py: COPY . . changes, so the install step after it runs again. Instead, keep the dependency step before source code:

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt ./
RUN python -m pip install --no-cache-dir -r requirements.txt
COPY app.py ./
CMD ["python", "app.py"]

Now an app.py edit changes the later COPY, while installation can be reused. A requirements.txt edit rebuilds the install and later steps. If installation takes 90 seconds, five code-only builds could avoid 5 × 90 = 450 seconds of repeated work. This is an illustration.

The build context contains files sent to the builder. Exclude .git, .venv, caches, datasets, and secrets with .dockerignore. Pin base images and dependencies; use a digest and lock file for stricter repeatability. Prefer a slim base when it has what you need. A multi-stage build can keep compilers out of the final image.

State, networking, and multiple services

Remove a container and its writable-layer data disappears. Use a volume for managed persistent data or a bind mount for a host directory, often during development. Keep databases and uploads outside the writable layer; back them up.

docker run --name api -p 127.0.0.1:8000:8000 \
  -v "$(pwd)/data:/app/data" --env APP_MODE=local tiny-api:demo

The sample API neither reads APP_MODE nor writes to /app/data, so this command only shows the syntax. A real service running as a non-root user also needs permission to write to the mounted directory.

localhost inside a container means that container, not your laptop or another container. Compose services on one network can address each other by name. A local compose.yaml can define an API and database:

services:
  api:
    build: .
    ports: ["127.0.0.1:8000:8000"]
    environment:
      DATABASE_HOST: db
    depends_on: [db]
  db:
    image: postgres:<pinned-tag>
    volumes: ["dbdata:/var/lib/postgresql/data"]
volumes:
  dbdata:

This is a wiring sketch, not a runnable database example. Replace <pinned-tag> with a tested tag, and check that image's documentation for the data directory to mount, because it can differ between versions. Configure PostgreSQL's credentials and initialization, add database access to the API (the sample never reads DATABASE_HOST), and wait for readiness before expecting the stack to serve requests. depends_on orders startup; it does not prove readiness. Once those pieces exist, docker compose up --build builds and starts the stack, and the API container uses db as the database hostname.

Kubernetes schedules and replaces containers across hosts, provides service discovery, and manages rollout and health policies. It does not make an application stateless or solve storage design.

Operate the image safely

Run as a non-root user, and keep one main service process per container so its lifecycle and logs are clear. Add a health check that tests actual service readiness; a running process can still be unable to serve requests. Keep images small enough to move and scan efficiently. Never put credentials in a Dockerfile ENV, ARG, or copied file: build inputs and image history can expose them even if a later layer deletes the file. Supply secrets through an appropriate runtime secret mechanism.

Use an image tag or digest that identifies what you deployed. latest is a movable name, not a promise that two machines get the same bytes. A successful build also does not prove the application starts or can reach its database: run it and check a request. Containers make packaging repeatable only when you control the inputs and verify the result.

For AI engineers

For AI engineers

Your training script may import a pinned Python package yet depend on a particular system library or GPU stack. A container captures much of that user-space environment, while GPU execution also needs a compatible host driver and container runtime. Test on the target host; an image cannot supply its own host kernel or fix a missing driver.

Large ML dependencies and model weights make image size a design choice. Bake weights into the image when a fixed version and fast startup justify the larger artifact; mount them when a host manages the files; or download a versioned artifact at startup when storage and network behavior allow it. Record checksums and versions. Use pinned requirements or a lock file, and consider using the same validated image for training and serving components that must share preprocessing code, while keeping their entry commands separate.

Common mistakes

  • Putting COPY . . before dependency installation makes every source edit invalidate the expensive install step.
  • Using latest or unpinned packages makes a rebuild depend on what the registry serves that day.
  • Storing a password in ENV, ARG, or a copied file can publish it with the image or build records.
  • Running the service as root gives a compromised process more privileges than it needs.
  • Keeping important data only in the container's writable layer loses it when the container is replaced.
  • Calling localhost from the API container to reach a database container targets the API container itself.

Check yourself

You edit only app.py. Which steps rebuild in the two Dockerfiles above?

In the first, COPY . . changes, so the later package installation cannot use its old cache. In the second, COPY requirements.txt and package installation can be reused; the later COPY app.py and following steps rebuild.

Your API works on the host but cannot reach a database defined as db in Compose. Its connection string uses localhost. What should change?

Use db as the hostname from the API container. Inside that container, localhost refers to the API container, not the database service.

A container writes uploaded files under /app/uploads. You replace the container during a deploy. What happens, and where should those files live?

Files kept only in the old container's writable layer disappear with it. Put durable uploads in a volume or external storage and back them up according to the application's needs.

A teammate says the Dockerfile uses a pinned base image, so its builds must be identical. What else would you check?

Check that package versions and other build inputs are pinned, the build context excludes accidental files, and the base resolves to the same image bytes (a digest gives a fixed identity). Then build and run a smoke test.

Lab

In code/docker-containers/, implement a small Dockerfile parser, build-cache simulator, and linter. Start by joining continued lines and ignoring comments, then compare instruction and copied-file inputs. Report when latest, early COPY . ., root execution, remote ADD, or secret-like ENV creates risk. The lab uses inline Dockerfiles and needs no Docker installation or network access. Run: cd code/docker-containers && PYTHONPATH=starter python -m pytest tests -q

Go deeper

  • Docker documentation for Dockerfiles, images, storage, and Compose.
  • Kubernetes documentation for orchestration after you understand container boundaries.
  • Your Software Engineering Handbook, ch. 13 "CI/CD cơ bản", for building and shipping tested artifacts.

See it in the wild

Open these real architectures and find the idea in the diagram. Predict how it is used before you read the analysis.