Docker¶
Docker packages applications into containers — lightweight, isolated environments with everything needed to run (code, runtime, libraries). Key concepts: Image (blueprint, built from Dockerfile), Container (running instance of image), Docker Compose (multi-container orchestration). Containers share the host OS kernel (unlike VMs). Benefits: consistency across environments, fast startup, easy scaling.
Key Concepts¶
Deep Dive: Docker vs VMs
VM: Docker:
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ App A │ │ App B │ │ App A │ │ App B │
├──────────┤ ├──────────┤ ├──────────┤ ├──────────┤
│ Guest OS │ │ Guest OS │ │ Bins/ │ │ Bins/ │
├──────────┤ ├──────────┤ │ Libs │ │ Libs │
│ Hypervisor │ ├──────────┴─┴──────────┤
│ │ │ Docker Engine │
├──────────────────────────┤ ├────────────────────────┤
│ Host OS │ │ Host OS │
└──────────────────────────┘ └────────────────────────┘
| Feature | VM | Container |
|---|---|---|
| Size | GBs | MBs |
| Startup | Minutes | Seconds |
| Isolation | Full OS | Process-level |
| Performance | Overhead | Near-native |
Deep Dive: Dockerfile
# Multi-stage build for Java Spring Boot
FROM eclipse-temurin:21-jdk AS builder
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn clean package -DskipTests
FROM eclipse-temurin:21-jre
WORKDIR /app
COPY --from=builder /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java", "-jar", "app.jar"]
Key instructions:
| Instruction | Purpose |
|-------------|---------|
| FROM | Base image |
| WORKDIR | Set working directory |
| COPY / ADD | Copy files into image |
| RUN | Execute command during build |
| EXPOSE | Document port (doesn't publish) |
| ENTRYPOINT | Command to run on container start |
| CMD | Default args for ENTRYPOINT |
| ENV | Set environment variable |
Deep Dive: Docker Compose
version: '3.8'
services:
app:
build: .
ports:
- "8080:8080"
environment:
- SPRING_PROFILES_ACTIVE=prod
- DB_HOST=postgres
depends_on:
- postgres
- redis
postgres:
image: postgres:15
environment:
POSTGRES_DB: mydb
POSTGRES_PASSWORD: secret
volumes:
- pg_data:/var/lib/postgresql/data
redis:
image: redis:7-alpine
ports:
- "6379:6379"
volumes:
pg_data:
Commands: docker compose up -d, docker compose down, docker compose logs
Deep Dive: Best Practices
- Use multi-stage builds to reduce image size
- Use
.dockerignoreto exclude unnecessary files - Don't run as root — use
USERinstruction - Pin versions —
FROM node:18.17notFROM node:latest - Minimize layers — combine RUN commands
- Use health checks —
HEALTHCHECK CMD curl -f http://localhost:8080/actuator/health
Common Interview Questions
- What is Docker? How is it different from a VM?
- What is a Dockerfile? Explain key instructions.
- What is Docker Compose? When would you use it?
- What is a multi-stage build? Why use it?
- What is the difference between CMD and ENTRYPOINT?
- How do you persist data in Docker?
- What is a Docker volume?
- How do containers communicate with each other?