Docker Fundamentals — Images, Containers and Dockerfiles

What containers are, writing a Dockerfile for a Python API, layers and caching, volumes, ports, and image hygiene.

Est. 40 min Updated Suggest a fix
// Part 01 — Why containers

Package an App with Its Runtime Expectations

An application may work on one laptop and fail on another because the Python runtime, system libraries, or configuration differ. A container image packages an application filesystem and its dependencies using the host operating system's kernel. Docker provides tools to build images and start containers from them. Containers are isolated processes, not full virtual machines: they share the host kernel, so kernel-level isolation and host security still matter.

An image is a reusable, built artifact; a container is a running (or stopped) instance created from that image. One image can start many containers with different names, environment settings, and published ports. The container's writable layer is normally ephemeral. Data that must survive replacement belongs in a volume or an external data service, not only in the container filesystem.

ConceptWhat it isOperational implication
ImageRead-only layers and metadata used to start containersBuild, tag, scan, and publish deliberately
ContainerA process created from an image with runtime settingsReplace it rather than editing it by hand
VolumePersistent storage managed outside the container layerBack up and protect it separately
Port mappingA host port forwarded to a container portExpose only the service that needs access
💡 Note
Containers improve repeatability, but do not make an application secure by default. Keep base images maintained, restrict privileges, protect secrets, and patch the host as well as the image.
// Part 02 — First container

Build and Run a Small FastAPI Service

We will package a tiny FastAPI application. The app listens on port 8000 inside the container. Docker's published port mapping connects a host port to that container port; the two numbers need not be the same. A containerized web server must listen on an address reachable inside the container, not only the loopback interface.

app/main.py
python
from fastapi import FastAPI

app = FastAPI(title="Delivery status API")

@app.get("/health")
def health():
    return {"status": "ok"}
bash
# In the project directory containing Dockerfile and app/:
docker build -t delivery-status-api:dev .
docker image ls delivery-status-api
docker run --rm --name delivery-api -p 8000:8000 delivery-status-api:dev

# In another terminal, call the published endpoint.
curl http://localhost:8000/health

The image tag dev is a local label, not a guarantee of immutable content. For releases, use a deliberate version or content digest and record which artifact was deployed. --rm removes the stopped container after this local run; it does not delete the image. Keep interactive experiments separate from production run configuration.

🎯 Pro Tip
If the API responds inside the container but not from the host, check the app's bind address, the container port, the published host port, and local firewall rules as separate things.
// Part 03 — Dockerfile

Describe the Build in a Dockerfile

A Dockerfile is a recipe for building an image. FROM chooses a base image, WORKDIR sets the working directory for later instructions, COPY adds selected files, RUN performs build steps, and CMD supplies the default process when a container starts. Choose maintained base images appropriate for the app, and review their provenance and update policy rather than relying on an arbitrary image.

Dockerfile
dockerfile
FROM python:3-slim

ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1
WORKDIR /app

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt
COPY app ./app

EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
requirements.txt
bash
fastapi
uvicorn

EXPOSE documents the port the application uses; it does not publish that port to the host. The CMD array form runs the process directly and makes signal handling clearer than a shell wrapper. Install dependencies from a lock or constraints file for reproducible production builds; an unpinned development requirements list can change over time as upstream packages release updates.

⚠️ Important
Do not copy a local .env, cloud credential, or private SSH key into an image. Anything copied into an image layer can remain recoverable even if a later layer deletes it. Pass runtime secrets through an approved secret mechanism, not a Dockerfile ENV instruction.
// Part 04 — Layers and cache

Order Instructions to Reuse Work

Many Dockerfile instructions create image layers. If an earlier layer's inputs are unchanged, the build engine can reuse its cached result. Copying all source files before installing dependencies means a one-line code edit can invalidate the dependency-install layer. Copying dependency manifests first lets ordinary code changes reuse dependency installation. Cache behavior depends on the instruction and its inputs; changing a base image or a dependency manifest appropriately requires rebuilding the affected steps.

Dockerfile layer order
dockerfile
FROM python:3-slim
WORKDIR /app

# Dependency inputs change less often than application source.
COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

# Copy code after dependency installation to preserve useful build cache.
COPY app ./app
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

The build context is the set of files sent to the builder, commonly the current directory when using a final dot. A smaller context reduces unnecessary transfer and reduces the chance of including local-only files. Add a .dockerignore that excludes virtual environments, Git metadata, caches, local secrets, and generated artifacts that the image does not need.

.dockerignore
bash
.git
.venv
__pycache__
*.py[cod]
.env
*.log
📌 Real World Example
If a Swiggy-style delivery API changes its Python code every day but dependencies only occasionally, putting the requirements copy and install before the source copy avoids reinstalling packages for every code edit.
// Part 05 — Multi-stage builds

Separate Build Dependencies from Runtime

Multi-stage builds use one stage to prepare artifacts and another stage for the final runtime image. The final stage copies only what it needs from the builder, which can reduce image size and avoid shipping build-only tools. The example creates an isolated Python installation prefix in a builder stage and copies that prefix into a clean runtime stage. Test the resulting image: native dependencies, certificate stores, and runtime shared libraries may need to be present in both stages.

Dockerfile.multi
dockerfile
FROM python:3-slim AS builder
WORKDIR /build
COPY requirements.txt ./
RUN pip install --no-cache-dir --prefix=/install -r requirements.txt

FROM python:3-slim AS runtime
ENV PYTHONDONTWRITEBYTECODE=1 \
    PYTHONUNBUFFERED=1
WORKDIR /app
COPY --from=builder /install /usr/local
COPY app ./app
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

Multi-stage builds are not automatically safer or smaller; verify the final artifact and dependency behavior. Use an appropriate non-root runtime user when the application permits it, keep only necessary packages, and avoid embedding build credentials. Production build pipelines should also scan images and make rebuilds available when upstream vulnerabilities are fixed.

  1. Build from a small, reviewed context with a .dockerignore.
  2. Install dependencies using an appropriately reproducible manifest.
  3. Copy only application files and runtime artifacts into the final stage.
  4. Run a smoke test against the built image and record its tag or digest.
// Part 06 — Runtime data and networking

Keep State Outside Replaceable Containers

A container's writable layer is coupled to that container's lifetime. A bind mount maps a host path into the container and is convenient for local development; a named volume is managed by Docker and is commonly used for persistent container data. Mounts can also expose host files, so do not mount broad paths or credentials without a reason. Back up important state and practice restores; persistence alone is not a backup.

bash
# Development: mount source into the app container for local iteration.
docker run --rm -p 8000:8000 \
  --mount type=bind,source="$PWD/app",target=/app/app \
  delivery-status-api:dev

# Named volume example for a service that writes durable data.
docker volume create api-data
docker volume inspect api-data

Port mapping has the form host port followed by container port. For local-only testing, binding to the loopback host interface avoids exposing the port on every network interface. In production, the network boundary should be controlled by the platform and firewall policy, not by an assumption that an unpublished container is inherently safe. Containers can communicate on a Docker network without publishing every internal service port to the host.

bash
# Expose the service to this machine only.
docker run --rm -p 127.0.0.1:8000:8000 delivery-status-api:dev

# Inspect the running container and its logs.
docker ps
docker logs delivery-api
docker inspect delivery-api
🎯 Pro Tip
Use docker logs to inspect a container's standard output and error. Applications should generally log to those streams in containers so the platform can collect and route the logs.
// Part 07 — Operations

Run, Observe, and Stop Containers Intentionally

Containers should run one main application process and report status through logs and health checks where the platform supports them. Use a meaningful container name when useful, inspect logs and exit status, and stop a container gracefully before removing it. Avoid editing a running container as a deployment method: those changes are not captured in the image and disappear when it is replaced. Change the build inputs, build a new artifact, and run that artifact instead.

bash
docker run -d --name delivery-api -p 127.0.0.1:8000:8000 delivery-status-api:dev
docker ps
docker logs --tail 50 delivery-api
docker stop delivery-api
docker rm delivery-api

A development bind mount can intentionally replace files from the image during local work; it should not be confused with a release artifact. Set container resource limits and restart behavior through the orchestrator or deployment configuration appropriate to your environment. Keep runtime configuration separate from the image so the same artifact can be promoted through test and production environments.

QuestionLocal command or featureWhat to verify
What is running?docker psImage, command, port mappings, status
Why did it stop?docker logs NAMEApplication error and startup output
Which image is this?docker inspect NAMEConfigured image and runtime settings
Where is state stored?docker inspect / volume toolsMount source and backup plan
// Part 08 — Pitfalls

Common Mistakes

Confusing EXPOSE with publishing a port

Why: EXPOSE is image metadata and does not create host access.

Fix: Use a deliberate port mapping and bind locally when appropriate.

Storing application state only in the container layer

Why: Replacing the container discards its writable layer.

Fix: Use a volume or managed service and maintain tested backups.

Copying all files into the build context

Why: Secrets, caches, and local artifacts can enter image layers.

Fix: Use a focused build context and a reviewed .dockerignore.

Treating an image tag as proof of immutable content

Why: Tags can be moved to refer to a different build.

Fix: Use controlled release tags or digests and record deployed artifacts.

// Part 09 — Practice

Containerize and Inspect the API

Practice

Build a repeatable local API image

  1. Create the FastAPI application and requirements file shown above, then build an image from the project directory.
  2. Run the image with a host port that differs from the container port and call the health endpoint.
  3. Change only application source, rebuild, and observe which build steps can reuse cache.
  4. Add a .dockerignore and verify local .env and virtual-environment files are not included in the build context.
  5. Use a named volume with a disposable test container, remove the container, and inspect what data remains.
  6. Build the multi-stage variant and verify that the application starts and answers its health check.

Hint: Use local test data only. Do not copy credentials into the build context or run an unreviewed image as root on a shared host.

🎯 Key Takeaways

  • ✓Images are reusable build artifacts; containers are runtime instances of those images.
  • ✓A container shares the host kernel and is not a full virtual machine or a security boundary by itself.
  • ✓Dockerfile ordering and build context affect cache reuse, repeatability, and accidental file inclusion.
  • ✓EXPOSE documents a container port; publish a port explicitly when host access is needed.
  • ✓Use volumes or external services for state that must survive container replacement.
  • ✓Keep secrets out of images, review artifacts, and run production containers with least privilege.

Next

What comes next

You have packaged one service. Next, define an API, database, and cache together with Compose so they can be started and tested as a system.

Lesson 05 · Docker Compose for Multi-Service Apps →

HELP US IMPROVE

How was this lesson?

Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.

Choose your feedback

Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.

Share

Discussion

0

Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.

Continue with GitHub
Loading...