CloudTadaInsights

Docker Fundamentals

Docker Fundamentals

Overview

Docker is the most popular container platform that has made containerization accessible to millions of developers worldwide. This article covers Docker fundamentals, including architecture, commands, and best practices for containerizing applications.

Docker Architecture

Docker Engine Components

Docker uses a client-server architecture with several key components:

Docker Client

The command-line interface (CLI) that allows users to communicate with the Docker daemon.

Docker Daemon (dockerd)

The background service that manages Docker objects such as images, containers, networks, and volumes.

Docker Objects

  • Images: Read-only templates used to create containers
  • Containers: Runnable instances of images
  • Networks: Allow containers to communicate
  • Volumes: Persist data beyond container lifecycles

Docker Architecture Diagram

TEXT
┌─────────────────┐    ┌──────────────────┐
│   Docker CLI    │────│  Docker Daemon   │
│     (Client)    │    │    (dockerd)     │
└─────────────────┘    └──────────────────┘
                              │
                       ┌──────────────────┐
                       │   Docker Objects │
                       │                  │
                       ├──────────────────┤
                       │ • Images         │
                       │ • Containers     │
                       │ • Networks       │
                       │ • Volumes        │
                       └──────────────────┘

Docker Images

What Are Docker Images?

Docker images are lightweight, standalone, executable packages that include everything needed to run a piece of software: code, runtime, libraries, environment variables, and configuration files.

Image Layers

Docker images use a layered filesystem where each layer represents a set of changes. This enables:

  • Efficiency: Layers are cached and reused
  • Speed: Only changed layers need to be rebuilt
  • Sharing: Multiple images can share common layers

Working with Images

Common Image Commands:

BASH
# List images
docker images

# Pull an image from registry
docker pull ubuntu:latest

# Remove an image
docker rmi image_name

# Build an image from Dockerfile
docker build -t myapp:latest .

# Tag an image
docker tag myapp:latest myapp:v1.0

Dockerfile Essentials

Dockerfile Instructions

A Dockerfile is a text document containing instructions to assemble a Docker image.

Key Instructions:

  • FROM: Sets the base image
  • LABEL: Adds metadata to the image
  • ENV: Sets environment variables
  • WORKDIR: Sets working directory
  • COPY: Copies files from host to container
  • ADD: Copies files with additional features
  • RUN: Executes commands during image build
  • CMD: Default command when container starts
  • ENTRYPOINT: Entry point for the container
  • EXPOSE: Documents ports to expose
  • VOLUME: Creates mount points

Sample Dockerfile for Node.js Application:

DOCKERFILE
# Use official Node.js runtime as base image
FROM node:18-alpine

# Set working directory in container
WORKDIR /app

# Copy package files
COPY package*.json ./

# Install dependencies
RUN npm ci --only=production

# Copy application code
COPY . .

# Expose port
EXPOSE 3000

# Define the command to run the application
CMD ["npm", "start"]

Multi-stage Builds

Multi-stage builds reduce image size by using multiple FROM statements:

DOCKERFILE
# Build stage
FROM node:18 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build

# Production stage
FROM node:18-alpine AS production
WORKDIR /app
COPY package*.json ./
RUN npm ci --only=production
COPY --from=builder /app/dist ./dist
EXPOSE 3000
CMD ["node", "dist/index.js"]

Docker Commands

Container Management

Running Containers:

BASH
# Run a container in detached mode
docker run -d --name mycontainer nginx

# Run with port mapping
docker run -p 8080:80 nginx

# Run with volume mounting
docker run -v /host/path:/container/path myapp

# Run and remove after exit
docker run --rm alpine echo "Hello World"

# Run interactively
docker run -it ubuntu bash

Container Lifecycle:

BASH
# Start a stopped container
docker start container_name

# Stop a running container
docker stop container_name

# Restart a container
docker restart container_name

# Pause and unpause containers
docker pause container_name
docker unpause container_name

Container Inspection:

BASH
# List running containers
docker ps

# List all containers (running and stopped)
docker ps -a

# Get detailed container information
docker inspect container_name

# View container logs
docker logs container_name

# Execute commands in running container
docker exec -it container_name bash

System Commands:

BASH
# View system-wide information
docker info

# Show disk usage
docker system df

# Clean up unused resources
docker system prune

# Clean up with more aggressive pruning
docker system prune -a

Docker Networking

Network Types

Docker provides several network drivers:

Bridge Network (Default)

  • Used for containers on the same host
  • Provides isolation between containers

Host Network

  • Removes network isolation
  • Uses host's network stack directly

None Network

  • Disables networking for the container

Overlay Network

  • Used for multi-host networking
  • Required for swarm services

Network Management:

BASH
# List networks
docker network ls

# Create a network
docker network create mynetwork

# Connect container to network
docker network connect mynetwork container_name

# Disconnect container from network
docker network disconnect mynetwork container_name

# Inspect network
docker network inspect mynetwork

Container Communication:

BASH
# Run container on specific network
docker run --network mynetwork myapp

# Link containers (legacy, use networks instead)
docker run --network mynetwork --name db_container mysql
docker run --network mynetwork --name app_container myapp

Docker Volumes

Volume Types

Named Volumes

Managed by Docker, stored in /var/lib/docker/volumes/

Anonymous Volumes

Also managed by Docker, but without explicit names

Bind Mounts

Mount host directory to container directory

tmpfs Mounts

Store data in host's memory only

Volume Management:

BASH
# List volumes
docker volume ls

# Create a volume
docker volume create myvolume

# Inspect volume
docker volume inspect myvolume

# Remove volume
docker volume rm myvolume

# Run container with named volume
docker run -v myvolume:/data myapp

# Run container with bind mount
docker run -v /host/path:/container/path myapp

Docker Compose

What is Docker Compose?

Docker Compose is a tool for defining and running multi-container Docker applications using YAML files.

Sample docker-compose.yml:

YAML
version: '3.8'

services:
  web:
    build: .
    ports:
      - "3000:3000"
    depends_on:
      - db
    environment:
      - DATABASE_URL=postgresql://user:password@db:5432/mydb
  
  db:
    image: postgres:13
    environment:
      POSTGRES_DB: mydb
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
    volumes:
      - postgres_data:/var/lib/postgresql/data
    ports:
      - "5432:5432"

volumes:
  postgres_data:

Docker Compose Commands:

BASH
# Start services
docker-compose up

# Start in detached mode
docker-compose up -d

# Stop services
docker-compose down

# View logs
docker-compose logs

# Scale services
docker-compose up --scale web=3

# Run one-time command
docker-compose run web bash

Docker Security

Security Best Practices

Image Security:

  • Use official base images when possible
  • Keep images updated
  • Scan images for vulnerabilities
  • Use minimal base images (alpine, distroless)

Runtime Security:

  • Run containers as non-root user
  • Use read-only root filesystem
  • Limit container capabilities
  • Use security profiles (AppArmor, SELinux)

Security Commands:

BASH
# Run as specific user
docker run --user 1000:1000 myapp

# Read-only root filesystem
docker run --read-only myapp

# Drop all capabilities
docker run --cap-drop=ALL myapp

# Add specific capability
docker run --cap-add=NET_ADMIN myapp

Docker Optimization

Image Optimization Techniques

Multi-stage Builds

Use separate build and runtime stages to reduce image size.

.dockerignore

Exclude unnecessary files from the build context:

TEXT
node_modules
npm-debug.log
.git
.gitignore
README.md
.env

Layer Caching

Order Dockerfile instructions to maximize layer caching:

DOCKERFILE
# Copy dependencies first (change less frequently)
COPY package*.json ./
RUN npm install

# Copy application code last (changes more frequently)
COPY . .

Performance Optimization

  • Use .dockerignore to reduce build context
  • Minimize number of layers
  • Clean up during build process
  • Use appropriate base images

Docker Registries

Public Registries

  • Docker Hub: Official public registry
  • GitHub Container Registry: Integrated with GitHub
  • Google Container Registry: Google Cloud's registry

Private Registries

  • Self-hosted solutions
  • Cloud provider registries (AWS ECR, Azure ACR, GCP GCR)

Working with Registries:

BASH
# Login to registry
docker login

# Tag image for registry
docker tag myapp:latest username/myapp:latest

# Push to registry
docker push username/myapp:latest

# Pull from registry
docker pull username/myapp:latest

Common Docker Patterns

Development Workflow

  1. Develop locally
  2. Create Dockerfile
  3. Build image
  4. Test locally
  5. Push to registry
  6. Deploy to production

CI/CD Integration

  • Automated builds triggered by commits
  • Automated testing in containers
  • Automated deployment to production

Troubleshooting Docker

Common Issues and Solutions

Container Won't Start

  • Check logs: docker logs container_name
  • Verify port conflicts: docker port container_name
  • Check resource limits

Slow Build Times

  • Use .dockerignore
  • Optimize layer caching
  • Use multi-stage builds

Network Issues

  • Check network connectivity
  • Verify port mappings
  • Test inter-container communication

Diagnostic Commands:

BASH
# View container stats
docker stats

# Show container processes
docker top container_name

# Copy files from container
docker cp container_name:/path/to/file ./local/path

# View system events
docker events

Best Practices

Dockerfile Best Practices

  • Use specific image tags (not latest)
  • Minimize number of layers
  • Clean up in same RUN instruction
  • Use multi-stage builds
  • Run containers as non-root

Container Management

  • Use meaningful names
  • Set resource limits
  • Implement health checks
  • Use labels for organization
  • Monitor container performance

Conclusion

Docker provides a powerful platform for containerizing applications, making them portable, efficient, and easy to manage. Mastering Docker fundamentals is essential for modern application development and deployment.

In the next article, we'll explore container orchestration with Kubernetes, covering how to manage containers at scale.

Share this article

You might also like

Browse all articles
Series

Virtual Networking with VMware

Comprehensive guide to VMware virtual networking, including vSwitches, port groups, VLANs, and network configuration best practices.

#VMware#Networking#vSwitch
Series

Introduction to Containers

An introduction to container technology, covering the fundamentals of containers, their benefits, and how they differ from traditional virtualization.

#Containers#Docker#Virtualization

Lecture 4: Memory

Introduction to memory management focusing on pointers, segmentation faults, dynamic memory allocation, stack, heap, buffer overflow, file I/O, and images.

#Pointers#Segmentation Faults#Dynamic Memory Allocation
Series

vCenter Server and Centralized Management

Complete guide to VMware vCenter Server and centralized management, covering installation, configuration, and management of VMware environments.

#VMware#vCenter Server#Centralized Management
Series

Storage Virtualization with VMware

Complete guide to VMware storage virtualization, including datastore types, storage protocols, and storage management strategies.

#VMware#Storage#Datastore