Docker 概念

镜像与容器的关系、分层文件系统、容器与虚拟机的差别。

Beginner
Key Points镜像是多层只读文件系统的叠加,容器在镜像之上加一个可写层;删掉容器,可写层随之丢弃,镜像不受影响。

镜像与容器

An image is the class, a container is the instance. One image can start any number of containers, each with its own writable layer, network and process space. Files written inside a container live only in that layer and vanish with it — persist data with volumes.

Text
镜像(只读,可共享)
├── layer 4  COPY app.jar
├── layer 3  RUN apt-get install -y openjdk-21-jre
├── layer 2  ENV LANG=C.UTF-8
└── layer 1  FROM ubuntu:24.04
容器 = 镜像 + 可写层(container layer)

分层与写时复制

Every RUN / COPY / ADD creates a layer keyed by a content hash, shared across machines and images. Reads hit the lower layers directly; a file is copied up to the writable layer only on first write (copy-on-write).

ConceptMeaningPractical effect
LayerOne instruction, one layerReordering Dockerfile changes cache hits
Copy-on-writeCopy up on first writeEditing a big file copies it whole
Immutable imageLayers never changeSame digest = same bytes, everywhere

容器 vs 虚拟机

ContainerVirtual Machine
IsolationProcess-level (namespaces)Hardware-level (hypervisor)
Guest OSNone — shares host kernelFull OS per VM
StartupMillisecondsTens of seconds
SizeMBGB
DensityDozens to hundreds per hostA few per host
Isolation strengthWeaker — kernel sharedStrong
Sharing the kernel means a kernel exploit escapes to the host. For untrusted workloads use a sandboxed runtime such as gVisor or Kata, or just use VMs.

命名空间与 cgroups

  • pid — 容器内看不到宿主机的其他进程
  • net — 独立的网卡、IP、端口空间
  • mnt — 独立的挂载点视图(rootfs)
  • uts / ipc / user — 主机名、进程间通信、UID 映射
  • cgroups — 限制 CPU、内存、IO,而不是隔离可见性
Bash
# 看容器内的进程号:容器里的 1 号进程在宿主机上是另一个 pid
docker run -d --name demo nginx
docker exec demo ps -ef          # 只有 nginx 相关进程
docker top demo                  # 从宿主机看,pid 不一样

Friends & Partners