Chapter 1: Docker Basics Introduction

Haiyue
13min

Chapter 1: Docker Basics Introduction

Learning Objectives
  • Understand the concepts and advantages of containerization technology
  • Master Docker’s core architecture and basic components
  • Complete Docker environment installation and configuration
  • Learn to use basic Docker command operations

Knowledge Points

What is Containerization Technology

Containerization is a lightweight virtualization technology that packages applications and their dependencies into a portable container, ensuring applications run consistently in any environment.

Core Features of Containerization Technology:

  • Lightweight: Compared to traditional virtual machines, containers share the host operating system kernel with less resource consumption
  • Portability: Build once, run anywhere, solving the “works on my machine” problem
  • Isolation: Containers are isolated from each other, providing a secure runtime environment
  • Fast Startup: Second-level startup, much faster than traditional virtual machines

Docker Architecture Overview

Docker uses a client-server (C/S) architecture pattern, mainly composed of the following components:

ComponentRoleDescription
Docker ClientClientThe primary way users interact with Docker, sending commands to Docker Daemon
Docker DaemonDaemon ProcessDocker’s core service, handling Docker API requests, managing images, containers, etc.
Docker ImagesImagesRead-only templates used to create Docker containers
Docker ContainerContainersRunning instances of images, can be started, stopped, moved, or deleted
Docker RegistryImage RegistryPlace to store Docker images, such as Docker Hub

Containers vs Virtual Machines

Traditional Virtual Machine Architecture:

🔄 正在渲染 Mermaid 图表...

Docker Container Architecture:

🔄 正在渲染 Mermaid 图表...
Core Differences
  • Resource Overhead: Containers run directly on the host kernel without requiring an additional operating system
  • Startup Time: Container startup time is typically in seconds, virtual machines require minutes
  • Density: The same hardware resources can run more containers
  • Isolation Level: Virtual machines provide stronger isolation, container isolation is relatively weaker but secure enough

Docker Installation and Configuration

Linux System Installation

# Install Docker on Ubuntu/Debian
# Update package index
sudo apt-get update

# Install necessary packages
sudo apt-get install \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg \
    lsb-release

# Add Docker official GPG key
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

# Add Docker official repository
echo \
  "deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# Install Docker Engine
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io

# Verify successful installation
sudo docker run hello-world

CentOS/RHEL System Installation

# Install necessary tools
sudo yum install -y yum-utils

# Add Docker repository
sudo yum-config-manager \
    --add-repo \
    https://download.docker.com/linux/centos/docker-ce.repo

# Install Docker Engine
sudo yum install docker-ce docker-ce-cli containerd.io

# Start Docker service
sudo systemctl start docker
sudo systemctl enable docker

# Verify installation
sudo docker run hello-world

Windows and macOS Installation

# Windows users:
# Download Docker Desktop for Windows
# URL: https://desktop.docker.com/win/main/amd64/Docker%20Desktop%20Installer.exe

# macOS users:
# Download Docker Desktop for Mac
# URL: https://desktop.docker.com/mac/main/amd64/Docker.dmg

# Verify after installation
docker --version
docker-compose --version

Configure Docker User Permissions

# Add current user to docker group (avoid using sudo every time)
sudo usermod -aG docker $USER

# Re-login or use the following command to take effect
newgrp docker

# Test if you can run without sudo
docker run hello-world

Basic Command Operations

# View Docker version information
docker --version
docker version    # Detailed version information
docker info      # System information

# Search for images
docker search nginx
docker search --filter stars=100 nginx  # Filter images with more than 100 stars

# Pull images
docker pull nginx                    # Pull latest nginx
docker pull nginx:1.20             # Pull specific version
docker pull ubuntu:20.04           # Pull Ubuntu 20.04

# View local images
docker images                       # List all images
docker images nginx                # List nginx-related images
docker images --format "table {{.Repository}}\t{{.Tag}}\t{{.Size}}"  # Formatted output

# Delete images
docker rmi nginx:latest             # Delete specific image
docker rmi $(docker images -q)     # Delete all images
docker image prune                  # Clean up unused images
# Run containers
docker run hello-world                      # Run and exit
docker run -it ubuntu:20.04 /bin/bash     # Run Ubuntu interactively
docker run -d nginx                        # Run nginx in background
docker run -d -p 8080:80 nginx            # Run nginx with port mapping
docker run -d --name my-nginx nginx       # Specify container name

# View containers
docker ps                          # View running containers
docker ps -a                       # View all containers (including stopped)
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}"  # Formatted output

# Container operations
docker start my-nginx              # Start container
docker stop my-nginx               # Stop container
docker restart my-nginx            # Restart container
docker pause my-nginx              # Pause container
docker unpause my-nginx            # Unpause container

# Enter containers
docker exec -it my-nginx /bin/bash        # Enter running container
docker attach my-nginx                     # Attach to container (not recommended)

# View container logs
docker logs my-nginx               # View container logs
docker logs -f my-nginx            # Follow logs in real-time
docker logs --tail 100 my-nginx   # View last 100 lines of logs

# Delete containers
docker rm my-nginx                 # Delete stopped container
docker rm -f my-nginx              # Force delete running container
docker rm $(docker ps -aq)        # Delete all containers
docker container prune             # Clean up stopped containers

Practical Command Combinations

# One-click Docker environment cleanup
docker system prune -a             # Clean up all unused images, containers, networks
docker system df                   # View Docker disk usage

# Batch operations
docker stop $(docker ps -q)       # Stop all running containers
docker rm $(docker ps -aq)        # Delete all containers
docker rmi $(docker images -q)    # Delete all images

# Container resource monitoring
docker stats                      # Real-time view of container resource usage
docker stats my-nginx             # View specific container resource usage

# Container detailed information
docker inspect my-nginx           # View detailed container configuration
docker port my-nginx              # View container port mapping
docker top my-nginx               # View container process information

Practical Exercises

Hello World Example

# Run first Docker container
docker run hello-world

# Output explanation:
# 1. Docker client contacts Docker daemon
# 2. Daemon pulls hello-world image from Docker Hub
# 3. Creates a new container and runs the program in the image
# 4. Program outputs message and container stops

Web Server Example

# Run Nginx web server
docker run -d --name web-server -p 8080:80 nginx

# Verify service is running
curl http://localhost:8080
# Or visit http://localhost:8080 in browser

# View container status
docker ps

# View container logs
docker logs web-server

# Enter container
docker exec -it web-server /bin/bash

# Execute commands inside container
ls /usr/share/nginx/html/    # View web files
cat /etc/nginx/nginx.conf    # View nginx configuration

# Exit container
exit

# Stop and delete container
docker stop web-server
docker rm web-server

Data Persistence Example

# Create data volume and run container
docker run -d --name nginx-with-volume \
    -p 8080:80 \
    -v /tmp/nginx-data:/usr/share/nginx/html \
    nginx

# Create custom webpage on host
echo "<h1>Hello from Docker!</h1>" > /tmp/nginx-data/index.html

# Access webpage to see effect
curl http://localhost:8080

# Stop container but data remains on host
docker stop nginx-with-volume
ls /tmp/nginx-data/  # Files still exist

Common Issue Resolution

Permission Issues

# Issue: Got permission denied while trying to connect to the Docker daemon socket
# Solution: Add user to docker group
sudo usermod -aG docker $USER
newgrp docker

# Or temporarily use sudo
sudo docker run hello-world

Network Connection Issues

# Issue: Unable to pull images or connection timeout
# Solution: Configure domestic mirror sources

# Create or edit daemon configuration file
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
    "registry-mirrors": [
        "https://registry.docker-cn.com",
        "https://docker.mirrors.ustc.edu.cn",
        "https://hub-mirror.c.163.com"
    ]
}
EOF

# Restart Docker service
sudo systemctl daemon-reload
sudo systemctl restart docker

# Verify configuration
docker info | grep "Registry Mirrors" -A 3

Storage Space Issues

# Issue: Insufficient disk space
# Solution: Clean up Docker resources

# View disk usage
docker system df

# Clean up unused resources
docker system prune -a    # Clean up all unused images, containers, networks, build cache

# Clean up separately
docker container prune    # Clean up stopped containers
docker image prune        # Clean up unused images
docker network prune      # Clean up unused networks
docker volume prune       # Clean up unused volumes
Important Notes
  • Docker requires 64-bit operating system support
  • In production environments, recommend using specific version tags instead of latest
  • Regularly clean up unused Docker resources to free disk space
  • Containers run as root user by default, pay attention to security

Summary

Through this chapter, you should have mastered:

  • Containerization Concepts: Understood the advantages and application scenarios of containerization technology
  • Docker Architecture: Learned Docker’s core components and working principles
  • Environment Setup: Completed Docker installation and basic configuration
  • Basic Operations: Mastered basic management commands for images and containers
  • Practical Experience: Deepened understanding of Docker through practical cases

In the next chapter, we will dive into Docker image management, including image layered structure, build process, and repository management.