Skip to content

Docker Containerization

Mở đầu

"Trên máy tôi chạy được" = excuse kinh điển của dev, Docker xoá excuse này. Containerization pack app + mọi dependency thành unit standardized, đảm bảo chạy nhất quán mọi env. Foundation của software delivery hiện đại.

Bạn sẽ học:

  • Core concepts: image, container, registry
  • Architecture: container vs VM
  • Practical: Dockerfile + commands
  • Orchestration: Docker Compose multi-service
  • Best practice: image optimization, security
ChươngNội dung
1Sao cần container
2Core concepts
3Docker lifecycle
4Docker Compose
5Best practice

1. Sao cần container?

Trước container, deploy app phải manual cài runtime, config env var, handle dependency conflict. Khác biệt env (dev, staging, prod) = ổ chứa bug.

虚拟机 vs 容器
点击切换查看两种虚拟化方式的架构差异
应用 A / 应用 B / 应用 C
App A + Bins/Libs
App B + Bins/Libs
App C + Bins/Libs
Docker Engine
宿主操作系统(Host OS)
物理硬件
启动速度秒级
资源占用共享宿主 OS 内核(MB 级)
隔离性较强(进程级隔离)
密度单机可运行数百个容器
镜像大小MB 级

Container giải gì?

IssueTraditionalContainer
Env inconsistent"Tôi local chạy được"Pack mọi dependency, mọi nơi consistent
Dependency conflictApp A cần Node 14, B cần 18Mỗi container env riêng
Resource wasteMỗi VM 1 full OSShare kernel, MB overhead
Slow deployManual cài configdocker run 1 command
Scale khóTạo VM mới + cài env + deployContainer start trong giây

Container essence

Container không phải lightweight VM. Bản chất = process bị isolate. Linux kernel qua 2 mechanism implement container:

  • Namespace: isolate process view (PID, network, FS)
  • Cgroups: limit process resource (CPU, mem, IO)

Process trong container và process bình thường trên host không khác bản chất, chỉ "bị nhốt trong phòng không thấy bên ngoài".


2. Core concepts

3 concepts: Image, Container, Registry.

ConceptAnalogyNote
ImageClass / templateTemplate app read-only, chứa code, runtime, lib, config
ContainerInstance / objectImage running instance, R/W, có lifecycle riêng
RegistryApp storeService store + distribute image (Docker Hub, ACR, ECR)
DockerfileRecipe / blueprintText define build image thế nào
VolumeExternal diskPersist data, container xoá data không mất

Image layered structure

Docker image = nhiều layer read-only stack lên, mỗi Dockerfile instruction tạo 1 layer:

┌─────────────────────────┐
│  CMD ["node", "app.js"] │  ← Start command layer
├─────────────────────────┤
│  COPY . /app            │  ← App code layer (đổi thường xuyên)
├─────────────────────────┤
│  RUN npm install        │  ← Dependency layer (đôi khi đổi)
├─────────────────────────┤
│  FROM node:18-alpine    │  ← Base image layer (ít đổi)
└─────────────────────────┘

Sao layered quan trọng?

Docker cache mỗi layer. Layer không đổi → reuse cache. Dockerfile phải instruction đổi ít → trước, đổi nhiều → sau. Đa số build hit cache, nhanh hơn nhiều.


3. Docker lifecycle

Từ Dockerfile → container chạy = workflow.

Docker 生命周期
点击每个阶段查看详细说明
📝
编写 Dockerfile
🔨
构建镜像
☁️
推送仓库
▶️
运行容器
⚙️
管理容器
编写 Dockerfile
Dockerfile 是构建镜像的"配方",定义了从基础镜像开始,如何一步步构建出你的应用环境。每条指令创建一个镜像层(Layer),Docker 会缓存这些层以加速后续构建。
常用命令
FROM node:18-alpine指定基础镜像
WORKDIR /app设置工作目录
COPY package*.json ./复制依赖文件(利用缓存)
RUN npm install安装依赖
COPY . .复制应用代码
EXPOSE 3000声明端口
CMD ["node", "server.js"]启动命令

Dockerfile commands

CommandUseExample
FROMBase imageFROM node:18-alpine
WORKDIRSet working dirWORKDIR /app
COPYCopy file vào imageCOPY package.json ./
RUNExecute lúc buildRUN npm install
ENVEnv varENV NODE_ENV=production
EXPOSEDeclare port (doc)EXPOSE 3000
CMDStart commandCMD ["node", "app.js"]
ENTRYPOINTEntry point (khó override)ENTRYPOINT ["nginx"]

4. Docker Compose: multi-service orchestration

Project thật thường nhiều container: app + DB + Redis + Nginx. Docker Compose dùng YAML define + manage.

docker-compose.yml example

yaml
version: '3.8'
services:
  app:
    build: .
    ports:
      - "3000:3000"
    environment:
      - DB_HOST=db
      - REDIS_HOST=redis
    depends_on:
      - db
      - redis

  db:
    image: postgres:15-alpine
    volumes:
      - db-data:/var/lib/postgresql/data
    environment:
      - POSTGRES_PASSWORD=secret

  redis:
    image: redis:7-alpine

volumes:
  db-data:

Core concepts

ConceptNoteExample
servicesDefine container serviceapp, db, redis
volumesPersist data volumedb-data lưu DB file
networksCustom network (default auto tạo)Service gọi nhau qua tên
depends_onOrder dependencyapp depend db + redis
environmentEnv varDB password, connect URL

Service discovery

Trong Docker Compose, service name = hostname. App container gọi DB qua db:5432, Redis qua redis:6379, không cần biết IP. Docker built-in DNS.


5. Best practice

5.1 Multi-stage build

Optimize image size. Build stage cài tool + dependency, final stage chỉ giữ runtime.

dockerfile
# Build stage
FROM node:18-alpine AS builder
WORKDIR /app
COPY package*.json ./
RUN npm ci
COPY . .
RUN npm run build

# Run stage
FROM node:18-alpine
WORKDIR /app
COPY --from=builder /app/dist ./dist
COPY --from=builder /app/node_modules ./node_modules
EXPOSE 3000
CMD ["node", "dist/server.js"]

5.2 Image optimization

ItemCáchEffect
Small base imagealpine thay vì ubuntu200MB → 50MB
Combine RUNMulti command &&Giảm layer
.dockerignoreExclude node_modules, .gitFaster build, smaller context
Multi-stageTách build + runFinal không có build tool
Pin versionnode:18.17-alpine không node:latestBuild reproducible

5.3 Security

PracticeNote
Không run as rootUSER node non-root user
Vulnerability scandocker scout hoặc Trivy
Min permissionChỉ cài package cần, không debug tool
Đừng hardcode keyEnv var hoặc Docker Secret
Update base regularlyFix security vulnerability

Tổng kết

Docker = infrastructure cho software delivery hiện đại, must cho mọi dev.

  1. Container vs VM: container share kernel, lightweight, fast, isolation hơi kém VM
  2. Core 3: image (template), container (instance), registry (distribution)
  3. Dockerfile: layered build, leverage cache, ít đổi trước
  4. Compose: YAML define multi-service, service name = hostname
  5. Production: multi-stage build, alpine base, non-root

2026 cho VN dev

  • Modern container tooling 2026:
    • Podman: rootless alternative Docker
    • Buildah: build without daemon
    • nerdctl: containerd CLI
    • Lima: chạy Linux container trên macOS (thay Docker Desktop)
  • VN context:
    • Startup → Docker Compose đủ cho mid-size
    • Enterprise → Docker + K8s
    • VN banking → Docker compliance + private registry
  • AI scenario: Dockerfile cho LLM inference (PyTorch + CUDA), multi-stage để image nhỏ
  • Trends: distroless image (Google), security scanning trong CI (Snyk, Trivy)

Tài liệu