- #docker
- #containers
- #devops
Docker 101: Images and Containers From Zero
Images, containers, Dockerfiles, volumes, ports and Compose, explained with everyday examples and hand-drawn diagrams. Then containerize a small web app on your own machine.
Akshit Bansal19 min readTutorial 2
ship the whole lunchboxon this page
In one minute
Docker- Docker packs your app and everything it needs into one bundle called an image.
- Running an image gives you a container: your app, walled off from the rest of the computer.
- The same image runs the same way on your laptop, a teammate's laptop and a server.
- It starts in about a second, because no extra operating system has to boot.
Words you need
Program
A file of instructions sitting on the disk, doing nothing yet. node, python and Chrome are programs.
Like a recipe written in a book
Process
A program that is running right now, using CPU and memory. One program can run as many processes at once.
Like a dish being cooked from that recipe
Kernel
The core of the operating system. It starts every process and decides what each one may see and use.
Like the kitchen manager who hands out stoves and ingredients
Host
The computer Docker runs on: your laptop or a server.
Like the kitchen itself
Image
A read-only bundle: your app plus everything it needs (runtime, libraries, files, settings). It never changes once built.
Like a sealed, packed lunchbox
Container
A running copy of an image. It is a process on the host with walls around it, so it sees only its own files.
Like the lunchbox opened and being eaten
Dockerfile
A text file of steps that tells Docker how to build an image.
Like the recipe card for packing the lunchbox
Registry
An online store of images. Docker Hub is the default one.
Like an app store, but for images
Tag
A label on an image, usually its version: node:24-alpine, hits:1.0.
Like the edition printed on a book
Port
A numbered door into a computer for network traffic. Web servers often listen on 80, 443 or 3000.
Like a flat number in a building
Volume
Storage kept outside the container, so data survives when the container is deleted.
Like a locker you keep when you change hotel rooms
Docker Engine
The background program that builds images and runs containers. The docker command only sends it requests.
Like the kitchen; the docker command is the waiter taking your order
Why Docker exists
Without Docker
With Docker
What a container really is
A container is not a small computer. It is an ordinary process on the host, with walls put around it by the kernel.
Host computer
Container: web
Container: redis
Normal processes
The walls are made of standard Linux features:
Namespaces
pid, net, mnt, uts, ipc, userWhat it can SEE: its own process list (its app is PID 1), network, filesystem and hostname.
cgroups
docker run --memory 256m --cpus 0.5How much it can USE: memory and CPU ceilings. Cross the memory one and it is killed (exit 137).
Union filesystem (OverlayFS)
docker image history IMAGERead-only image layers stacked, plus one thin writable layer on top that dies with the container.
OCI standards
image spec + runtime specOpen formats: an image built with Docker runs on containerd, Podman or Kubernetes unchanged.
Quick check: Your laptop runs Linux. Can a container on it run a Windows app natively?
Docker on Windows and macOS
Windows and macOS have no Linux kernel, so Docker Desktop quietly runs a small Linux VM and puts your containers inside it.
Your laptop: Windows or macOS
Hidden Linux VM (WSL 2 on Windows)
Image vs container
| Image | Container | |
|---|---|---|
| What it is | Frozen package: app + dependencies + OS files | A running copy of an image |
| Code analogy | A class | An object |
| Kitchen analogy | The sealed tiffin box | The opened tiffin you are eating |
| Changes? | Never (read-only layers) | Yes, in its writable layer |
| How many | One | As many as you start from it |
| Made by | docker build | docker run |
- 01
Dockerfile
The recipe you write
- 02
docker build
Bakes layers
- 03
Image
hits:1.0
- 04
docker push
To a registry
- 05
docker run
Anywhere with Docker
How Docker works
Docker Engine (on the host)
What docker run nginx actually does:
- 01
Find the image
is nginx on this computer?
- 02
Pull it if missing
download its layers from Docker Hub
- 03
Create the container
a thin writable layer on top + its own walls
- 04
Start the process
runs the image's start command
Dockerfile: the recipe
# Annotated example, not the walkthrough fileFROM node:24-alpineWORKDIR /appCOPY package.json ./RUN npm install --omit=devCOPY server.js ./USER nodeEXPOSE 3000CMD ["node", "server.js"]| Instruction | What it does | When |
|---|---|---|
| FROM | Base image to start from (alpine = small) | Build |
| WORKDIR | Folder later lines work in (created if missing) | Build + run |
| COPY | Files from your project into the image | Build |
| RUN | Runs a command; the result is saved as a layer | Build, once |
| ENV / ARG | ENV: variable at build and run. ARG: build only | Build (+ run) |
| USER | Switch away from root, so a bug has fewer powers | Run |
| EXPOSE | Documents the port. Does NOT publish it | Docs only |
| CMD | What starts every time a container starts (use list form) | Run, every start |
Layers and the build cache
- Every
FROM,COPYandRUNmakes a layer, and Docker caches it. - If one layer changes, every layer after it rebuilds.
- So: copy
package.jsonand install first, copy your code last. Code edits then skip the slow install.
docker build .- 1
FROM node:24-alpinecached - 2
WORKDIR /appcached - 3
COPY . .cache miss: reads server.jsrebuilt - 4
RUN npm install --omit=devslow step, rerun anywayrebuilt - 5
CMD ["node", "server.js"]rebuilt
3 of 5 steps rebuilt. A one-line code edit reinstalls every package.
Quick check: You change one line in server.js. Which order rebuilds fastest?
Smaller images: .dockerignore and multi-stage
.dockerignorekeepsnode_modules,.gitand.envout of the build: faster builds, no leaked secrets.- Multi-stage: build in a fat image, ship only the result in a clean one. No compilers or dev tools in production.
# Illustration only: build in one stage, ship from anotherFROM node:24-alpine AS buildWORKDIR /appCOPY package*.json ./RUN npm ciCOPY . .RUN npm run buildFROM node:24-alpineWORKDIR /appCOPY --from=build /app/dist ./distUSER nodeCMD ["node", "dist/server.js"]Storage: volumes and bind mounts
Writable layer
Named volume
Bind mount
Networks and ports
Compose network hits_default (has DNS)
-p 8080:3000reads host:container. Forget-pand the app runs, but nothing outside Docker reaches it.- Containers on the same network find each other by name (
redis), never by IP. - Publish only what the outside needs. Redis has no
-p, and that is a security feature.
Compose, registries and tags
- Compose: all services, networks and volumes in one
compose.yaml, started withdocker compose up. Right for local dev and single-server apps. Not a cluster manager. - Registry: where images live (Docker Hub, GHCR, ECR, ...).
Habits worth having from day one
| Habit | Why |
|---|---|
| Run as non-root (USER) | A hacked app gets fewer powers |
| Small, pinned base image | Less to download, less to attack, same build every time |
| No secrets in the image | Anyone with the image can read every layer. Pass them at run time |
| Add a HEALTHCHECK | Lets Docker, Compose and Kubernetes tell running from working |
| Write a .dockerignore | Faster builds, nothing private copied in |
| Least-changing lines first | Better cache hits, faster rebuilds |
| Scan images | docker scout quickview IMAGE or any scanner: flags known CVEs |
| Lockfile + npm ci | Same dependency versions everywhere |
The life of a container
Press the commands. Greyed-out ones are not allowed in the current state.
You have an image. Press a command that is allowed right now; hover one to see where it leads.
Command cheat sheet
| Command | What it does |
|---|---|
| docker build -t name:tag . | Build an image from ./Dockerfile |
| docker images / docker pull / docker push | List / download / upload images |
| docker run -d --name n -p 8080:3000 img | Start in the background, publish a port |
| docker ps (-a) | Running containers (-a: stopped too) |
| docker logs -f n | Follow a container's output |
| docker exec -it n sh | Shell inside a running container |
| docker stop n / docker rm -f n | Stop politely / stop and delete |
| docker inspect n | Everything Docker knows, as JSON |
| docker compose up -d / down | Start / remove all services (volumes kept) |
| docker compose down -v | Also delete volumes (your data) |
| docker system df | How much disk Docker uses |
Your Docker roadmap
Topics from the roadmap.sh Docker roadmap (opens in a new tab): what this page covers, and what to learn next. Ticks stay in your browser.
Docker roadmap
0/14Learn now
Learn next
DIY walkthrough
You will containerize a tiny web app called hits that counts page views in Redis (a small, fast database), run it with plain Docker, then with Docker Compose.
Install Docker
Docker Desktop on Windows runs on WSL 2 and needs hardware virtualization turned on. Docker's install page lists Windows 21H2 or newer. Check virtualization first: open Task Manager, go to the Performance tab, pick CPU, and look for "Virtualization: Enabled".
Install Docker Desktop from docs.docker.com/desktop/setup/install/windows-install (opens in a new tab) and follow its WSL 2 option. If you work for a company, check Docker's current terms before using Docker Desktop at work.
Install Docker Desktop from docs.docker.com/desktop/setup/install/mac-install (opens in a new tab) and start it. Check Docker's current terms if you use it for a company.
Docker's own convenience script is the quickest route. Its page says the script is only recommended for testing and development, which is exactly what we are doing. The second block lets you run docker without sudo.
curl -fsSL https://get.docker.com -o get-docker.shsudo sh get-docker.shsudo groupadd dockersudo usermod -aG docker $USERnewgrp dockerCheck that Docker works
Start Docker Desktop (Windows and macOS) and wait until it says it is running. Then:
docker versionYou should see
docker version shows both a Client and a Server section. If Server is missing, Docker is not running yet.Create the project folder
mkdir hitscd hitsEvery file below is named in its title bar, like
hits/server.js. Create it inside thehitsfolder at that path. Run all commands from insidehits/.You should see
Your terminal is now inside an empty folder called hits.
Build and run hits
First the application files. They are small on purpose.
The app is a tiny web server. GET / adds one to a counter stored in Redis and returns it, along with the version and the name of the machine that answered. GET /healthz says the process is alive. It also stops cleanly when asked to, which makes rollouts quick later.
import { createServer } from "node:http";import { hostname } from "node:os";import { createClient } from "redis";const PORT = 3000;const VERSION = process.env.VERSION ?? "dev";const redis = createClient({ url: process.env.REDIS_URL ?? "redis://localhost:6379" });redis.on("error", (err) => console.error("redis error:", err.message));await redis.connect();const server = createServer(async (req, res) => { if (req.url === "/healthz") { res.writeHead(200).end("ok\n"); return; } if (req.url !== "/") { res.writeHead(404).end("not found\n"); return; } try { const hits = await redis.incr("hits"); res.writeHead(200, { "content-type": "text/plain" }); res.end(`hits: ${hits}, version: ${VERSION}, served by: ${hostname()}\n`); } catch { res.writeHead(503).end("redis unavailable\n"); }});server.listen(PORT, "0.0.0.0", () => console.log(`hits ${VERSION} listening on ${PORT}`));process.on("SIGTERM", () => { server.close(() => process.exit(0));});{ "name": "hits", "version": "1.0.0", "private": true, "type": "module", "scripts": { "start": "node server.js" }, "dependencies": { "redis": "^5.0.0" }}FROM node:24-alpineARG VERSION=devENV VERSION=$VERSION NODE_ENV=productionWORKDIR /appCOPY package.json ./RUN npm install --omit=devCOPY server.js ./USER nodeEXPOSE 3000HEALTHCHECK --interval=10s --timeout=3s CMD wget -qO- http://127.0.0.1:3000/healthz || exit 1CMD ["node", "server.js"]node_modulesnpm-debug.log.git.envDockerfilecompose.yamlk8sservices: web: build: context: . args: VERSION: "1.0" ports: - "8080:3000" environment: REDIS_URL: redis://redis:6379 depends_on: redis: condition: service_healthy redis: image: redis:7-alpine command: ["redis-server", "--appendonly", "yes"] volumes: - hits-data:/data healthcheck: test: ["CMD", "redis-cli", "ping"] interval: 2s timeout: 3s retries: 15volumes: hits-data:Peek at the shared kernel
This pulls a tiny image, runs one command in a container, and removes the container afterwards.
docker run --rm alpine uname -rIf you did VM 101, compare it with the kernel line from inside the VM. On a Linux host, compare it with plain
uname -r. A container does not have a kernel of its own.You should see
A kernel version prints. On Windows and macOS it is a Linux kernel, not the one your computer runs: Docker started a hidden Linux VM. On Linux it matches the kernel of your own machine, because nothing was virtualised.Build the image
docker build -t hits:1.0 --build-arg VERSION=1.0 .docker images hitsYou should see
The build ends without errors, and docker images lists hits with tag 1.0.Run Redis and the app on one network
A user-defined network gives you name lookup: the app will reach Redis simply as
cache.docker network create hits-netdocker run -d --name cache --network hits-net redis:7-alpinedocker run -d --name web --network hits-net -p 8080:3000 -e REDIS_URL=redis://cache:6379 hits:1.0docker psYou should see
docker ps lists two running containers, cache and web, and the web one shows 0.0.0.0:8080->3000/tcp.Talk to it
curl http://localhost:8080curl http://localhost:8080curl http://localhost:8080/healthzYou should see
The first call prints hits: 1 with version: 1.0 and a short hexadecimal name. Each call raises the number by one. /healthz prints ok.Look around inside
docker logs webdocker exec web whoamidocker exec web sh -c 'echo $VERSION'You should see
The logs show the line 'hits 1.0 listening on 3000'. whoami prints node, which proves the app is not running as root, and the last command prints 1.0.Rebuild and watch the cache
Open
hits/server.js, add a harmless comment line at the bottom and save. Then build again with plain progress output so you can read each step.docker build --progress=plain -t hits:1.0 --build-arg VERSION=1.0 .You should see
In the second build output most steps say CACHED. Only the COPY server.js step and later ones run again. Order matters, just like the demo showed.Stop the manual containers and switch to Compose
We remove the hand-made containers first because Compose wants the same port, 8080. Then one file does the work of all those commands.
docker rm -f web cachedocker network rm hits-netdocker compose up -d --build --waitdocker compose pscurl http://localhost:8080You should see
docker compose ps shows web and redis running, and web is healthy. The counter starts again at 1 because this is a fresh Redis.Prove the volume keeps your data
docker compose downdocker compose up -d --waitcurl http://localhost:8080docker compose down -vdocker compose up -d --waitcurl http://localhost:8080docker compose down -vYou should see
After the restart the next call prints 2, continuing from the call you made before, because the volume survived. After down -v and a fresh up, the number is 1 again: you deleted the volume.
Clean up
Stop the containers
docker compose down -vdocker psYou should see
docker ps shows nothing from this tutorial.Delete the images and the folder
docker image rm hits:1.0 hits-web redis:7-alpine alpineThen delete the
hitsfolder from your file manager or terminal.You should see
docker images no longer lists hits, hits-web or redis.
Troubleshooting
Click an entry to open it. Match on the key phrase of your error; the wording shifts a little between versions.
Installing and starting Docker
WslRegisterDistribution failed with error: 0x80370102
Cause
Fix
Restart the PC and open the BIOS or UEFI setup (often Del, F2 or F10 at power-on). Find a setting named Intel Virtualization Technology, VT-x, SVM Mode or AMD-V and enable it. Back in Windows, open PowerShell as administrator:
wsl --installwsl --updateRestart if asked, then confirm in Task Manager (Performance, CPU) that Virtualization says Enabled.
Docker Desktop stays on 'Starting...' and never turns green
Cause
Fix
Update WSL, restart it, then restart Docker Desktop.
wsl --updatewsl --shutdownIf it still hangs, restart Windows. On a company laptop, a security policy may block WSL, so ask IT.
Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running?
Cause
Fix
Windows and macOS: start Docker Desktop and wait for it to say it is running. Linux:
sudo systemctl start dockersudo systemctl enable dockerpermission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock
Cause
Fix
Add yourself to the group and refresh your session. The docker group effectively grants root powers, so add only people you trust.
sudo usermod -aG docker $USERnewgrp dockerdocker run hello-worldLog out and back in if a new terminal still complains.
Building and running with Docker
curl: (56) Recv failure: Connection reset by peer
Cause
Fix
Wait a couple of seconds and run curl again. If it keeps failing, the app has stopped, so read its logs.
docker ps -adocker logs webBind for 0.0.0.0:8080 failed: port is already allocated
Cause
Fix
Find and remove the owner, or publish on another port such as -p 8090:3000.
docker psdocker rm -f webexec format error
Cause
Fix
Check the architecture and ask for the one you need. Docker can emulate amd64 on arm64, more slowly.
docker image inspect IMAGE --format "{{.Architecture}}"docker run --platform linux/amd64 IMAGEno space left on device
Cause
Fix
See what uses space, then prune. docker system prune removes stopped containers, unused networks, dangling images and build cache. It does not remove volumes unless you add --volumes, and -a also removes every unused image, so read the prompt before saying yes.
docker system dfdocker system prunetoomanyrequests: You have reached your pull rate limit
Cause
Fix
Wait and retry, or sign in, which usually gives a higher allowance. Check Docker's current limits on its site.
docker loginconnect ECONNREFUSED 127.0.0.1:6379
Cause
Fix
Make sure both containers share a network and the URL uses the container name.
docker run -d --name web --network hits-net -p 8080:3000 -e REDIS_URL=redis://cache:6379 hits:1.0With Compose, check that the Redis service is named redis and the environment line matches. Some Node versions hide the address and print only AggregateError, so the cause is the same.
dependency failed to start: container hits-redis-1 is unhealthy
Cause
Fix
Read Redis's own output and fix what it complains about.
docker compose logs redisdocker compose down -vdocker compose up -d --waitNext steps and sources
- Next: Kubernetes 101, to run this same app on a cluster.
- Compare all three: Docker vs Kubernetes vs VM.
- Official guide: docs.docker.com/get-started (opens in a new tab) (the "What is a container?" and "What is an image?" pages are short and good).
- roadmap.sh Docker roadmap (opens in a new tab)
- Videos this was planned around: Docker tutorial (opens in a new tab) by The Coding Sloth, Docker vs virtual machines (opens in a new tab) by IBM Technology