Essential CLI Commands
- Images
- Containers
- Volumes & Inspection
Dockerfile Best Practices
A well-written Dockerfile is reproducible, minimal, and builds quickly. These principles are ordered by impact:1
Pin base image versions
Always specify an exact tag.
FROM python:3.12.3-slim-bookworm is reproducible; FROM python:latest is not.2
Order layers from least to most volatile
Docker caches each layer. Put
COPY requirements.txt and RUN pip install before COPY . . — the dependency install cache survives code changes.3
Combine RUN commands to reduce layers
Each
RUN creates a new layer. Chain related commands with && and clean up in the same layer.4
Use multi-stage builds for compiled artefacts
Keep build tools out of the final image. The final image should contain only what the running process needs.
5
Run as a non-root user
Add a dedicated user and switch to it before the
CMD. This is required by many security policies and Kubernetes admission controllers.Multi-Stage Build Example
The final image contains zero build tools (
npm, compilers, dev dependencies). The AS builder stage is discarded — only its output is copied. This typically cuts image size by 60–80%.Python Multi-Stage Example
.dockerignore
Always create a .dockerignore alongside your Dockerfile:
Docker Compose
Docker Compose is the right tool for local development stacks and single-host multi-container deployments.Docker Networking
Docker creates three default networks. In practice you’ll use two of them:Cleanup One-Liners
Container and image sprawl is a real issue on long-running build hosts. These commands keep things tidy:Related Pages
GitLab CI/CD
Use Docker-in-Docker inside GitLab pipelines to build and push the images you create with these commands.
Kubernetes
Run Docker images at scale — Kubernetes orchestrates the containers Docker builds.