All tutorials
  • #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 lunchbox
on 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

Your laptopNode 24, Redis 7: works
The serverNode 18, no Redis: crashes

With Docker

Imagecode + Node 24 + libraries + settings
Laptopworks
Serverworks
Same code, different surroundings: the classic 'it works on my machine'.

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

node server.jssees only its own files and processes

Container: redis

redis-serverhas its own network and hostname

Normal processes

your browser, editor...no walls
ONE shared Linux kerneldraws the walls, shares CPU and memory
Containers are processes on the same host, sharing its one kernel. The walls decide what each can see and use.

The walls are made of standard Linux features:

  • Namespaces

    pid, net, mnt, uts, ipc, user

    What it can SEE: its own process list (its app is PID 1), network, filesystem and hostname.

  • cgroups

    docker run --memory 256m --cpus 0.5

    How much it can USE: memory and CPU ceilings. Cross the memory one and it is killed (exit 137).

  • Union filesystem (OverlayFS)

    docker image history IMAGE

    Read-only image layers stacked, plus one thin writable layer on top that dies with the container.

  • OCI standards

    image spec + runtime spec

    Open 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)

Docker Engineruns on the VM's Linux kernel
webcontainer
rediscontainer
kind nodea Kubernetes node that is itself a container
On a Windows or Mac laptop, all three layers are already stacked.

Image vs container

ImageContainer
What it isFrozen package: app + dependencies + OS filesA running copy of an image
Code analogyA classAn object
Kitchen analogyThe sealed tiffin boxThe opened tiffin you are eating
Changes?Never (read-only layers)Yes, in its writable layer
How manyOneAs many as you start from it
Made bydocker builddocker run
  1. 01

    Dockerfile

    The recipe you write

  2. 02

    docker build

    Bakes layers

  3. 03

    Image

    hits:1.0

  4. 04

    docker push

    To a registry

  5. 05

    docker run

    Anywhere with Docker

How Docker works

docker CLIwhat you type: docker build, docker run

Docker Engine (on the host)

Imagesstored on your disk
Containersrunning processes
RegistryDocker Hub, GHCR, ECR...
You type commands; Docker Engine does the work and talks to the registry.

What docker run nginx actually does:

  1. 01

    Find the image

    is nginx on this computer?

  2. 02

    Pull it if missing

    download its layers from Docker Hub

  3. 03

    Create the container

    a thin writable layer on top + its own walls

  4. 04

    Start the process

    runs the image's start command

Dockerfile: the recipe

dockerfile
# 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"]
InstructionWhat it doesWhen
FROMBase image to start from (alpine = small)Build
WORKDIRFolder later lines work in (created if missing)Build + run
COPYFiles from your project into the imageBuild
RUNRuns a command; the result is saved as a layerBuild, once
ENV / ARGENV: variable at build and run. ARG: build onlyBuild (+ run)
USERSwitch away from root, so a bug has fewer powersRun
EXPOSEDocuments the port. Does NOT publish itDocs only
CMDWhat starts every time a container starts (use list form)Run, every start

Layers and the build cache

  • Every FROM, COPY and RUN makes a layer, and Docker caches it.
  • If one layer changes, every layer after it rebuilds.
  • So: copy package.json and install first, copy your code last. Code edits then skip the slow install.
Dockerfile
What changed
docker build .
  1. 1FROM node:24-alpinecached
  2. 2WORKDIR /appcached
  3. 3COPY . .cache miss: reads server.jsrebuilt
  4. 4RUN npm install --omit=devslow step, rerun anywayrebuilt
  5. 5CMD ["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

  • .dockerignore keeps node_modules, .git and .env out 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.
dockerfile
# 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

Containerwrites to /tmp, /data, /app/src

Writable layer

Deleted with the containerscratch files only

Named volume

-v hits-data:/dataDocker manages it. Survives rm. For databases

Bind mount

-v ./src:/app/srcYour own folder. Live code edits in dev
Only the writable layer dies with docker rm.

Networks and ports

Your browserlocalhost:8080

Compose network hits_default (has DNS)

weblistens on :3000
redis:6379, no -p
volume hits-dataRedis data survives restarts
Exactly what you build in the walkthrough.
  • -p 8080:3000 reads host:container. Forget -p and 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 with docker compose up. Right for local dev and single-server apps. Not a cluster manager.
  • Registry: where images live (Docker Hub, GHCR, ECR, ...).
ghcr.ioregistry (default: Docker Hub)
akshituser or org
hitsrepository
:1.0tag = a movable label
Reading an image name.

Habits worth having from day one

HabitWhy
Run as non-root (USER)A hacked app gets fewer powers
Small, pinned base imageLess to download, less to attack, same build every time
No secrets in the imageAnyone with the image can read every layer. Pass them at run time
Add a HEALTHCHECKLets Docker, Compose and Kubernetes tell running from working
Write a .dockerignoreFaster builds, nothing private copied in
Least-changing lines firstBetter cache hits, faster rebuilds
Scan imagesdocker scout quickview IMAGE or any scanner: flags known CVEs
Lockfile + npm ciSame 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

CommandWhat it does
docker build -t name:tag .Build an image from ./Dockerfile
docker images / docker pull / docker pushList / download / upload images
docker run -d --name n -p 8080:3000 imgStart in the background, publish a port
docker ps (-a)Running containers (-a: stopped too)
docker logs -f nFollow a container's output
docker exec -it n shShell inside a running container
docker stop n / docker rm -f nStop politely / stop and delete
docker inspect nEverything Docker knows, as JSON
docker compose up -d / downStart / remove all services (volumes kept)
docker compose down -vAlso delete volumes (your data)
docker system dfHow 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/14

Learn 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.

  1. Check that Docker works

    Start Docker Desktop (Windows and macOS) and wait until it says it is running. Then:

    bash
    docker version

    You should see

    docker version shows both a Client and a Server section. If Server is missing, Docker is not running yet.
  2. Create the project folder

    bash
    mkdir hitscd hits

    Every file below is named in its title bar, like hits/server.js. Create it inside the hits folder at that path. Run all commands from inside hits/.

    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.

hits/server.jsjavascript
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));});
hits/package.jsonjson
{  "name": "hits",  "version": "1.0.0",  "private": true,  "type": "module",  "scripts": {    "start": "node server.js"  },  "dependencies": {    "redis": "^5.0.0"  }}
hits/Dockerfiledockerfile
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"]
hits/.dockerignoretext
node_modulesnpm-debug.log.git.envDockerfilecompose.yamlk8s
hits/compose.yamlyaml
services:  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:
  1. Peek at the shared kernel

    This pulls a tiny image, runs one command in a container, and removes the container afterwards.

    bash
    docker run --rm alpine uname -r

    If 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.
  2. Build the image

    bash
    docker build -t hits:1.0 --build-arg VERSION=1.0 .docker images hits

    You should see

    The build ends without errors, and docker images lists hits with tag 1.0.
  3. Run Redis and the app on one network

    A user-defined network gives you name lookup: the app will reach Redis simply as cache.

    bash
    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 ps

    You should see

    docker ps lists two running containers, cache and web, and the web one shows 0.0.0.0:8080->3000/tcp.
  4. Talk to it

    bash
    curl http://localhost:8080curl http://localhost:8080curl http://localhost:8080/healthz

    You 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.
  5. Look around inside

    bash
    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.
  6. 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.

    bash
    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.
  7. 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.

    bash
    docker rm -f web cachedocker network rm hits-netdocker compose up -d --build --waitdocker compose pscurl http://localhost:8080

    You 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.
  8. Prove the volume keeps your data

    bash
    docker compose downdocker compose up -d --waitcurl http://localhost:8080docker compose down -vdocker compose up -d --waitcurl http://localhost:8080docker compose down -v

    You 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

  1. Stop the containers

    bash
    docker compose down -vdocker ps

    You should see

    docker ps shows nothing from this tutorial.
  2. Delete the images and the folder

    bash
    docker image rm hits:1.0 hits-web redis:7-alpine alpine

    Then delete the hits folder 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

Hardware virtualization is turned off in your BIOS or UEFI, or the Windows Virtual Machine Platform feature is off. Docker Desktop on Windows needs both.

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:

powershell
wsl --installwsl --update

Restart if asked, then confirm in Task Manager (Performance, CPU) that Virtualization says Enabled.

Docker Desktop stays on 'Starting...' and never turns green

Cause

WSL is missing, outdated or stuck, or another virtualization tool is holding the hypervisor.

Fix

Update WSL, restart it, then restart Docker Desktop.

powershell
wsl --updatewsl --shutdown

If 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

The Docker engine is not running. On Windows the text instead mentions a pipe such as dockerDesktopLinuxEngine, with the same meaning.

Fix

Windows and macOS: start Docker Desktop and wait for it to say it is running. Linux:

bash
sudo systemctl start dockersudo systemctl enable docker
permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock

Cause

On Linux, only root and members of the docker group may use the socket, and your user is not in it.

Fix

Add yourself to the group and refresh your session. The docker group effectively grants root powers, so add only people you trust.

bash
sudo usermod -aG docker $USERnewgrp dockerdocker run hello-world

Log out and back in if a new terminal still complains.

Building and running with Docker

curl: (56) Recv failure: Connection reset by peer

Cause

You were faster than the app. Docker opens the port the moment the container starts, but Node needs a second to boot and connect to Redis. The door is there before anyone is standing behind it.

Fix

Wait a couple of seconds and run curl again. If it keeps failing, the app has stopped, so read its logs.

bash
docker ps -adocker logs web
Bind for 0.0.0.0:8080 failed: port is already allocated

Cause

Something else is using host port 8080. Often it is the hand-made web container from the plain-Docker steps still running when you start Compose, or an old container from a previous attempt.

Fix

Find and remove the owner, or publish on another port such as -p 8090:3000.

bash
docker psdocker rm -f web
exec format error

Cause

The image was built for a different CPU architecture than your machine, for example an amd64-only image on an Apple Silicon (arm64) laptop. The official images in this tutorial support both, so this usually points at a third-party image.

Fix

Check the architecture and ask for the one you need. Docker can emulate amd64 on arm64, more slowly.

bash
docker image inspect IMAGE --format "{{.Architecture}}"docker run --platform linux/amd64 IMAGE
no space left on device

Cause

Docker's disk (the VM disk on Windows and macOS) is full of old images, stopped containers and build cache.

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.

bash
docker system dfdocker system prune
toomanyrequests: You have reached your pull rate limit

Cause

Docker Hub limits how many images an anonymous or free account may pull in a period, and your network, such as a shared office or college, has used it up.

Fix

Wait and retry, or sign in, which usually gives a higher allowance. Check Docker's current limits on its site.

bash
docker login
connect ECONNREFUSED 127.0.0.1:6379

Cause

The app cannot reach Redis. Inside a container, 127.0.0.1 is the container itself, not Redis. This is what you get if REDIS_URL is missing, because the app falls back to localhost.

Fix

Make sure both containers share a network and the URL uses the container name.

bash
docker run -d --name web --network hits-net -p 8080:3000 -e REDIS_URL=redis://cache:6379 hits:1.0

With 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

Compose waited for Redis to pass its health check and it never did. Redis may have crashed, or the health check command is wrong.

Fix

Read Redis's own output and fix what it complains about.

bash
docker compose logs redisdocker compose down -vdocker compose up -d --wait

Next steps and sources