Docker: What is Docker?

Docker ensures that applications run exactly the same way in any environment—it packages "code + dependencies + configuration" into a portable container, putting an end to the "it works on my machine" nightmare.

1. What You'll Learn



2. A True Story of a Backend Developer

(1) Pain Point: Disasters Caused by Inconsistent Environments

Alice is a backend developer. Although her project runs smoothly on her local machine, she frequently encounters the "it works on my machine" problem: her colleagues' Ubuntu environments are missing dependencies, the library versions on the CentOS test server are incorrect, and the Red Hat production environment requires recompilation. Every deployment feels like a gamble—three environments, five rounds of debugging, and two days wasted on "environment configuration" instead of writing code.

(2) The Docker Solution

Bob recommended that she use Docker: "With just one command, the app will run exactly the same way on any Linux system."

BASH
# Build once, run anywhere
docker build -t myapp:1.0 .
docker run -d -p 8080:80 myapp:1.0

(3) Benefit: Environmental Consistency

After Alice packaged the application into a Docker image, the same image was used to run the application in all three environments—development, testing, and production—reducing deployment time from two days to 10 minutes and eliminating all environment-related issues.



3. What Is Containerization?

Containerization is a lightweight virtualization technology that packages an application and all its dependencies into an isolated runtime environment, ensuring consistent execution on any infrastructure.

100%
graph TB
    A[Traditional Deployment<br/>App + OS + Hardware] --> B[Virtualization<br/>App + Guest OS + Hypervisor + Host OS]
    B --> C[Containerization<br/>App + Container Engine + Host OS]
    C --> D["Lighter · Faster · More consistent"]

(1) The Core Concept of Containerization

(2) Why Are They Called "Containers"?

Think of containers in the transportation industry: whether they’re filled with cars, clothes, or food, the ships, trains, and trucks that carry them don’t need to know—they simply transport standard-sized containers. Docker containers are the containers of the software world:

Dimension Shipping Container Docker Container
Standardization Uniform dimensions (20/40 feet) Uniform image format (OCI standard)
Isolation No interference between loads Process/network/filesystem isolation
Portable Can be transported by ship, train, or truck Runs in development, testing, and production environments
Highly Efficient No need to unpack and switch cars No need to reinstall dependencies


4. Containers vs. Virtual Machines

Both containers and virtual machines provide isolated environments, but they are implemented in completely different ways.

100%
graph TB
    subgraph VM["Virtual Machine Architecture"]
        VM_APP1["App 1"] --> VM_OS1["Guest OS"]
        VM_APP2["App 2"] --> VM_OS2["Guest OS"]
        VM_OS1 --> VM_H["Hypervisor"]
        VM_OS2 --> VM_H
        VM_H --> VM_HOST["Host OS"]
        VM_HOST --> VM_HW["Hardware"]
    end
    subgraph CT["Container Architecture"]
        CT_APP1["App 1"] --> CT_APP2["App 2"]
        CT_APP2 --> CT_CE["Container Engine<br/>Docker"]
        CT_CE --> CT_KERNEL["Host OS Kernel"]
        CT_KERNEL --> CT_HW["Hardware"]
    end

(1) Comparison of Key Differences

Dimension Virtual Machine (VM) Container
Isolation Level Hardware-level isolation (separate kernel) Process-level isolation (shared kernel)
Boot Speed Minutes (to boot the entire OS) Seconds (to start a process)
Resource Usage GB-level (including Guest OS) MB-level (application dependencies only)
Image Size 1–20 GB 5–500 MB
Performance Overhead 5–15% (virtualization overhead) ≈0% (close to native)
Density 5–10 VMs per machine 100–1,000 containers per machine

(2) Comparison of Use Cases

Scenario Recommended Virtual Machine Recommended Container
Requires different operating system kernels ✅ (e.g., Windows and Linux running in parallel)
Microservices/Stateless Applications ✅ (Lightweight, fast scaling)
Strong isolation security requirements ✅ (Kernel-level isolation) ⚠️ (Requires additional hardening)
CI/CD Build Environment ✅ (Launches and shuts down in seconds)
Development Environment Consistency ✅ (The image is the environment)
Run traditional GUI applications ⚠️ (Requires additional configuration)
💡 Tip: Containers are not a replacement for virtual machines, but rather a complementary technology. Use virtual machines for scenarios requiring full kernel isolation, and containers for application-level isolation.



5. Docker Architecture

Docker uses a client-server architecture and consists of three core components.

100%
graph TB
    CLI["Docker Client<br/>docker build/run/pull"]
    CLI -->|REST API| D["Docker Daemon<br/>dockerd"]
    D -->|pull/push| R["Docker Registry<br/>Docker Hub / Private"]
    D -->|create/start| C["Containers<br/>Running instances"]
    D -->|build/cache| I["Images<br/>Read-only templates"]
    I -->|docker run| C
    R -->|docker pull| I

(1) A Detailed Explanation of the Three-Tier Architecture

Component Function Common Commands
Docker Client The command-line interface that users use to interact with Docker docker run / docker build / docker pull
Docker Daemon Background service that manages images, containers, networks, and volumes systemctl start docker / dockerd
Docker Registry A repository for storing and distributing images docker pull / docker push

(2) The Relationship Between Images and Containers

An image is a read-only template, and a container is a running instance of an image. To draw an analogy with object-oriented programming:

Concept OOP Analogy Description
Image Class A read-only template that defines everything needed to run the application
Container Instance The running state of an image; readable and writable; has a lifecycle
Dockerfile Source Code Instruction file for building images

(3) OCI Standard

Docker adheres to the OCI (Open Container Initiative) standard to ensure container portability:

📌 Key Point: The OCI standard means that images built with Docker can also run on other container runtimes, such as Podman and containerd.



6. Key Use Cases for Docker

(1) Scenario Overview

Scenario Description Example
Standardization of the Development Environment Unified development environment for the team New members can set up the complete development stack in 10 minutes
Microservice Deployment Each service runs in its own container API, DB, and Cache are each containerized
CI/CD Pipeline Consistent and repeatable build environment GitHub Actions + Docker for automated deployment
Rapid Scaling Instances launched/shut down in seconds 1→10 replicas during traffic peaks, 10→1 during off-peak hours
Containerization of Legacy Applications Migrate legacy applications without modification Package a 2015 PHP 5.4 project into a container

(2) The Container Startup Process

When you run docker run hello-world, the following steps take place internally in Docker:

100%
graph LR
    A["docker run<br/>hello-world"] --> B{"There is a local mirror?"}
    B -->|No| C["docker pull<br/>from Registry Pull"]
    B -->|Yes| D["Create a Container<br/>Writable layer"]
    C --> D
    D --> E["Start the container<br/>Execute CMD"]
    E --> F["Output Results<br/>Hello from Docker!"]


7. Hands-On Experience with Docker

▶ Example: Running "hello-world" (Difficulty: ⭐)

The Simplest Way to Try Docker—Verify That Docker Is Installed Correctly.

BASH
# Pull and run the hello-world image
docker run hello-world
💻 Output:

TEXT
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
e6590344b1a5: Pull complete
Digest: sha256:7be1...2c2d
Status: Downloaded newer image for hello-world:latest

Hello from Docker!
This message shows that your installation appears to be working correctly.

▶ Example: Viewing Docker Configuration Information (Difficulty: ⭐)

docker info Displays the complete configuration of the Docker daemon.

BASH
# Display system-wide Docker information
docker info
💻 Output (excerpt):

TEXT
Client: Docker Engine - Community
 Version:    24.0.7
 Context:    default

Server:
 Containers: 3
  Running: 1
  Paused: 0
  Stopped: 2
 Images: 5
 Server Version: 24.0.7
 Storage Driver: overlay2
 Kernel Version: 5.15.0-91-generic
 Operating System: Ubuntu 22.04

▶ Example: Browse Docker command categories (Difficulty: ⭐)

The Docker CLI is categorized by management objects for easy memorization.

BASH
# List all Docker management commands
docker --help
💻 Output (excerpt):

TEXT
Management Commands:
  builder     Manage builds
  container   Manage containers
  image       Manage images
  network     Manage networks
  volume      Manage volumes
  system      Manage Docker

Commands:
  run         Create and run a new container
  ps          List containers
  images      List images
  build       Build an image from a Dockerfile
  pull        Pull an image from a registry

▶ Example: Try running the Nginx web server (Difficulty: ⭐⭐)

Start a web server with a single Docker command—no need to install Nginx.

BASH
# Run Nginx in detached mode, map port 8080 to container port 80
docker run -d -p 8080:80 --name my-nginx nginx:latest

# Verify the container is running
docker ps
💻 Output:

TEXT
CONTAINER ID   IMAGE          STATUS         PORTS                  NAMES
a1b2c3d4e5f6   nginx:latest   Up 10 seconds  0.0.0.0:8080->80/tcp   my-nginx

Open your browser and go to http://localhost:8080 to see the Nginx welcome page.

▶ Example: View the list of currently running containers (Difficulty: ⭐)

BASH
# List all running containers
docker ps

# List all containers (including stopped ones)
docker ps -a
💻 Output:

TEXT
CONTAINER ID   IMAGE           STATUS                    PORTS       NAMES
a1b2c3d4e5f6   nginx:latest    Up 5 minutes              8080->80    my-nginx
f7e8d9c0b1a2   hello-world     Exited (0) 3 minutes ago              hungry_einstein
⚠️ Note: The hello-world container automatically exits after running (status: Exited). This is not an error—it is a demo container designed to exit once it has finished running.



8. Verifying the Docker Version and Installation

(1) Docker Versioning System

Version Positioning Update Frequency Use Cases
Docker Desktop Developer Desktop Edition Quarterly Updates Windows / Mac Development Environment
Docker Engine Server Edition Quarterly Updates Linux Production Environment
Docker CE Community Edition (Free) Continuously updated Individuals and small teams
Docker EE Enterprise Edition (Paid) Continuously Updated Large Enterprises + Commercial Support

(2) Verify that the installation was successful

BASH
# Check Docker client and server versions
docker version

# Quick verification: run hello-world
docker run hello-world

If docker version displays both Client and Server information, the installation was successful.



9. Complete Example: A Step-by-Step Guide to Getting Started with Docker

BASH
# ============================================
# Complete walkthrough: First Docker experience
# Covers: version check, info, run, ps, clean
# ============================================

# 1. Verify Docker is installed and running
docker version

# 2. View Docker system information
docker info

# 3. Run the hello-world container (first pull, then run)
docker run hello-world

# 4. Run an Nginx web server
docker run -d -p 8080:80 --name web nginx:latest

# 5. List running containers
docker ps

# 6. Stop and remove the Nginx container
docker stop web
docker rm web

# 7. View all containers (including stopped)
docker ps -a

# 8. Clean up: remove the stopped hello-world container
docker rm $(docker ps -a -q --filter "ancestor=hello-world")
💻 Output (excerpt):

TEXT
# docker version
Client: Docker Engine - Community
 Version:    24.0.7
Server: Docker Engine - Community
 Version:    24.0.7

# docker run hello-world
Hello from Docker!

# docker ps (while Nginx is running)
CONTAINER ID   IMAGE          STATUS         PORTS                  NAMES
a1b2c3d4e5f6   nginx:latest   Up 10 seconds  0.0.0.0:8080->80/tcp   web

❓ FAQ

Q What is the difference between Docker and VirtualBox?
A VirtualBox emulates a complete operating system (including the kernel), takes minutes to start up, and consumes gigabytes of resources. Docker shares the host’s kernel and isolates only processes; it starts up in seconds and consumes megabytes of resources. Docker is lighter and faster, but it does not support running Windows containers on a Linux host (and vice versa).
Q Does a container run an operating system?
A No. Containers share the host’s kernel; they do not have their own kernel. The “Ubuntu” inside a container is merely a set of user-space tools (such as bash and apt), not a full-fledged operating system. This is the fundamental reason why containers are lighter than virtual machines.
Q Can Docker only be used on Linux?
A Docker containers rely on Linux kernel features (namespaces/cgroups), so they run natively on Linux. Docker Desktop on Windows and Mac runs containers indirectly through built-in Linux virtual machines (WSL2/Hypervisor), which is transparent to the user.
Q How do I install Docker on Windows?
A Install Docker Desktop for Windows; it will automatically use WSL2 as its backend. This requires Windows 10 64-bit (version 1903 or later) with WSL2 enabled. After installation, open Docker Desktop and run docker run hello-world in the terminal to verify it works.
Q Can containers leak host data?
A By default, no. Containers use Linux namespaces to isolate file systems, networks, and processes, so they cannot directly access host files. Unless a host directory is explicitly mounted (using the -v parameter), containers are isolated from the host. However, running a container with the --privileged option breaks this isolation; this should be disabled in production environments.
Q What is the relationship between Docker and Kubernetes?
A Docker is a container runtime (responsible for building and running individual containers), while Kubernetes is a container orchestration platform (responsible for managing the scheduling, scaling, and self-healing of hundreds or thousands of containers). K8s uses containerd (a runtime spun off from Docker) to run containers and no longer relies directly on Docker.
Q Do I need to know Linux to learn Docker?
A You’ll need basic Linux command-line skills (ls, cd, mkdir, cat, grep), but you don’t need to be an expert in Linux. Docker’s core operations are all performed using the docker command. This tutorial starts from scratch, and any necessary Linux concepts will be explained as we go.

📖 Summary


📝 Exercises

  1. Basic Exercise (Difficulty: ⭐): Install Docker Desktop and run docker run hello-world, then take a screenshot or copy the output.
  2. Advanced Exercise (Difficulty ⭐⭐): Run docker info to view your local Docker configuration, and record the values for the three fields: Number of Containers, Storage Driver, and Kernel Version.
  3. Challenge Question (Difficulty: ⭐⭐⭐): List three advantages and three disadvantages of containers and virtual machines, respectively, and explain in which scenarios you should choose containers and in which scenarios you should choose virtual machines.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏