DevOps, CI/CD & Containers
Docker Fundamentals: Images, Containers and Dockerfiles
Beginner6 min readUpdated
Docker packages an application with everything it needs into an image, and runs that image as an isolated process called a container. This guide explains the pieces — images, layers, registries, containers, volumes — then shows how to write a Dockerfile that builds fast and produces a small, secure image, with worked examples for a Spring Boot service.
What you will learn
- Explain the difference between an image, a layer, a container and a registry
- Run, inspect, stop and remove containers with the core CLI commands
- Write a multi-stage Dockerfile that produces a small, reproducible image
- Use .dockerignore, layer ordering and cache mounts to keep builds fast
- Avoid the most common mistakes: running as root, latest tags, secrets in images
"It works on my machine" used to be a punchline; Docker turned it into a deployment strategy by making the machine part of the artifact. An image carries the application, its runtime, its libraries and its configuration. Run the same image on a laptop, a CI runner and a production cluster and you get the same behaviour. This guide explains the model behind that promise and then gets practical: the commands you use daily and how to write a Dockerfile you will not be embarrassed by later.
Images, layers, containers and registries
Four words carry most of Docker's vocabulary.
An image is a read-only template: a filesystem snapshot plus metadata such as the default command, environment variables and exposed ports. Images are built from a Dockerfile and identified by a name and tag, for example eclipse-temurin:21-jre.
An image is made of layers. Each instruction in a Dockerfile that changes the filesystem — COPY, RUN, ADD — produces a new layer stacked on the previous ones. Layers are content-addressed and shared: if ten images all start FROM eclipse-temurin:21-jre, the base layers are stored and downloaded once. This is also what makes the build cache work, as we will see.
A container is a running (or stopped) instance of an image. Docker adds a thin writable layer on top of the image's read-only layers, creates an isolated view of the process table, network and filesystem using Linux namespaces, and applies resource limits with cgroups. The container is just a process on the host kernel; there is no guest operating system booting.
A registry stores and distributes images. Docker Hub is the default public one; organisations run private registries (Harbor, GitLab, Amazon ECR, GitHub Container Registry). docker pull and docker push move images between a host and a registry.
$ docker pull eclipse-temurin:21-jre
$ docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
eclipse-temurin 21-jre 3a1f0b2c9d7e 2 weeks ago 268MB
The daily commands
You can go a long way with a dozen commands.
# Run a container from an image, interactively, and remove it on exit
docker run --rm -it ubuntu:24.04 bash
# Run a web server in the background, mapping host port 8080 to container port 80
docker run -d --name web -p 8080:80 nginx:1.27
# See what is running (add -a for stopped containers too)
docker ps
# Logs, a shell inside, resource usage
docker logs -f web
docker exec -it web sh
docker stats web
# Stop, start, remove
docker stop web
docker start web
docker rm -f web
# Inspect anything — images, containers, networks — as JSON
docker inspect web | jq '.[0].NetworkSettings.Ports'
# Reclaim disk: stopped containers, dangling images, unused networks
docker system prune
Two flags are worth internalising early. --rm deletes the container when it exits, which stops your machine filling with dead containers from experiments. -v (or --mount) attaches a volume or a host directory so data survives the container:
docker run -d --name db -v pgdata:/var/lib/postgresql/data -e POSTGRES_PASSWORD=dev postgres:16
Without the volume, the database files live in the container's writable layer and vanish with docker rm.
Writing a Dockerfile
A Dockerfile is a script of instructions that produce an image. Here is a minimal one for a Spring Boot application whose build already produced target/app.jar:
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY target/app.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
Build and run it:
docker build -t myorg/app:1.0.0 .
docker run --rm -p 8080:8080 myorg/app:1.0.0
The trailing . is the build context — the directory sent to the Docker daemon. Everything COPY refers to must be inside it, and everything inside it is transferred, which is why .dockerignore matters.
The instructions you will use:
| Instruction | Purpose |
|---|---|
FROM | Base image. Every Dockerfile starts here (or FROM scratch for an empty base). |
WORKDIR | Sets the working directory for following instructions; creates it if missing. |
COPY | Copies files from the build context into the image. Prefer it to ADD, which also fetches URLs and unpacks archives. |
RUN | Executes a command at build time and commits the result as a layer. |
ENV | Sets an environment variable for build and runtime. |
ARG | Build-time variable, passed with --build-arg; not present at runtime. |
EXPOSE | Documents which port the process listens on. It does not publish anything. |
USER | Switches the user for following instructions and for the running container. |
ENTRYPOINT / CMD | The command to run. Use the JSON array form so no shell is involved and signals reach the process. |
HEALTHCHECK | A command Docker runs periodically to report the container's health. |
Multi-stage builds
The Dockerfile above assumes the jar was built outside Docker, which makes the build depend on the host's Maven and JDK. A multi-stage build does the compilation inside a first stage and copies only the artifact into a slim runtime stage:
# ---- build stage ----
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /src
# Copy the files that change least first, so dependency download is cached
COPY pom.xml .
RUN --mount=type=cache,target=/root/.m2 mvn -q dependency:go-offline
COPY src ./src
RUN --mount=type=cache,target=/root/.m2 mvn -q package -DskipTests
# ---- runtime stage ----
FROM eclipse-temurin:21-jre
RUN useradd --system --uid 10001 app
WORKDIR /app
COPY --from=build /src/target/app.jar app.jar
USER app
EXPOSE 8080
HEALTHCHECK --interval=30s --timeout=3s CMD wget -qO- http://localhost:8080/actuator/health || exit 1
ENTRYPOINT ["java", "-XX:MaxRAMPercentage=75", "-jar", "app.jar"]
The build stage, with Maven and the full JDK, is discarded; the final image contains only the JRE and the jar. Sizes drop from around 700 MB to under 300 MB, and no source code or build tooling ships to production. The same pattern applies to Node (build with node:22, run with node:22-slim or serve static files from nginx), Go (build, then FROM scratch) and everything else.
Keeping builds fast: cache and ordering
Docker caches each layer and reuses it when the instruction and its inputs are unchanged. The cache is invalidated at the first instruction whose inputs changed, and every instruction after it is rebuilt. Two consequences:
- Order instructions from least to most volatile. Copy
pom.xmlorpackage.jsonand install dependencies before copying the source. Then editing a source file rebuilds only the compile step, not the dependency download. - Use
.dockerignore. ACOPY . .invalidates whenever any file in the context changes — including.git, build output, and editor swap files. Exclude them:
.git
target
node_modules
*.log
.idea
.vscode
Dockerfile
docker-compose*.yml
BuildKit's --mount=type=cache (shown above) keeps package-manager caches between builds without baking them into a layer. Combine RUN commands that belong together with && so their intermediate files never become a layer, and clean up in the same instruction:
RUN apt-get update \
&& apt-get install -y --no-install-recommends curl ca-certificates \
&& rm -rf /var/lib/apt/lists/*
Security and hygiene essentials
Do not run as root. By default the process inside a container runs as UID 0. A container escape or an application bug then hands an attacker root on the host filesystem the container can see. Create a user and switch to it with USER, as in the multi-stage example.
Pin base images. FROM node or FROM node:latest means a different image every week. Use a specific tag (node:22.9-slim) and, for reproducible builds, a digest: FROM node:22.9-slim@sha256:…. Rebuild deliberately to pick up security patches.
Never put secrets in an image. A COPY .env . or an ENV API_KEY=... is stored in a layer forever, visible with docker history, and pushed to every registry the image reaches. Pass secrets at runtime through environment variables or mounted files, and use BuildKit's --mount=type=secret if a build step genuinely needs one.
Keep the image small. Fewer packages mean fewer vulnerabilities to patch and faster pulls. Prefer -slim, -alpine or distroless bases, and scan images with docker scout or Trivy in CI.
Handle signals. Use the JSON array form of ENTRYPOINT so your process is PID 1 and receives SIGTERM when the container stops. A shell-form ENTRYPOINT java -jar app.jar puts sh in front of your process, swallows the signal, and your application is killed without a graceful shutdown after the ten-second grace period.
Common mistakes
- Treating containers as pets. Logging into a container and editing files inside it works until the container is recreated. Change the Dockerfile and rebuild.
- Publishing ports with
EXPOSEalone.EXPOSEis documentation.-p host:container(or a Composeportsentry) actually publishes. - Expecting
localhostto mean the host. Inside a container,localhostis the container. Reach other containers through a user-defined network and their service names, and the host throughhost.docker.internalon Docker Desktop. - Writing data to the container filesystem. It is gone on
docker rm. Use volumes. - One process, one container — ignored. Cramming an app, a database and a cron daemon into one image defeats orchestration, logging and scaling. Compose or Kubernetes exist for multi-container applications.
- Ignoring the exit code.
docker ps -ashows exited containers with their codes;docker logsshows why.137means killed by the OOM killer or aSIGKILL; raise the memory limit or fix the leak.
Key takeaways
- An image is a layered, read-only template; a container is a process running from it with a writable layer on top; a registry stores images.
- Learn
run,ps,logs,exec,stop,rm,build,pushandsystem prune. Add--rmto experiments and-vto anything that stores data. - Write multi-stage Dockerfiles: build in a full image, run in a slim one, copy only the artifact across.
- Order instructions from stable to volatile, maintain
.dockerignore, and use cache mounts so a source change rebuilds only the compile step. - Run as a non-root user, pin base images, keep secrets out of layers, use the JSON
ENTRYPOINTform and keep the image small.
Sources and further reading
Frequently asked questions
- Is a container a lightweight virtual machine?
- No. A virtual machine runs a full guest operating system on a hypervisor. A container is an ordinary process on the host kernel, isolated with Linux namespaces and limited with cgroups, that sees its own filesystem taken from the image. That is why containers start in milliseconds and share the host kernel — and why a container cannot run a different kernel from its host.
- What is the difference between CMD and ENTRYPOINT?
- ENTRYPOINT sets the executable that always runs; CMD supplies default arguments that a user can override on the docker run command line. Use ENTRYPOINT for the fixed part (the java command and its flags) and CMD for arguments you expect people to change. If only CMD is set, the whole command can be replaced.
- Why is my image so large?
- Usually because the build tools, source code and package caches ended up in the final image. A multi-stage build compiles in one stage and copies only the resulting artifact into a slim runtime image. Also check that .dockerignore excludes .git, node_modules, target and IDE folders, and that you clean package-manager caches in the same RUN instruction that installs packages.
- Should I use the latest tag?
- Not for anything you deploy. latest is just a mutable tag that points at whatever was pushed most recently, so two builds on different days can produce different images. Pin base images to a specific version (and ideally a digest) and tag your own images with the build's version or commit hash.