SDSystem DesignConcepts to case studies
System DesignDSA
x
0/311
Part 1: Foundations
Part 2: APIs and Communication
Part 3: Caching
Part 4: Data and Storage
Part 5: Architecture
  • Client-Server
  • Monolithic Architecture
  • Microservices
  • Serverless
  • Event-Driven Architecture
  • Peer-to-Peer (P2P)
  • Hexagonal Architecture
  • CQRS
  • Event Sourcing
  • Domain-Driven Design (DDD)
  • Layered (N-Tier) Architecture
  • Containers and Docker
  • Kubernetes Basics
  • Clean Architecture and Modular Monolith
  • Multi-Tenancy
  • Cloud Basics: Regions, Zones and Edge
Part 6: Distributed Systems
Part 7: Advanced Data Topics
Part 8: Operations and Security
Part 9: Estimation and Interview Method
Part 10: Case Studies
System Design/Architecture/Architectural Patterns

Containers and Docker

Pack an app with everything it needs into one light, portable box that runs the same everywhere.

⏱ 14 min readBeginnerMust KnowInterview FavouriteHas visualizer
SummaryConceptReal-Life ExampleWhy?Where?How It WorksStepsKey TermsPros & ConsMistakesReal WorldRead NextInterview Q&ACheat-Sheet

01Quick Summary

A container packs an app together with everything it needs to run (libraries, tools, settings) into one light, portable box. Docker is the best-known tool for building and running them.

  • A container runs as an isolated process that shares the host's operating system kernel, so it starts in moments and uses little memory.
  • An image is the read-only recipe and the packed files. A container is a running copy of an image.
  • The same image runs the same way on a laptop, a test server and in the cloud. That ends "it works on my machine".
  • Containers are meant to be disposable. Data you want to keep must live outside, in a volume or a database.

02Concept: What is it?

Before containers, you installed an app by hand on a server: the right language version, the right libraries, the right settings. Two apps on one machine could need different versions of the same library and fight each other. And the test server never quite matched production.

A container solves this by bundling the app with its dependencies. Under the hood, Linux features isolate it: namespaces give each container its own view of processes, network and files, and control groups (cgroups) cap how much CPU and memory it may use. It looks like a small separate computer, but it is only a well-fenced process.

Container or virtual machine?

A virtual machine carries a whole OS. A container shares the host kernel.
Virtual machines
📱App A
📱App B
🐧Guest OS
🐧Guest OS
🧬Hypervisor
🖥️Host hardware
Containers
📦App A
📦App B
🐳Container runtime
🐧Host OS (shared kernel)
🖥️Host hardware
Extra OS per VM Light container
That is why containers start faster and use less memory, and why a VM is isolated more strongly.

Image and container

  • An image is built from layers, each one a step in the recipe. It never changes after it is built.
  • A container is an image that is running, with a thin writable layer on top. Delete the container and that layer is gone.
  • A registry (Docker Hub, or a private one) stores and shares images, which are named with a tag.
From Dockerfile to a running container
📝Dockerfilethe recipe
→↓build
🧱Imageread-only layers
→↓push
🗂️Registryshared store
→↓pull and run
📦Containerrunning copy
Build once, run anywhere the container runtime is installed.

03Real-Life Example

🍵The Shipping Container
Before shipping containers, every cargo was loaded by hand in its own way, and ports needed special cranes for each kind. Then the industry agreed on one standard steel box. Now a crane can lift any box, a ship can carry any box, and a truck can haul any box, without caring about what is inside. Software containers do the same: the box is standard, so any machine with a runtime can run it, whatever the app inside is made of.
Shipping
Containers
A standard steel box
A container image
What is packed inside
The app, its libraries and settings
Cranes, ships and trucks
Any host with a container runtime
A box on a ship right now
A running container
The packing list on the box
The Dockerfile and image tag
The port warehouse
A container registry
Opening the box leaves nothing behind
Data inside a container is lost unless it is in a volume
Same image, many places
📦One image
→↓
💻Laptop
🧪Test server
☁️Cloud

04Why Do We Need It?

🧳Runs the same everywhere
The app brings its own libraries, so a laptop, test and production behave alike.
⚡Fast to start
A container starts in moments because there is no guest operating system to boot.
🪶Light on memory
Many containers fit on one host, so you pay for less hardware.
🧱Isolated apps
Two apps with clashing library versions can sit side by side without a fight.
🚢Easy to ship and roll back
You deploy a versioned image, and rolling back is starting the previous one.
📈Easy to scale
Start more copies of the same image when load grows, and stop them when it falls.
Pack the app with everything it needs into a standard box, and it runs the same way wherever the box is opened.

05Where Do We Use It?

🧩Microservices
Each service is built into its own image and deployed on its own.
🔁CI/CD pipelines
Build servers run tests inside containers and publish an image to deploy.
🧑‍💻Local development
Start a database or a queue in one command, without installing it on your machine.
☸️Orchestrators
Kubernetes and similar systems run and heal containers across many machines.
λServerless platforms
Some functions and jobs run as container images behind the scenes.
🧪Testing
Spin up a clean, identical environment for each test run, then throw it away.

06Types / Parts / How It Works

A short Dockerfile (illustrative)

Dockerfile (example, details change with your language and version)
# Small base image, with a pinned version
FROM node:20-slim

WORKDIR /app

# Copy the dependency list first, so this layer is cached
COPY package.json package-lock.json ./
RUN npm ci --omit=dev

# Copy the source last, because it changes most often
COPY . .

# Do not run as root
USER node

EXPOSE 3000
CMD ["node", "server.js"]

Each instruction makes a layer. Docker reuses a cached layer if that line and every line above it are unchanged. That is why the dependency list is copied and installed before the source code: dependencies change rarely, and the source changes all the time.

Container or virtual machine

ContainerVirtual machine
What it runsAn app and its libraries, sharing the host kernelA full guest operating system
Start timeMoments (illustrative: seconds)Slower (illustrative: tens of seconds to minutes)
Size and memorySmall, lightLarge, heavy
IsolationGood, but the kernel is sharedStronger, with a separate kernel
Different OSSame kernel family as the hostAny OS the hypervisor supports
Typical useApps, services, jobsStrong separation, other operating systems

Image layers

Layers stack up, and only the top one is writable
4Container layer (writable)lost when the container is removed
3Your app codeCOPY . .
2DependenciesRUN npm ci
1Base imageFROM node:20-slim
Many containers can share the same read-only layers on disk, which saves space.
VisualizerVirtual machines vs containers, and the Dockerfile layer cacheAdd apps and watch memory grow for VMs and containers. Then change the Dockerfile order and edit a file to see which layers rebuild.
What do you want to see?
Each virtual machine carries its own guest operating system. Containers share the host's kernel.
Virtual machines6.2 GB
Containers2.6 GB
VM x 3
app 200 MB
+1200 MB
app 200 MB
+1200 MB
app 200 MB
+1200 MB
Container x 3
app 200 MB
+15 MB
app 200 MB
+15 MB
app 200 MB
+15 MB
Memory with VMs
6.2 GB
illustrative
Memory with containers
2.6 GB
illustrative
Saved
57%
less memory
Start time
45s vs 2s
VM vs container, illustrative
Running 3 apps, the guest operating systems alone add about 3.6 GB for VMs. Containers add only about 0.04 GB, because they reuse the host kernel. The trade-off: a VM is isolated more strongly.

07How to Use It / Steps / Implementation

Containerising an app well

  1. 1
    Start from a small, trusted base
    Slim images start faster and have fewer things that can be attacked. Pin a version, and do not rely on the latest tag in production.
  2. 2
    Order the Dockerfile for the cache
    Put steps that rarely change (dependencies) before steps that change often (source code).
  3. 3
    Run as a non-root user
    If someone breaks into the app, they do not get full rights inside the container.
  4. 4
    Keep config outside the image
    Pass settings through environment variables or mounted files, so one image works in every environment.
  5. 5
    Never bake secrets into an image
    Anyone with the image can read its layers. Inject secrets when the container starts, from a secret store.
  6. 6
    Store data in volumes
    Anything that must survive a restart goes into a volume or an external database, not into the container layer.
  7. 7
    One main process per container
    Run the web server in one container and the worker in another. They can then be scaled, restarted and logged on their own.
  8. 8
    Tag, scan and push
    Give each build a unique tag, scan it for known weaknesses in the pipeline, and push it to a registry.
💡Tags move, digests do not
A tag such as 1.4 can be pointed at a new image later. A digest (a hash of the image) names exactly one image. Use digests, or unique build numbers, when you need to be sure what is running.
⚠️Containers are not a security wall
They share the host kernel, so a flaw in the kernel can reach every container. Keep hosts patched, drop extra privileges, and use a VM boundary when you run code from strangers.

08Key Terms to Know

TermMeaning in easy words
ContainerAn isolated process that carries its own libraries and shares the host kernel
ImageA read-only package of layers from which containers are started
DockerfileA text recipe that says how to build an image
LayerOne step of an image, which can be cached and shared
RegistryA store for images, such as Docker Hub or a private registry
TagA human-friendly name for an image version, such as 1.4
DigestA hash that names exactly one image
VolumeStorage that lives outside the container and survives its removal
NamespaceA Linux feature that gives a process its own view of things like processes and network
cgroupA Linux feature that limits the CPU and memory a process may use
OrchestratorA system such as Kubernetes that runs and manages many containers

09Pros, Cons and Trade-offs

✅ Pros
  • Same behaviour in every environment
  • Quick to start and light on memory
  • Easy to version, ship and roll back
  • Apps with clashing dependencies can live together
  • A solid base for CI/CD and microservices
⚠️ Cons
  • A shared kernel means weaker isolation than a VM
  • Persistent data needs extra care
  • Many containers need an orchestrator and monitoring
  • Images can hold old, vulnerable packages
  • A learning curve for networking and storage

Trade-offs

ChoiceWe gainWe lose
Containers instead of VMsSpeed and densitySome isolation strength
Small base imageFast pulls and a smaller attack surfaceFewer built-in tools for debugging
Many tiny containersIndependent scaling and deploysMore moving parts to run and watch
Pin exact versionsRepeatable buildsYou must update them on purpose
Use the latest tagNo manual updatesSurprise changes and hard rollbacks
Volume for dataData survives restartsThe container is tied to that storage

10Common Problems and Mistakes

Common mistakes

  1. Storing data inside the container. It disappears when the container is replaced.
  2. Secrets in the image. A password in a layer stays there, even if a later layer deletes the file.
  3. Using the latest tag. Today's deploy may differ from yesterday's with no code change.
  4. Running as root. It widens the damage of any break-in.
  5. Huge images. Full operating system images with build tools make pulls slow and attacks easier.
  6. Copying everything before installing. Any code edit breaks the cache for the slow install step.
  7. Treating a container like a small VM. Logging in to patch it by hand, instead of building a new image.

Things to watch

🧯Out of memory kills
A container that goes over its memory limit is stopped. Set limits from real measurements.
🕳️Old packages
An image built last year may carry known weaknesses. Rebuild and scan on a schedule.
📜Logs
Write logs to standard output so the platform can collect them. Files inside the container vanish.
🌐Networking
Container ports and host ports are different things. Publish only what must be reachable.

11Real-World Examples

☸️Kubernetes clusters
Companies run large numbers of containers across many machines, and the platform restarts failed ones.
🧰CI build agents
Pipelines build and test inside containers so each run starts from a clean, known state.
☁️Managed container services
Cloud providers offer services that run your image without you managing servers.
🧑‍💻Developer environments
A compose file starts the app, a database and a cache with one command.
🧪Integration testing
Tests start a throwaway database in a container, run, and remove it.
🔬Data and ML work
Teams package a model and its exact library versions so results can be reproduced.
📝Note
Tools and defaults change between versions. Check the current Docker and platform documentation before copying a command or setting a limit.
Mini case: a release by image
💻Commit
→↓
🧪Build and testin a container
→↓push
🗂️Registrymyapp:2025.42
→↓deploy
📦Containersrolling update
The pipeline builds one image. The same image moves through every environment.

12Related Topics to Read Next

Kubernetes Basics→

The usual way to run, scale and heal many containers.

Microservices→

Containers make it practical to ship many small services.

Stateless vs Stateful→

Stateless containers are easy to replace. Stateful ones need volumes.

Rolling Deployments→

Replace running containers with a new image, a few at a time.

Rollbacks and Immutable Infrastructure→

Images are never patched in place: you replace them.

Secrets Management→

How to give a container its secrets without baking them into the image.

CI/CD Pipelines→

Where images are built, tested and published.

13Interview Questions with Short Answers

14Quick Revision Cheat-Sheet

  • ✔What: an app packed with its dependencies, run as an isolated process on a shared kernel.
  • ✔Image vs container: read-only recipe and layers, versus the running copy.
  • ✔Vs VM: lighter and faster, with somewhat weaker isolation.
  • ✔Dockerfile: small pinned base, dependencies first, source last, non-root user.
  • ✔Data: in volumes or external databases, never only in the container.
  • ✔Config and secrets: inject at run time, never bake into the image.
  • ✔Tags: avoid latest in production. Use fixed versions or digests.
  • ✔One line: “A standard box for software: pack it once, and run it the same way anywhere.”
← Previous
Layered (N-Tier) Architecture
Next →
Kubernetes Basics