Docker Tutorial for Beginners: Containerise Your First App
November 27, 2026 · 11 min read

This Docker tutorial takes you from zero to a running, production-style container in under an hour. Docker packages an application with everything it needs, including the runtime, libraries and settings, into an image that runs the same way on your laptop, a colleague's machine, a CI server and the cloud. "It works on my machine" stops being an excuse.
Docker is everywhere: Docker Hub serves more than 20 billion image pulls a month, and in December 2025 Docker made its catalogue of hardened, minimal base images free and open source. In this guide you will containerise a small Node.js API step by step, write a multi-stage Dockerfile, run the app with a database using Docker Compose, and learn the best practices and mistakes that matter.
What Docker Is, in Plain Terms
- Image: a read-only template containing your app and its environment, built from a Dockerfile.
- Container: a running instance of an image, isolated from other processes but sharing the host's operating system kernel.
- Dockerfile: a text file of instructions for building an image.
- Registry: a store for images, such as Docker Hub or GitHub Container Registry.
- Volume: storage that outlives containers, used for databases and uploads.
- Compose: a tool for defining and running several containers together.
| Containers | Virtual machines | |
|---|---|---|
| Start-up time | Seconds or less | Usually minutes |
| Size | Megabytes | Gigabytes |
| Isolation | Process-level, shared kernel | Full operating system per VM |
| Best for | Packaging and running applications | Running different operating systems or strong isolation |
Docker builds and runs containers; Kubernetes runs many containers across many machines. Our comparison of Docker and Kubernetes explains how they fit together.
How Images and Layers Work
Each instruction in a Dockerfile creates a layer, a set of file changes stacked on the layers before it. Layers are cached and shared: if ten images use the same Node.js base, it is downloaded once, and if a build step's inputs have not changed, Docker reuses its cached layer instead of running it again. That is why the order of instructions matters so much for build speed. When a container runs, Docker adds a thin writable layer on top; anything written there disappears when the container is removed, which is why databases and uploads belong in volumes.
Install Docker
On macOS and Windows, install Docker Desktop, which includes the Docker Engine, the command-line tools, Compose and a graphical dashboard. Docker Desktop is free for personal use, education, open source and small businesses, but larger organisations need a paid subscription; check the licence terms. On Linux servers, install Docker Engine directly; version 29, released in late 2025, made the containerd image store the default for new installations, as Docker's Engine 29 announcement explains. Check your installation by running docker version and docker run hello-world.
Step 1: The App
We will containerise a tiny Node.js API with a health check endpoint. It has no dependencies, so you can focus on Docker rather than the code:
// server.js - a tiny Node.js API to containerise (no dependencies needed)
import http from "node:http";
const port = Number(process.env.PORT ?? 3000);
const server = http.createServer((req, res) => {
if (req.url === "/health") return res.end("ok"); // used by Docker and Kubernetes health checks
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ message: "Hello from a container", version: process.env.APP_VERSION ?? "dev" }));
});
server.listen(port, () => console.log(`Listening on port ${port}`));
process.on("SIGTERM", () => server.close(() => process.exit(0))); // shut down cleanly when the container stops
{
"name": "hello-api",
"version": "1.0.0",
"type": "module",
"scripts": { "start": "node server.js" },
"engines": { "node": ">=24" }
}
Notice two details that matter in containers: the port comes from an environment variable, and the server shuts down cleanly when it receives the stop signal Docker sends. Run npm install once to create the package-lock.json file the build expects. For a fuller API, see our Node.js REST API guide.
Step 2: Write a Dockerfile
Create a file called Dockerfile next to the code:
# syntax=docker/dockerfile:1
# Stage 1: install production dependencies
FROM node:24-alpine AS deps
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci --omit=dev
# Stage 2: a small runtime image that runs as a non-root user
FROM node:24-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY --from=deps /app/node_modules ./node_modules
COPY --chown=node:node . .
USER node
EXPOSE 3000
HEALTHCHECK --interval=30s --timeout=3s CMD ["wget", "-qO-", "http://localhost:3000/health"]
CMD ["node", "server.js"]
Line by line, this does the following:
- Two stages: the first installs dependencies; the second copies only what the app needs, keeping the final image small and free of build tools.
- A small official base image, pinned to Node.js 24 on Alpine Linux, rather than a vague "latest" tag.
- Dependency files first: copying
package.jsonand the lock file before the source code lets Docker reuse the cached dependency layer when only your code changes. - npm ci with production dependencies only, for fast, repeatable installs.
- A non-root user: the official Node.js images include a
nodeuser, which limits damage if the app is compromised. - A health check so Docker knows whether the app is actually responding, not just running.
- Exec-form CMD so the stop signal reaches Node.js directly.
Add a .dockerignore file so local clutter and secrets never reach the image:
node_modules
npm-debug.log
.git
.env
Dockerfile
compose.yaml
Step 3: Build and Run the Container
# Build an image from the Dockerfile in this folder and tag it
docker build -t hello-api:1.0.0 .
# Run it in the background, mapping port 3000 on your machine to port 3000 in the container
docker run -d --name hello-api -p 3000:3000 -e APP_VERSION=1.0.0 hello-api:1.0.0
# Check it works, read its logs, then stop and remove it
curl http://localhost:3000
docker logs hello-api
docker stop hello-api && docker rm hello-api
# Or run the API and its database together
docker compose up --build
docker build creates the image and tags it with a name and version. docker run -d starts a container in the background, and -p 3000:3000 maps port 3000 on your machine to port 3000 inside the container, so curl http://localhost:3000 returns the JSON greeting. The last command starts the whole stack with Compose, which we set up next.
Step 4: Add a Database With Docker Compose
Real apps need databases, caches and queues. Compose describes them all in one file, here called compose.yaml:
# compose.yaml - start everything with: docker compose up --build
services:
api:
build: .
ports:
- "3000:3000"
environment:
APP_VERSION: "1.0.0"
DATABASE_URL: postgres://app:app@db:5432/app
depends_on:
db:
condition: service_healthy
db:
image: postgres:17-alpine
environment:
POSTGRES_USER: app
POSTGRES_PASSWORD: app # local development only; use secrets in production
POSTGRES_DB: app
volumes:
- db-data:/var/lib/postgresql/data
healthcheck:
test: ["CMD-SHELL", "pg_isready -U app"]
interval: 5s
timeout: 3s
retries: 5
volumes:
db-data:
The API waits until PostgreSQL passes its health check before starting, and the named volume keeps database data when containers are recreated. Services reach each other by name, so the API connects to the host db, not localhost. Use docker compose up --build to start everything, docker compose logs -f to follow the output and docker compose down to stop it. Compose is now built into Docker as the docker compose command; the Compose documentation covers every option.
Essential Docker Commands
| Command | What it does |
|---|---|
docker ps | Lists running containers; add -a to include stopped ones |
docker images | Lists images on your machine |
docker logs -f name | Follows a container's output |
docker exec -it name sh | Opens a shell inside a running container for debugging |
docker stop name | Stops a container gracefully |
docker system prune | Removes stopped containers, unused networks and dangling images |
docker compose ps | Shows the status of a Compose project's services |
A Faster Development Loop
Rebuilding an image after every code change gets slow. During development, mount your source code into the container with a bind mount, or use Compose's watch mode, which syncs changed files into running containers and rebuilds only when dependencies change. Keep a separate development Compose file for tools such as database admin interfaces, and never use development settings, such as the plain-text database password above, in production.
Use Secure Base Images
Base images often carry known vulnerabilities in packages your app never uses. Docker's Docker Hardened Images, free under the Apache 2.0 licence since December 2025, offer more than 1,000 minimal images built on Debian and Alpine, with software bills of materials and provenance information. After signing in to the dhi.io registry with your Docker account, you can swap the base images in the Dockerfile above for hardened equivalents such as dhi.io/node:24, using the -dev variant for the build stage. Whatever base you choose, scan images in CI with a tool such as Docker Scout or Trivy and rebuild regularly to pick up patches.
Push Your Image to a Registry
To run the image elsewhere, push it to a registry. Tag it with the registry address, such as ghcr.io/your-org/hello-api:1.0.0, sign in with docker login, then run docker push. In practice, let CI build and push images on every merge; our GitHub Actions tutorial shows how. Our guide to types of web hosting explains where containers can run, from simple container platforms to full Kubernetes clusters.
Running Containers in Production
On a single server, Docker with a restart policy can be enough for small apps. Most teams, though, hand containers to a platform: managed services such as AWS ECS and Fargate, Azure Container Apps or Google Cloud Run run containers without managing servers, while Kubernetes offers the most control at the cost of complexity. Whichever you choose, use immutable version tags rather than overwriting images, set memory and CPU limits, send logs to a central service and keep the previous image ready for a quick rollback. Docker Desktop has also grown beyond containers, with recent releases bundling tools such as Model Runner for running AI models locally.
Dockerfile Best Practices
- Use small, official or hardened base images, and pin their versions.
- Use multi-stage builds to keep compilers and build tools out of production images.
- Order instructions from least to most frequently changed to make the most of caching.
- Run as a non-root user and give containers only the permissions they need.
- Never bake secrets into images; pass them at runtime or use build secrets.
- Run one main process per container, and log to standard output.
- Add health checks and handle stop signals for clean shutdowns.
- Scan images for vulnerabilities and rebuild them regularly.
Common Beginner Mistakes
- Using localhost between containers: inside a container, localhost means the container itself; use service names.
- Losing data: anything written inside a container disappears when it is removed, unless it is in a volume.
- Slow builds: copying all source code before installing dependencies breaks the cache on every change.
- Huge images: full operating system images and build tools in production images waste space and add risk.
- Relying on "latest": the image changes underneath you, so builds stop being repeatable.
Where to Go Next
Once you have finished this Docker tutorial and your app runs in a container, the next steps are automating builds and deployments with CI/CD, running containers at scale with Kubernetes, covered in our guide to Kubernetes for beginners, and giving developers self-service paths to production, the focus of platform engineering. Our DevOps roadmap shows how these skills fit together.
Frequently Asked Questions
What is Docker used for?
Docker packages applications and their dependencies into containers that run consistently across laptops, test servers and the cloud, simplifying development, testing and deployment.
Is Docker free?
Docker Engine is open source and free. Docker Desktop is free for personal use, education, open source and small businesses, while larger organisations need a paid subscription.
What is the difference between an image and a container?
An image is a read-only template built from a Dockerfile. A container is a running instance of that image, with its own writable layer and isolated processes.
What is Docker Compose?
Compose defines multi-container applications, such as an API and a database, in one YAML file and starts them together with docker compose up.
Should I learn Docker before Kubernetes?
Yes. Kubernetes runs containers, so understanding images, containers, ports, volumes and environment variables in Docker first makes Kubernetes much easier to learn.
How do I make Docker images more secure?
Use minimal or hardened base images, multi-stage builds and a non-root user, keep secrets out of images, pin versions and scan images in CI.
Containerise Your Applications
We containerise existing applications, build CI/CD pipelines and run workloads on managed container platforms and Kubernetes. Contact our team to modernise your deployments.