Introduction to Docker and Containerization

Docker revolutionizes application deployment by packaging applications and their dependencies into lightweight, portable containers that run consistently across different environments.

What is Docker?

Docker is a containerization platform that allows you to package applications with all their dependencies into portable containers. Think of containers as lightweight, standalone packages that include everything needed to run an application: code, runtime, system tools, libraries, and settings.

Traditional Deployment vs. Containerization

Traditional Deployment:
┌─────────────────────────────────────┐
│           Physical Server           │
├─────────────────────────────────────┤
│         Operating System            │
├─────────────────────────────────────┤
│    App A    │    App B    │  App C  │
│  (Python)   │   (Node.js) │ (Java)  │
│   Deps A    │    Deps B   │ Deps C  │
└─────────────────────────────────────┘
Problems: Dependency conflicts, "works on my machine"

Docker Containerization:
┌─────────────────────────────────────┐
│           Physical Server           │
├─────────────────────────────────────┤
│         Operating System            │
├─────────────────────────────────────┤
│            Docker Engine            │
├─────────────────────────────────────┤
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ │
│ │Container│ │Container│ │Container│ │
│ │   A     │ │   B     │ │   C     │ │
│ │(Python) │ │(Node.js)│ │ (Java)  │ │
│ │ Deps A  │ │ Deps B  │ │ Deps C  │ │
│ └─────────┘ └─────────┘ └─────────┘ │
└─────────────────────────────────────┘
Benefits: Isolation, consistency, portability

Key Docker Concepts

Images

  • Docker Image: A read-only template used to create containers
  • Contains application code, dependencies, and configuration
  • Built in layers for efficiency
  • Stored in registries (Docker Hub, private registries)

Containers

  • Docker Container: A running instance of an image
  • Lightweight and isolated from other containers
  • Can be started, stopped, moved, and deleted
  • Share the host OS kernel

Dockerfile

  • Dockerfile: A text file with instructions to build an image
  • Defines the environment and steps to create your application image
  • Version-controlled and reproducible

Registry

  • Docker Registry: A service for storing and distributing images
  • Docker Hub is the default public registry
  • Can host private registries for internal use

Why Use Docker?

1. Consistency

# Same container runs identically everywhere
docker run myapp:latest
# Works on development, staging, and production

2. Portability

# Move containers between environments
docker save myapp:latest > myapp.tar
docker load < myapp.tar

3. Efficiency

# Lightweight compared to VMs
# Fast startup times
docker run -d nginx  # Starts in seconds

4. Scalability

# Easy horizontal scaling
docker run -d --name web1 myapp:latest
docker run -d --name web2 myapp:latest
docker run -d --name web3 myapp:latest

Installing Docker

Windows

Docker Desktop for Windows

  1. Download: Visit docker.com and download Docker Desktop

  2. System Requirements:

    • Windows 10 64-bit: Pro, Enterprise, or Education
    • Hyper-V and Containers Windows features enabled
    • BIOS-level hardware virtualization support
  3. Installation Steps:

    # Download and run Docker Desktop Installer.exe
    # Follow the installation wizard
    # Restart your computer when prompted
    
    # Verify installation
    docker --version
    docker run hello-world
    
# Enable WSL 2
wsl --install

# Set WSL 2 as default
wsl --set-default-version 2

# Install Ubuntu from Microsoft Store
# Configure Docker Desktop to use WSL 2 backend

macOS

Docker Desktop for Mac

  1. Download: Get Docker Desktop from docker.com

  2. System Requirements:

    • macOS 10.14 or newer
    • 4GB RAM minimum
    • VirtualBox prior to version 4.3.30 must be uninstalled
  3. Installation:

    # Download Docker.dmg
    # Drag Docker to Applications folder
    # Launch Docker from Applications
    
    # Verify installation
    docker --version
    docker run hello-world
    

Using Homebrew

# Install Docker Desktop via Homebrew
brew install --cask docker

# Start Docker Desktop
open /Applications/Docker.app

# Verify installation
docker --version

Linux

Ubuntu/Debian

# Update package index
sudo apt update

# Install prerequisites
sudo apt install apt-transport-https ca-certificates curl gnupg lsb-release

# Add Docker's 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 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

# Update package index again
sudo apt update

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

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

# Add user to docker group (optional, for non-root usage)
sudo usermod -aG docker $USER
newgrp docker

# Verify installation
docker --version
docker run hello-world

CentOS/RHEL/Fedora

# Install required packages
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 and enable Docker
sudo systemctl start docker
sudo systemctl enable docker

# Add user to docker group
sudo usermod -aG docker $USER

# Verify installation
docker --version
docker run hello-world

Docker Architecture

Docker Engine Components

┌─────────────────────────────────────┐
│            Docker Client            │
│         (docker command)            │
└─────────────┬───────────────────────┘
              │ REST API
┌─────────────▼───────────────────────┐
│          Docker Daemon              │
│         (dockerd process)           │
├─────────────────────────────────────┤
│  ┌─────────┐ ┌─────────┐ ┌────────┐ │
│  │Container│ │Container│ │ Image  │ │
│  │    1    │ │    2    │ │ Store  │ │
│  └─────────┘ └─────────┘ └────────┘ │
└─────────────────────────────────────┘

Key Components

  1. Docker Client: Command-line interface (CLI) that users interact with
  2. Docker Daemon: Background service that manages containers, images, networks
  3. Docker Registry: Stores and distributes Docker images
  4. Docker Objects: Images, containers, networks, volumes

Your First Docker Commands

Verify Installation

# Check Docker version
docker --version
# Output: Docker version 20.10.x, build xxxxx

# Check system information
docker info

# Test with hello-world
docker run hello-world

Basic Image Operations

# Search for images on Docker Hub
docker search nginx

# Pull an image from registry
docker pull nginx:latest

# List local images
docker images
# or
docker image ls

# Remove an image
docker rmi nginx:latest
# or
docker image rm nginx:latest

Basic Container Operations

# Run a container (interactive)
docker run -it ubuntu:latest /bin/bash

# Run a container (detached/background)
docker run -d --name my-nginx nginx:latest

# List running containers
docker ps

# List all containers (including stopped)
docker ps -a

# Stop a container
docker stop my-nginx

# Start a stopped container
docker start my-nginx

# Remove a container
docker rm my-nginx

# Remove a running container (force)
docker rm -f my-nginx

Practical Examples

Example 1: Running a Web Server

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

# Access the web server
# Open browser to http://localhost:8080

# View container logs
docker logs webserver

# Execute commands in running container
docker exec -it webserver /bin/bash

# Stop and remove
docker stop webserver
docker rm webserver

Example 2: Running a Database

# Run MySQL database
docker run -d \
  --name mysql-db \
  -e MYSQL_ROOT_PASSWORD=mypassword \
  -e MYSQL_DATABASE=testdb \
  -p 3306:3306 \
  mysql:8.0

# Connect to the database
docker exec -it mysql-db mysql -u root -p

# View database logs
docker logs mysql-db

# Stop and remove (with volume cleanup)
docker stop mysql-db
docker rm mysql-db

Example 3: Development Environment

# Run Python development environment
docker run -it \
  --name python-dev \
  -v $(pwd):/workspace \
  -w /workspace \
  python:3.9 \
  /bin/bash

# Inside the container, you can:
# pip install packages
# run Python scripts
# develop and test code

Docker Hub and Image Registry

Exploring Docker Hub

# Search for official images
docker search --filter is-official=true python

# Pull specific versions
docker pull python:3.9
docker pull python:3.9-slim
docker pull python:3.9-alpine

# View image details
docker inspect python:3.9

# View image history (layers)
docker history python:3.9

Understanding Image Tags

# Different ways to specify images
docker pull nginx                    # Latest tag (default)
docker pull nginx:latest            # Explicit latest
docker pull nginx:1.21              # Specific version
docker pull nginx:1.21-alpine       # Version with variant
docker pull nginx:stable            # Stable release

Container Lifecycle Management

Container States

┌─────────┐    docker run     ┌─────────┐
│ Created │ ──────────────────▶│ Running │
└─────────┘                   └─────────┘
     ▲                             │
     │                             │ docker stop
     │ docker create               ▼
     │                        ┌─────────┐
     └────────────────────────│ Stopped │
          docker start        └─────────┘
                                   │
                                   │ docker rm
                                   ▼
                              ┌─────────┐
                              │ Removed │
                              └─────────┘

Lifecycle Commands

# Create container without starting
docker create --name my-app nginx:latest

# Start created container
docker start my-app

# Restart running container
docker restart my-app

# Pause/unpause container
docker pause my-app
docker unpause my-app

# Kill container (force stop)
docker kill my-app

# Remove stopped container
docker rm my-app

# Remove running container (force)
docker rm -f my-app

Troubleshooting Common Issues

Permission Issues (Linux)

# If you get permission denied errors
sudo usermod -aG docker $USER
newgrp docker

# Or run with sudo (not recommended for regular use)
sudo docker run hello-world

Port Already in Use

# Check what's using the port
netstat -tulpn | grep :8080
# or
lsof -i :8080

# Use different port
docker run -p 8081:80 nginx

Container Won’t Start

# Check container logs
docker logs container-name

# Inspect container configuration
docker inspect container-name

# Run container interactively for debugging
docker run -it image-name /bin/bash

Disk Space Issues

# Clean up unused containers, images, networks
docker system prune

# Remove all stopped containers
docker container prune

# Remove unused images
docker image prune

# Remove unused volumes
docker volume prune

# See disk usage
docker system df

Best Practices for Beginners

1. Use Official Images

# Prefer official images
docker pull python:3.9        # ✓ Official
docker pull nginx:latest      # ✓ Official
# Avoid random user images for production

2. Specify Image Tags

# Avoid using 'latest' in production
docker pull python:3.9        # ✓ Specific version
docker pull python:latest     # ✗ Unpredictable

3. Clean Up Regularly

# Regular cleanup
docker system prune -f

# Remove stopped containers
docker container prune -f

# Remove unused images
docker image prune -f

4. Use Meaningful Names

# Good container names
docker run --name web-server nginx
docker run --name mysql-db mysql:8.0

# Avoid auto-generated names
docker run nginx  # Gets random name like "silly_einstein"

Summary

In this introduction, you learned:

Core Concepts

  • What Docker is and why it’s useful
  • Key differences between containers and virtual machines
  • Docker architecture and components
  • Container lifecycle and states

Practical Skills

  • Installing Docker on different platforms
  • Basic Docker commands for images and containers
  • Running web servers and databases in containers
  • Troubleshooting common issues

Best Practices

  • Using official images
  • Specifying image tags
  • Regular cleanup
  • Meaningful naming conventions

Key Takeaways:

  • Containers provide consistency across environments
  • Docker images are templates, containers are running instances
  • Always specify image tags for predictable deployments
  • Regular cleanup prevents disk space issues

Next, we’ll dive deeper into Docker images, learn how to create custom images with Dockerfiles, and explore image optimization techniques.