Docker Notes
T

容器和虚拟机

container_vs_vm

容器不是 Mini 虚拟机

  • 容器其实是进程 Containers are just processes
  • 容器中的进程被限制了对 CPU 内存等资源的访问
  • 当进程停止后,容器就退出了
虚拟机容器
虚拟机容器

容器的进程 process

因 Windows 环境下的 Docker 和 Linux 具有一些差异,以下是在 Ubuntu 20.04.3 LTS 中演示。pstree 命令需要额外安装,可以使用 yum/dnf install psmisc 或者 sudo apt install psmisc 安装。

container-vs-vm-container-process

  • docker container top [container-id or container-name]: 显示容器运行了哪些进程。
    • nginx 主进程:进程 PID 为 19438,父进程 PPID 为 19416.
    • ndinx 子进程:进程 PID 为 19494,父进程 PPID 为 19438.
  • ps -aux | grep nginx: 查看本机 nginx 进程信息。
  • pstree: 查看进程关系。containerd-shim 是 containerd 的一个组件,主要是用于剥离 containerd 守护进程与容器进程。containerd 通过 shim 调用 runc 的包函数来启动容器。引入 shim,允许 runc 在创建和运行容器之后退出,并将 shim 作为容器的父进程,而不是 containerd 作为父进程,这样做的目的是当 containerd 进程挂掉,由于 shim 还正常运行,因此可以保证容器不受影响。此外,shim 也可以收集和报告容器的退出状态,不需要 containerd 来 wait 容器进程。

注意,我们在容器中看到的进程 PID 和在主机上看到的进程 PID 是不一样的。

$ docker container run -it busybox sh
Unable to find image 'busybox:latest' locally
latest: Pulling from library/busybox
5cc84ad355aa: Pull complete
Digest: sha256:5acba83a746c7608ed544dc1533b87c737a0b0fb730301639a0179f9344b1678
Status: Downloaded newer image for busybox:latest
/ # ps
PID   USER     TIME  COMMAND
    1 root      0:00 sh
    7 root      0:00 ps
/ #

容器内进程 PID 为 1。

$ docker container ls -a
CONTAINER ID   IMAGE     COMMAND   CREATED          STATUS          PORTS     NAMES
be0e5378cc6f   busybox   "sh"      10 seconds ago   Up 10 seconds             adoring_yonath

$ docker container top be0e5378cc6f
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                21856               21828               0                   23:14               pts/0               00:00:00            sh

$ pstree -halps 21856
systemd,1
  └─containerd-shim,21828 -namespace moby -id be0e5378cc6ff74d371c83a5f62e45133685f974671e7ad54fdfec044cca2295 -address /run/containerd/containerd.sock
      └─sh,21856

$ ps -ef | grep 21828 | grep -v grep
root       21828       1  0 23:14 ?        00:00:00 /usr/bin/containerd-shim-runc-v2 -namespace moby -id be0e5378cc6ff74d371c83a5f62e45133685f974671e7ad54fdfec044cca2295 -address /run/containerd/containerd.sock
root       21856   21828  0 23:14 pts/0    00:00:00 sh

主机内进程 PID 为 21856。

Show Graph Visualisation