devHọc Dev

Week 1 - Day 1: Why Docker, Installation, and Basic Commands

Week 1 – Day 1

This lesson combines 2 topics: Why Docker? and Installing Docker and Basic Commands.

Learning Objectives

  • Understand the problem Docker solves (the "works on my machine" problem)
  • Distinguish containers from virtual machines (VMs)
  • Know Docker's history and its place in the cloud ecosystem
  • Understand Docker's role on AWS (ECS, EKS, Fargate) and when to choose containers vs serverless
  • Install Docker Desktop on Mac/Windows or Docker Engine on Linux
  • Master the container lifecycle: run, stop, rm
  • Distinguish images from containers
  • Know how to view logs and exec into a running container
  • Understand how pulling from a public registry (Docker Hub) works

Part 1: Why Docker?

1. The problem before Docker

"It works on my machine"

Before Docker, development teams often ran into this problem:

DevlaptopStagingserverProduction───────────────────────────────────────Python3.9Python3.7Python3.11libpq12libpq10libpq14OpenSSL1.1OpenSSL1.0OpenSSL3.0Ubuntu22.04CentOS7AmazonLinux2

The result: the app runs fine on the laptop but crashes on the server because of a dependency mismatch.

The traditional solution: Virtual Machines

┌────────────────────────────────────┐│VMHost(baremetal)││┌───────────┐┌───────────┐│││VM1││VM2││││┌───────┐││┌───────┐│││││App││││App│││││├───────┤││├───────┤│││││OS││││OS││││││(4GB)││││(4GB)│││││└───────┘││└───────┘│││└───────────┘└───────────┘││┌──────────────────────────────┐│││Hypervisor(VMware/KVM)│││└──────────────────────────────┘││┌──────────────────────────────┐│││HostOS(Linux/Windows)│││└──────────────────────────────┘│└────────────────────────────────────┘

VMs solve isolation but at a high cost: each VM needs its own OS (~GB), boot time is slow (~minutes), and they add RAM/CPU overhead.

2. What is a container?

Container architecture

┌──────────────────────────────────────┐│ContainerHost││┌──────────┐┌──────────┐│││AppA││AppB││││+libsA││+libsB││││(~50MB)││(~80MB)│││└──────────┘└──────────┘││┌────────────────────────────────┐│││ContainerRuntime(Docker)│││└────────────────────────────────┘││┌────────────────────────────────┐│││HostOSKernel(shared)│││└────────────────────────────────┘│└──────────────────────────────────────┘

Containers share the host OS kernel (through Linux namespaces + cgroups) and package only the app + its dependencies. The result:

  • Start in milliseconds (no OS boot)
  • Small footprint (~MB instead of ~GB)
  • Higher density: one server can run 100 containers instead of 10 VMs

Container vs VM comparison

CriteriaContainerVirtual Machine
Boot timeMillisecondsMinutes
Image sizeMBGB
OSShares the host kernelSeparate OS
IsolationProcess-level (namespace)Hardware-level (hypervisor)
OverheadVery lowHigh
PortabilityHigh (image includes deps)Medium
Security boundaryWeaker than a VMStronger than a container
Use caseMicroservices, CI/CDLegacy apps, strong isolation

When do you still use VMs? When you need a different kernel from the host (a Windows app on a Linux host), when the workload needs hard security isolation (financial, multi-tenant), or for stateful legacy apps that cannot be containerized.

3. Docker history

  • 2008: LXC (Linux Containers) — containers appear but are hard to use
  • 2013: Docker, Inc. launches Docker Engine — a friendly wrapper on top of LXC, later switched to runc
  • 2014: Docker Hub launches — a public registry for images
  • 2015: Docker Compose and Docker Swarm launch
  • 2016: OCI (Open Container Initiative) — standardizes the container runtime/image format
  • 2017-2020: Kubernetes dominates, replacing Docker Swarm as the standard for orchestration
  • 2021: Kubernetes drops dockershim and uses containerd/CRI-O directly
  • 2022: Docker Desktop changes its pricing — free for personal use/small teams (<250 employees, <$10M revenue), paid for enterprises
  • 2023-2024: BuildKit becomes the default in Docker Engine; multi-arch builds with docker buildx become standard

Docker Desktop vs Docker Engine

ComponentDocker DesktopDocker Engine
PlatformMac, WindowsLinux
GUIYesNo
LicenseFree/paidApache 2.0, free
VM layerYes (Linux VM on Mac/Win)Not needed
Used forDev laptopServer/CI

4. Docker in the AWS ecosystem

┌─────────────────────────────────────────────────────────┐│AWSContainerServices││││RegistryOrchestrationCompute││┌───────┐┌────────────────┐┌──────────────────┐│││ECR││ECS││EC2instances│││││──▶│(Elastic│──▶│(youmanageOS)││││Amazon││ContainerSvc)│└──────────────────┘│││ECR│└────────────────┘││││┌────────────────┐┌──────────────────┐││││──▶│EKS│──▶│Fargate│││└───────┘│(Elastic││(serverless││││Kubernetes)││compute—no│││└────────────────┘│EC2tomanage)│││└──────────────────┘││││*ECSandEKScanbothrunonEC2ORFargate││(thearrowsabovearejustcommonpairings)│└─────────────────────────────────────────────────────────┘
ServiceDescriptionWhen to use
Amazon ECRPrivate/public Docker registryStore your images before deploying
Amazon ECSAWS-native container orchestrationSmall teams that don't want to learn Kubernetes
Amazon EKSManaged KubernetesNeed the Kubernetes ecosystem, large scale
AWS FargateServerless compute for ECS/EKSDon't want to manage EC2, variable load

Container vs Serverless (Lambda) trade-off

CriteriaContainer (Fargate/ECS)Lambda
Starting a new task/function~30 seconds to a few minutes (provision ENI + pull image; an already-running service has no cold start)Cold start ~100ms-1s (depends on language)
Max runtimeUnlimited15 minutes
Memory0.5 GB - 120 GB128 MB - 10 GB
Custom runtimeAny OS/languageYes (custom runtime layer)
Persistent stateVolume, EFS mountNo (stateless)
Cost modelPer vCPU/GB-hourPer invocation count + GB-s
Best forLong-running, stateful, web serverEvent-driven, short bursts, scheduled

Exam keyword awareness: "least operational overhead" + long-running web app → Fargate. "Event-driven, occasional spikes" → Lambda.

5. Docker Architecture

┌──────────────────────────────────────────────────┐│DockerHost││││DockerCLI────DockerDaemon(dockerd)││││││dockerbuild┌────────────────────┐││dockerrun│containerd│││dockerpush│(containermgmt)│││└────────────────────┘│││││┌────────────────┐│││runc││││(OCIruntime)│││└────────────────┘│└──────────────────────────────────────────────────┘│DockerHub/ECR/GHCR(registries)

Core concepts

  • Image: A read-only template made of multiple layers, built from a Dockerfile
  • Container: A running instance of an image (image + writable layer)
  • Registry: Where images are stored and distributed (Docker Hub, ECR, GHCR)
  • Dockerfile: A file that describes how to build an image
  • Layer: Each instruction in a Dockerfile creates a layer; layers are cached and reused

Part 2: Installing Docker and Basic Commands

1. Installing Docker

macOS

# Option 1: download Docker Desktop from the official site
# https://docs.docker.com/desktop/install/mac-install/
# There are Intel and Apple Silicon (M1/M2/M3/M4) builds — pick the one for your chip

# Option 2: use Homebrew (recommended)
brew install --cask docker

# After installing, open the Docker Desktop app and wait for the daemon to start
docker --version
# Docker version 2x.x.x (any recent version)

Windows

# Requirement: WSL2 enabled (Windows 10/11)
# Download Docker Desktop: https://docs.docker.com/desktop/install/windows-install/

# Or use winget
winget install Docker.DockerDesktop

# Verify
docker --version

Linux (Ubuntu/Debian)

# Add the official Docker apt repo (don't use apt install docker.io — it's an old version)
curl -fsSL https://get.docker.com | sh

# Add the current user to the docker group (so you don't have to type sudo every time)
sudo usermod -aG docker $USER
newgrp docker   # or log out and log back in

# Enable the Docker service
sudo systemctl enable --now docker

# Verify
docker --version
docker run hello-world

Verify the installation

docker --version      # Docker version 2x.x.x (any recent version)
docker info           # daemon info, storage driver, runtime
docker run hello-world # test pulling an image and running a simple container

2. Image vs Container

The core distinction

┌──────────────────────────────────────────────────┐│Image(read-onlytemplate)││─────────────────────────────││Layer3:Appcode(COPY)││Layer2:Node.js24(RUNaptinstallnodejs)││Layer1:Ubuntu22.04(FROMubuntu:22.04)│└────────────────────────┬─────────────────────────┘│dockerrun▼┌──────────────────────────────────────────────────┐│Container(image+writablelayer)││─────────────────────────────────││Writablelayer:logs,tempfiles,state││──────────────(lostwhencontainerisremoved)││[Imagelayersunderneath—read-only]│└──────────────────────────────────────────────────┘
  • One image can create many containers at the same time
  • Each container has its own writable layer — by default, data written inside a container is lost when the container is removed
  • Use a volume to persist data (covered in Day 2, Part 2)

3. Basic commands — the container lifecycle

Pull an image from a registry

# Pull an image from Docker Hub (the default)
docker pull nginx:1.27
docker pull ubuntu:22.04
docker pull node:24-alpine

# Pull from Amazon ECR Public
docker pull public.ecr.aws/nginx/nginx:1.27

# List the images you have pulled
docker images
# REPOSITORY   TAG        IMAGE ID       CREATED       SIZE
# nginx        1.27       abc123def456   2 days ago    188MB
# ubuntu       22.04      def456ghi789   3 weeks ago   77.9MB
# node         20-alpine  ghi789jkl012   1 week ago    135MB

Run a container

# Run in the foreground (attached) — takes over the terminal, Ctrl+C to stop
docker run nginx:1.27

# Run in the background (detached)
docker run -d nginx:1.27

# Name the container
docker run -d --name my-nginx nginx:1.27

# Map port host:container
docker run -d -p 8080:80 --name my-nginx nginx:1.27
# Open: http://localhost:8080

# Run interactively (interactive + tty)
docker run -it ubuntu:22.04 bash

# Automatically remove the container after it exits
docker run --rm ubuntu:22.04 echo "hello"

# Set environment variables
docker run -d \
  -e MYSQL_ROOT_PASSWORD=secret \
  -e MYSQL_DATABASE=mydb \
  --name my-mysql \
  mysql:8.0

# Mount a volume (host path:container path)
docker run -d \
  -p 8080:80 \
  -v /home/user/html:/usr/share/nginx/html:ro \
  --name my-nginx \
  nginx:1.27

List running containers

# Only running containers
docker ps
# CONTAINER ID   IMAGE        COMMAND       CREATED       STATUS        PORTS                  NAMES
# a1b2c3d4e5f6   nginx:1.27   "/docker-…"   2 mins ago    Up 2 minutes  0.0.0.0:8080->80/tcp   my-nginx

# All containers (including stopped ones)
docker ps -a

# Only container IDs
docker ps -q

Stop, Start, Restart

# Graceful stop (SIGTERM → wait 10s → SIGKILL)
docker stop my-nginx

# Stop immediately (SIGKILL)
docker kill my-nginx

# Start a stopped container again
docker start my-nginx

# Restart
docker restart my-nginx

View logs

# View all logs
docker logs my-nginx

# Follow logs (like tail -f)
docker logs -f my-nginx

# Last 50 lines
docker logs --tail 50 my-nginx

# Logs with timestamps
docker logs -t my-nginx

# Filter by time
docker logs --since 5m my-nginx     # last 5 minutes
docker logs --since 2024-01-01 my-nginx

Exec into a running container

# Open a bash shell inside a running container
docker exec -it my-nginx bash

# Run a single command
docker exec my-nginx nginx -t       # test nginx config
docker exec my-nginx cat /etc/nginx/nginx.conf

# Run as a different user
docker exec -it -u root my-nginx bash

Remove containers and images

# Remove a stopped container
docker rm my-nginx

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

# Remove all stopped containers
docker container prune

# Remove an image
docker rmi nginx:1.27

# Remove all unused images, containers, networks, and build cache
docker system prune -a
# Careful: this command removes quite a lot

4. Inspect and Stats

# View a container's detailed configuration (JSON output)
docker inspect my-nginx

# Get only the container's IP address
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' my-nginx

# View CPU/RAM usage in real time
docker stats
docker stats my-nginx   # a single container only

# View port mappings
docker port my-nginx

# Copy files between the host and a container
docker cp my-nginx:/etc/nginx/nginx.conf ./nginx.conf   # container → host
docker cp ./index.html my-nginx:/usr/share/nginx/html/  # host → container

5. Understanding registries and image tags

dockerpullnginx:1.27│││││└──Tag(version;"latest"ifomitted)│└───────Repositoryname└──────────────Registry(docker.iobydefault)dockerpullpublic.ecr.aws/nginx/nginx:1.27│││││││└──Tag││└───────Repository│└─────────────Namespace└──────────────────────────────Registry(ECRPublic)

Best practice: Always pin a specific tag (:1.27) instead of :latest in production — :latest changes when the image is updated and can break things.

6. Docker Hub quick tour

# Search for images on Docker Hub
docker search nginx
docker search --filter is-official=true ubuntu

# Log in to Docker Hub (needed to push private images)
docker login
# Username: your-dockerhub-username
# Password: your-password

# Logout
docker logout

Review Questions

  1. What is the most fundamental difference between a container and a VM with respect to the OS kernel?

    Show answer

    A container shares the host OS kernel through Linux namespaces and cgroups — it has no kernel of its own. A VM has a hypervisor that creates its own virtualized hardware, and each VM runs a full OS with its own kernel.

    Consequence: containers are lighter (~MB vs ~GB) and start faster (ms vs minutes), but their isolation is weaker than a VM's because they share the host kernel.

  2. Why do containers start significantly faster than VMs?

    Show answer

    A VM has to boot a full OS (load the kernel, init system, services), which takes from tens of seconds to several minutes. A container only needs to start a new process in an existing namespace — no OS boot — so it starts in milliseconds.

  3. When should you choose Fargate over Lambda for a web API?

    Show answer

    Choose Fargate when: (1) requests take longer than 15 minutes to process, (2) you need persistent connections (WebSocket, gRPC), (3) the app needs more than 10 GB of memory, (4) you need a custom runtime or OS-level dependencies, (5) the workload is steady-state (Lambda cold starts hurt UX).

    Choose Lambda when: the workload is event-driven, short bursts, with no need for a continuously running server — to reduce cost and operational overhead.

  4. How do ECR, ECS, and Fargate work together in a deployment?

    Show answer

    ECR is the private registry that stores the Docker image after you docker push. ECS is the orchestration layer: you define a Task Definition that references the image URI in ECR, then create an ECS Service with a desired count. Fargate is the compute layer — ECS has Fargate pull the image from ECR and run the container without you managing any EC2 instances.

    Flow: docker push → ECR → ECS Task Definition (image=ECR URI) → ECS Service → Fargate pulls & runs.

  5. Under Docker's current licensing policy, when is Docker Desktop free?

    Show answer

    Docker Desktop is free for: individuals (personal use), education, non-commercial research, and businesses with fewer than 250 employees AND less than $10 million USD in annual revenue. If a company exceeds either threshold, it needs a paid subscription.

    Docker Engine (the CLI on Linux, no GUI) is always free under Apache 2.0.

  6. Which command shows all containers (including stopped ones)?

    Show answer

    docker ps -a (or docker container ls -a). The -a / --all flag shows all containers, including those in the exited, created, and paused states. Without -a, only running containers are shown.

  7. What is the difference between docker stop and docker kill?

    Show answer

    docker stop sends a SIGTERM signal to PID 1 in the container and waits up to 10 seconds (configurable with --time) for the process to clean up, then sends SIGKILL if it still hasn't exited. docker kill sends SIGKILL immediately (or a custom signal), without waiting.

    Use docker stop for graceful shutdown; use docker kill when the container is hung and does not respond to SIGTERM.

  8. Which docker run flag makes the container remove itself after it exits?

    Show answer

    The --rm flag. Example: docker run --rm ubuntu:22.04 echo "hello" — the container is removed as soon as the process ends. Useful for one-shot commands, testing, or CI jobs to avoid piling up leftover containers.

  9. Why shouldn't you use the :latest tag in production?

    Show answer

    The :latest tag is mutable — when a new image is pushed to the registry, :latest points to the new image. Redeploying the same :latest tag can pull a different image than the previous deployment, causing inconsistency across servers or making a correct rollback impossible. Use a specific tag such as :1.2.3 or :sha256-abc123 to ensure reproducible deployments.

  10. What happens to data written to a container without a volume when the container is removed?

Show answer

The data is lost permanently. A container has a writable layer on top of the (read-only) image layers. When the container is removed (docker rm), the writable layer is removed with it. To persist data, use a named volume (-v mydata:/path) or a bind mount (-v /host/path:/container/path).

Hands-on Exercises

Part 1: Why Docker?

# Check whether Docker is installed
docker --version
docker info

# Pull and run your first container
docker run hello-world

# Run an Ubuntu container interactively
docker run -it ubuntu:22.04 bash

# Inside the container:
cat /etc/os-release
ps aux       # you only see processes inside the container
exit

# Compare: the container is gone
docker ps    # no containers running anymore
docker ps -a # but it still exists in the exited state

Part 2: Installing Docker and Basic Commands

# 1. Run nginx, map port 8080, name it "web"
docker run -d -p 8080:80 --name web nginx:1.27
curl http://localhost:8080   # or open a browser

# 2. View nginx logs
docker logs web
docker logs -f web     # Ctrl+C to exit

# 3. Exec into the container and check processes
docker exec -it web bash
ps aux
ls /usr/share/nginx/html
exit

# 4. Stop and remove
docker stop web
docker rm web

# 5. Run MySQL with env vars
docker run -d \
  --name mydb \
  -e MYSQL_ROOT_PASSWORD=secret123 \
  -e MYSQL_DATABASE=testdb \
  -p 3306:3306 \
  mysql:8.0

# Check that it is running
docker ps
docker logs mydb

# Connect to mysql (if you have the mysql client installed)
mysql -h 127.0.0.1 -P 3306 -u root -psecret123 testdb

# Clean up
docker rm -f mydb

References


Next lesson →