DevOps

Docker Fundamentals: Complete Guide

· Pavan Y N · docker, containers, devops, linux

Docker packages an application together with its dependencies, libraries, and configuration into a container image, so the same artifact runs the same way on a laptop, a CI runner, and a production host. EduGeek explains the core pieces here: images, containers, volumes, networking, and Docker Compose, with commands that work on current Docker Engine and Docker Desktop releases.

# What is Docker?

Docker is a platform for developing, shipping, and running applications in containers. A container is a running process (or group of processes) that is isolated from the rest of the host but shares the host's kernel. Everything the application needs in user space (runtime, libraries, configuration files) ships inside the image the container starts from.

# Containers vs virtual machines

## Virtual machines (VMs)

  • →Include a full guest operating system with its own kernel
  • →Typically gigabytes in size
  • →Boot in tens of seconds to minutes
  • →Higher per-instance resource overhead
  • →Strong isolation through a hypervisor

## Containers

  • →Share the host operating system kernel
  • →Typically tens to hundreds of megabytes in size
  • →Start in about a second
  • →Lower per-instance resource overhead
  • →Process-level isolation using kernel features such as namespaces and cgroups

When to use which

  • →Containers: microservices, CI/CD jobs, cloud-native applications, and anything that benefits from fast, repeatable packaging.
  • →VMs: workloads that need a different kernel or operating system, or a stronger isolation boundary than a shared kernel provides.

The two combine well in practice. On cloud platforms, containers commonly run inside VMs.

# Docker architecture

Docker uses a client-server architecture. The Docker client (docker) sends API requests to the Docker daemon (dockerd), which manages images, containers, networks, and volumes. The client and daemon communicate over a REST API, through a UNIX socket or a network interface.

code
┌─────────────┐
│ Docker CLI  │ (client)
└──────┬──────┘
       │ REST API
       ↓
┌─────────────┐
│Docker Daemon│ (server)
└──────┬──────┘
       │
       ├→ Images
       ├→ Containers
       ├→ Networks
       └→ Volumes

## Key components

  1. •Docker daemon: the background service that manages Docker objects.
  2. •Docker client: the command-line tool that talks to the daemon.
  3. •Registry: stores images. Docker Hub is the default public registry, and private registries work the same way.
  4. •Image: a read-only template with instructions for creating a container.
  5. •Container: a runnable instance of an image.

# Docker images

Images are the building blocks of containers.

## Image layers

An image is a stack of immutable layers. Instructions that change the filesystem (RUN, COPY, ADD) add layers. Instructions that only record configuration (CMD, ENV, EXPOSE, LABEL) appear in docker history as 0 B entries.

code
# Base layer
FROM ubuntu:24.04

# Filesystem layer: install packages (update and install in the same RUN)
RUN apt-get update && apt-get install -y --no-install-recommends nginx \
    && rm -rf /var/lib/apt/lists/*

# Filesystem layer: add the application files
COPY app /var/www/html

# Metadata only
CMD ["nginx", "-g", "daemon off;"]

Comments must start a line. A # placed after an instruction is not a comment. The Dockerfile reference states that a # anywhere else in a line is treated as an argument, so FROM ubuntu:24.04 # Base layer fails with FROM requires either one or three arguments.

Layers are cached and reused, which makes builds faster. When a layer changes, every layer after it must be rebuilt. This is why apt-get update and apt-get install belong in the same RUN instruction: a cached update layer can otherwise go stale.

## Working with images

code
# Pull an image from Docker Hub (pin a version tag in real projects)
docker pull nginx:1.30

# List local images
docker image ls

# Build an image from a Dockerfile in the current directory
docker build -t myapp:1.0 .

# Tag an image for a registry
docker tag myapp:1.0 myregistry/myapp:1.0

# Push to the registry
docker push myregistry/myapp:1.0

# Inspect the layers of an image
docker history myapp:1.0

# Remove an image
docker rmi myapp:1.0

BuildKit is the default builder in Docker Engine and Docker Desktop, so no environment variable is needed to enable it.

# Dockerfile best practices

A Dockerfile defines how to build an image:

code
# syntax=docker/dockerfile:1

# Use a specific, supported version tag (Node.js 24 is an LTS release)
FROM node:24-alpine

# Set the working directory
WORKDIR /app

# Copy package files first (better layer caching)
COPY package*.json ./

# Install production dependencies only
RUN npm ci --omit=dev

# Copy the application code
COPY . .

# Document the port the application listens on
EXPOSE 3000

# Run as the non-root user that the Node.js image provides
USER node

# Define the startup command
CMD ["node", "server.js"]

npm ci --only=production is the older spelling. Current npm versions warn that --only is deprecated and ask for --omit=dev instead.

## Best practices

  1. •Use trusted base images: start from Docker Official Images, verified publishers, or Docker Hardened Images, and pin a specific tag. Pinning a digest (FROM alpine:3.23@sha256:...) gives fully reproducible builds but opts out of automatic security fixes unless a tool such as Dependabot updates the digest.
  2. •Keep related commands together: combine apt-get update with apt-get install, and delete package caches in the same RUN so they never land in a layer.
  3. •Order instructions by change frequency: put rarely changing steps (dependency installation) before frequently changing ones (application code).
  4. •Use a .dockerignore file: exclude .git, node_modules, local .env files, and build output from the build context.
  5. •Use multi-stage builds: keep compilers and build tools out of the final image.
  6. •Run as a non-root user: set an explicit USER, and scan images for vulnerabilities.
  7. •Lint the Dockerfile: docker build --check . runs BuildKit's built-in Dockerfile checks without building the image.

# Docker containers

Containers are running instances of images.

## Container lifecycle

code
# Create and start a container
docker run -d --name myapp -p 8080:80 nginx:1.30

# List running containers
docker ps

# List all containers, including stopped ones
docker ps -a

# Stop a container
docker stop myapp

# Start a stopped container
docker start myapp

# Restart a container
docker restart myapp

# Remove a container
docker rm myapp

# Remove all stopped containers
docker container prune

## Container options

code
# Set environment variables
docker run -e DB_HOST=localhost -e DB_PORT=5432 myapp

# Mount a host directory (bind mount)
docker run -v /host/path:/container/path myapp

# Set resource limits: 512 MB of memory and at most one CPU
docker run --memory="512m" --cpus="1.0" myapp

# Run interactively with a shell
docker run -it ubuntu bash

# Run in the background (detached)
docker run -d nginx:1.30

# Remove the container automatically when it exits
docker run --rm myapp

--memory is a hard limit. --cpus="1.0" caps CPU use at the equivalent of one CPU, and it does not reserve that capacity.

# Docker volumes

Anything written inside a container's writable layer is lost when the container is removed. Volumes persist data beyond the container lifecycle:

code
# Create a volume
docker volume create mydata

# Use the volume in a container
docker run -v mydata:/app/data myapp

# List volumes
docker volume ls

# Inspect a volume
docker volume inspect mydata

# Remove a volume
docker volume rm mydata

## Storage types

  1. •Volumes: persistent storage managed by the Docker daemon. This is the usual choice for databases and other long-lived data.
  2. •Bind mounts: a direct link between a host path and a container path, common for source code in development.
  3. •tmpfs mounts: temporary storage held in the host's memory and never written to disk.

# Docker networking

## Network drivers

  1. •bridge (default): containers on the same bridge network can talk to each other, and published ports reach the outside world.
  2. •host: removes network isolation between the container and the host.
  3. •none: no networking.
  4. •overlay: connects multiple Docker daemons, used with Swarm.
  5. •macvlan and ipvlan: give containers addresses directly on the physical network or on VLANs.

The built-in default bridge network and a user-defined bridge network behave differently. On the default bridge, containers reach each other by IP address only. On a user-defined bridge, Docker's embedded DNS server also resolves container names. Create your own network for any multi-container setup.

code
# Create a network
docker network create mynetwork

# Run a container on the network
docker run --network mynetwork myapp

# Connect a running container to a network
docker network connect mynetwork myapp

# List networks
docker network ls

# Inspect a network
docker network inspect mynetwork

## Container communication

code
# Containers on the same user-defined network can reach each other by name
docker network create appnet
docker run -d --name database --network appnet -e POSTGRES_PASSWORD=change-me postgres:18-alpine
docker run -d --name webapp --network appnet myapp

# webapp can connect to the database using the hostname "database"

The PostgreSQL image refuses to start without a non-empty POSTGRES_PASSWORD. Without it, the container exits immediately with "Database is uninitialized and superuser password is not specified."

# Docker Compose

Docker Compose describes a multi-container application in one file and manages it with the docker compose command. The file is conventionally named compose.yaml.

code
services:
  web:
    build: .
    ports:
      - "8080:80"
    environment:
      DB_HOST: database
    depends_on:
      database:
        condition: service_healthy
    networks:
      - appnet

  database:
    image: postgres:18-alpine
    environment:
      POSTGRES_PASSWORD_FILE: /run/secrets/db_password
    secrets:
      - db_password
    volumes:
      - dbdata:/var/lib/postgresql
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U postgres"]
      interval: 5s
      timeout: 3s
      retries: 10
    networks:
      - appnet

secrets:
  db_password:
    file: ./db_password.txt

volumes:
  dbdata:

networks:
  appnet:

A few details in this file differ from older tutorials:

  • →No version: key. The top-level version property is obsolete. Compose ignores it, warns that it is obsolete, and always validates against the latest Compose Specification.
  • →depends_on with condition: service_healthy. A plain depends_on list only controls start order. It does not wait for the database to accept connections.
  • →PostgreSQL 18 and later mount at /var/lib/postgresql. For PostgreSQL 17 and earlier, the volume goes at /var/lib/postgresql/data. The official image documentation says the data directory moved to a version-specific path (/var/lib/postgresql/18/docker) starting with version 18.
  • →A file-based secret instead of a hardcoded password. The image reads the value from /run/secrets/db_password through POSTGRES_PASSWORD_FILE. Keep db_password.txt out of version control.
code
# Start all services in the background
docker compose up -d

# Stop and remove the containers and networks
docker compose down

# Follow the logs
docker compose logs -f

# Run three containers of a service
docker compose up -d --scale web=3

The hyphenated docker-compose command belongs to Compose v1, which Docker marked as deprecated when Compose v2 became generally available in April 2022 and which GitHub removed from its hosted runner images on July 9, 2024. Compose v2 ships as the docker compose plugin in Docker Desktop and Docker Engine packages.

Scaling has one catch. The example above publishes a fixed host port (8080:80), so --scale web=3 fails: the second container cannot bind a port the first already holds, and Docker reports port is already allocated. Publish a port range such as "8080-8082:80", or publish no host port and put a reverse proxy in front of the replicas.

# Troubleshooting common issues

## Container will not start

code
# Show the logs
docker logs myapp

# Show the last 100 lines
docker logs --tail 100 myapp

# Follow logs in real time
docker logs -f myapp

## Container exits immediately

code
# The STATUS column shows the exit code, for example "Exited (1)"
docker ps -a

# Print the exit code directly
docker inspect --format '{{.State.ExitCode}}' myapp

# Inspect the full container configuration and state
docker inspect myapp

# Start a shell instead of the default command
# (use sh: many slim and Alpine images do not include bash)
docker run -it --entrypoint sh myapp

Exit code 137 means the process received SIGKILL, which is often the kernel's out-of-memory killer enforcing a --memory limit.

## Port already in use

code
# Find the process using the port (Linux)
ss -ltnp | grep :8080

# Or publish on a different host port
docker run -p 8081:80 nginx:1.30

## Out of disk space

code
# See what is using space
docker system df

# Remove dangling images
docker image prune

# Remove stopped containers
docker container prune

# Remove unused anonymous volumes (add --all to include named volumes)
docker volume prune

# Remove stopped containers, unused networks, and all unused images
docker system prune -a

docker volume prune removes only anonymous volumes unless --all is passed, and docker system prune leaves volumes alone unless --volumes is passed. Check docker volume ls before pruning volumes, because a volume that no container currently uses may still hold data worth keeping.

# Security best practices

  1. •Use trusted images: prefer Docker Official Images, verified publishers, and Docker Hardened Images, which have a free Community tier under the Apache 2.0 license.
  2. •Scan for vulnerabilities: use Docker Scout, Trivy, or Snyk, and fail CI on critical findings.
  3. •Run as non-root: set USER to an unprivileged account.
  4. •Limit resources: set memory and CPU limits.
  5. •Keep secrets out of images: never bake credentials into ENV, ARG, or image layers. Use runtime secrets or BuildKit secret mounts (see Advanced Docker).
  6. •Keep base images updated: rebuild regularly to pick up security fixes.
  7. •Use minimal images: slim, Alpine, or distroless variants reduce attack surface.

# Real-world example

A complete Node.js application with a multi-stage build. The first stage installs all dependencies and builds the app. The runtime stage receives only production dependencies and the build output:

code
# syntax=docker/dockerfile:1

# Build stage: full dependencies plus build tooling
FROM node:24-alpine AS build
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build && npm prune --omit=dev

# Runtime stage
FROM node:24-alpine
ENV NODE_ENV=production
WORKDIR /app
COPY --from=build --chown=node:node /app/node_modules ./node_modules
COPY --from=build --chown=node:node /app/dist ./dist
COPY --chown=node:node package*.json ./
EXPOSE 3000
USER node
CMD ["node", "dist/server.js"]

npm prune --omit=dev removes development dependencies from node_modules in the build stage, so the copy into the runtime stage carries production packages only. Copying node_modules straight from a stage that ran a plain npm ci would ship every development dependency into production.

# Next steps

  1. •Install Docker Desktop or Docker Engine and run docker run hello-world.
  2. •Build a Dockerfile for one of your own applications and run docker build --check . on it.
  3. •Move a multi-container setup into a compose.yaml file.
  4. •Continue with Advanced Docker for multi-stage patterns, BuildKit cache and secret mounts, and hardening.
  5. •When containers need scheduling across machines, continue with Kubernetes Fundamentals, and see Linux Essentials for DevOps for the kernel features containers rely on.

# Key takeaways

  • →A container is an isolated process that shares the host kernel, while a VM runs a full guest operating system, so containers start faster and cost less per instance but isolate less strongly.
  • →Only filesystem-changing instructions (RUN, COPY, ADD) add image layers, and a changed layer invalidates every layer after it, so order instructions from least to most frequently changed.
  • →A # after an instruction is passed as an argument rather than treated as a comment, so comments must sit on their own lines.
  • →Create user-defined networks for multi-container setups, because only they resolve container names through Docker's embedded DNS.
  • →Write Compose files as compose.yaml without the obsolete version: key, run them with docker compose, and use depends_on with condition: service_healthy when startup order matters.
  • →Mount PostgreSQL 18 and later volumes at /var/lib/postgresql, and always supply a non-empty superuser password.
  • →In multi-stage builds, install development dependencies only where they are needed to build, and copy only production dependencies and build output into the final image.

# Further reading

Test yourself: Docker Fundamentals assessment

All posts