🔖 #docker #原生雲

[!AI] 本文摘要
這篇文章探討了Docker環境的設置和指令操作,回顧了Docker的背景與重要性,介紹了系統需求和安裝步驟,解釋了鏡像、容器和倉庫等核心概念,並詳細說明了各種Docker指令的使用方法和示例。此外,文章還分享了一個簡單的Docker應用案例,鼓勵大家在本地環境中練習使用Java微服務和Docker,整體為希望深入了解Docker的使用者提供了全面的指導。


以下是針對「Docker環境建置、指令操作介紹」的30分鐘演講大綱,假設使用者已經具備Docker的基本知識:

1. 引言 (3分鐘)

簡要回顧Docker的背景與重要性

Docker 是 Docker Inc 公司開源的一項基於 Ubuntu LXC 技術之上構建的應用打包運行時引擎,源代碼託管在 GitHub 上,完全基於 Go 語言開發並遵守 Apache License 2.0 協議開源。 Docker 在2014年6月召開的 DockerCon 2014 技術大會上,吸引了 IBM、Google、RedHat 等業界知名公司的關注和技術支持。無論是從 GitHub 上的代碼活躍度,還是開源巨頭紅帽宣佈在 RHEL7 中正式支持 Docker 技術,都可以説明 Docker 技術是一項創新型的技術解決方案,就連 Google 公司的 Compute Engine 也很快支持 Docker 在其之上運行。

200-AREA/風清雲談/POST/1. 軟體工程/架構/原生雲/attachments/Pasted image 20250320102153.png

容器化技術的優勢

Docker 技術解決以下問題:

複雜的環境配置管理:從各種 OS 環境到各種中間件環境以及各種應用環境。

在軟體產業中任何應用要做到成功發佈,開發團隊需要關心的東西太多且難於統一管理,這個問題普遍存在並需要直接面對。Docker 技術旨在簡化部署多種應用實例環境依賴,如 Web 應用、後端應用、資料庫應用、大數據應用(例如Hadoop集羣)、消息隊列(例如Kafka)等等都可以打包成一個鏡像部署。

雲計算時代的到來:AWS 的成功,引導開發者將應用轉移到雲上,解決了硬體管理的問題,然而軟體配置和管理相關的問題依然存在。Docker 的出現正好能幫助軟體開發者開闊思路,嘗試新的軟體管理方法來解決這個問題。

虛擬化手段的變化:雲時代採用標配硬體來降低成本,採用虛擬化手段來滿足用户按需分配的資源需求以及保證可用性和隔離性。然而無論是 KVM 還是 Xen,在 Docker 看來都在浪費資源,因為用户需要的是高效運行環境而非 OS,GuestOS 既浪費資源又難於管理,輕量級的 LXC 更加靈活和快速。
200-AREA/風清雲談/POST/1. 軟體工程/架構/原生雲/attachments/Pasted image 20250320102249.png

2. Docker環境建置 (7分鐘)

系統需求與相容性

Docker 是跨平台的解決方案,它支持在當前主流的各大平台安裝,包括 Ubuntu、RHEL、CentOS、Debian 等 Linux 發行版,同時也可以在 OSX 、Microsoft Windows 等非 Linux 平台下安裝使用。

200-AREA/風清雲談/POST/1. 軟體工程/架構/原生雲/attachments/Pasted image 20250320101632.png

因為 Linux 是 Docker 的原生支持平台,所以推薦在 Linux 上使用 Docker。由於生產環境中追求企業其穩定性,因此我們使用 Rocky Linux 這個平台來安裝和使用 Docker 的介紹。

[!quote] CentOS Linux所有版本已全部停止維護
CentOS 7 在 2024 年中停止了傳統的支援,並轉向了 CentOS Stream,這是一個滾動更新的版本,與 Red Hat Enterprise Linux(RHEL)更緊密地集成。這意味著 CentOS Stream 將會持續接收更新,但不再是傳統意義上的穩定版本。

[!quote] Rocky Linux
由 CentOS 的創始人之一創建,旨在成為 CentOS 的直接替代品,提供與 RHEL 相同的穩定性和兼容性。

操作系統要求

卸載已有 Docker

如果你已經安裝過舊版的 Docker,可以先執行以下命令卸載舊版 Docker。

Rocky Linux

# 停止 Docker 服務
$ sudo sudo systemctl stop docker
# 卸載 Docker 及其相關套件
$ sudo yum remove docker-ce docker-ce-cli containerd.io
#(可選)刪除所有 Docker 資料
$ sudo rm -rf /var/lib/docker

安裝 Docke

首次安裝 Docker 之前,需要添加 Docker 安裝源。添加之後,我們就可以從已經配置好的源,安裝和更新 Docker。添加 Docker 安裝源的命令如下:

# 添加Docker Repo
$ sudo dnf config-manager --add-repo=https://download.docker.com/linux/centos/docker-ce.repo

正常情況下,直接安裝最新版本的 Docker 即可,因為最新版本的 Docker 有着更好的穩定性和安全性。你可以使用以下命令安裝最新版本的 Docker。cl

# 在安裝Docker CE 的時候,會同步安裝 docker-compose-plugin 套件
$ sudo dnf install -y docker-ce
# 建議添加一般用戶至Docker群組,並以一般用戶運行Docker
$ sudo usermod -aG docker $USER
# 立即生效用戶變更配置
$ sudo newgrp docker

如果你想要安裝指定版本的 Docker,可以使用以下命令:

$ yum list docker-ce --showduplicates | sort -r
docker-ce.aarch64               3:28.0.1-1.el9                 docker-ce-stable 
docker-ce.aarch64               3:28.0.1-1.el9                 @docker-ce-stable
docker-ce.aarch64               3:28.0.0-1.el9                 docker-ce-stable 
docker-ce.aarch64               3:27.5.1-1.el9                 docker-ce-stable 
docker-ce.aarch64               3:27.5.0-1.el9                 docker-ce-stable 
docker-ce.aarch64               3:27.4.1-1.el9                 docker-ce-stable 
docker-ce.aarch64               3:27.4.0-1.el9                 docker-ce-stable
...

然後選取想要的版本執行以下命令:

# sudo yum install docker-ce-<VERSION_STRING> docker-ce-cli-<VERSION_STRING> containerd.io
$ sudo yum install docker-ce-28.0.1-1.el9 docker-ce-cli-28.0.1-1.el9 containerd.io

安裝完成後,使用以下命令啓動 Docker。

$ sudo systemctl start docker

測試啟動 hello world 容器

這裏有一個國際慣例,安裝完成後,我們需要使用以下命令啓動一個 hello world 的容器。

$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
0e03bdcc26d7: Pull complete
Digest: sha256:7f0a9f93b4aa3022c3a4c147a449bf11e0941a1fd0bf4a8e6c9408b2600777c5
Status: Downloaded newer image for hello-world:latest
Hello from Docker!

運行上述命令,Docker 首先會檢查本地是否有hello-world這個鏡像,如果發現本地沒有這個鏡像,Docker 就會去 Docker Hub 官方倉庫下載此鏡像,然後運行它。最後我們看到該鏡像輸出 “Hello from Docker!” 並退出。

[!tip] Title
安裝完成後默認 docker 命令只能以 root 用户執行,如果想允許普通用户執行 docker 命令,需要執行以下命令 sudo groupadd docker && sudo gpasswd -a ${USER} docker && sudo systemctl restart docker ,執行完命令後,退出當前命令行窗口並打開新的窗口即可。


3. Docker基本概念回顧

核心概念:鏡像(Image)容器(Container)、倉庫(Repository),Docker 架構核心設計理念

Docker 核心概念

200-AREA/風清雲談/POST/1. 軟體工程/架構/原生雲/attachments/Pasted image 20250320101806.png

鏡像

鏡像是什麼呢?通俗地講,它是一個只讀的文件和文件夾組合。它包含了容器運行時所需要的所有基礎文件和配置信息,是容器啓動的基礎。所以你想啓動一個容器,那首先必須要有一個鏡像。鏡像是 Docker 容器啓動的先決條件。

如果你想要使用一個鏡像,可以用這兩種方式:

  1. 自己創建鏡像。通常情況下,一個鏡像是基於一個基礎鏡像構建的,你可以在基礎鏡像上添加一些用户自定義的內容。例如你可以基於centos鏡像製作你自己的業務鏡像,首先安裝nginx服務,然後部署你的應用程序,最後做一些自定義配置,這樣一個業務鏡像就做好了。
  2. 從功能鏡像倉庫拉取別人製作好的鏡像。一些常用的軟體或者系統都會有官方已經制作好的鏡像,例如nginxubuntucentosmysql等,你可以到 Docker Hub 搜索並下載它們。
容器

容器是什麼呢?容器是 Docker 的另一個核心概念。通俗地講,容器是鏡像的運行實體。鏡像是靜態的只讀文件,而容器帶有運行時需要的可寫文件層,並且容器中的進程屬於運行狀態。即容器運行着真正的應用進程。容器有初建、運行、停止、暫停和刪除五種狀態。

雖然容器的本質是主機上運行的一個進程,但是容器有自己獨立的命名空間隔離和資源限制。也就是説,在容器內部,無法看到主機上的進程、環境變量、網絡等信息,這是容器與直接運行在主機上進程的本質區別。

倉庫

倉庫是用來存儲和分發 Docker 鏡像的地方。它可以是公共的(如 Docker Hub),任何人都可以訪問,也可以是私有的,僅限特定用戶使用。倉庫支持鏡像的版本管理,用戶可以推送和拉取鏡像,並且許多倉庫提供安全掃描功能,以檢查鏡像中的漏洞。

私有倉庫是專為特定用戶或團隊設計的 Docker 鏡像存儲空間,提供更高的安全性,只有授權用戶可以訪問。企業可以自建私有倉庫以控制鏡像的存儲和管理,並支持版本控制和與 CI/CD 流程的集成。

鏡像、容器、倉庫,三者之間的工作流程
200-AREA/風清雲談/POST/1. 軟體工程/架構/原生雲/attachments/Pasted image 20250320101857.png

瞭解了 Docker 的三大核心概念,接下來認識下 Docker 的核心架構和一些重要的組件。

Docker 架構

在瞭解 Docker 架構前,不免俗為大家説一下相關的背景知識——容器的發展史。

容器技術隨着 Docker 的出現變得炙手可熱,所有公司都在積極擁抱容器技術。此時市場上除了有 Docker 容器,還有很多其他的容器技術,比如 CoreOS 的 rkt、lxc 等。容器技術百花齊放是好事,但也出現了很多問題。比如容器技術的標準到底是什麼?容器標準應該由誰來制定?

也許你可能會説, Docker 已經成為了事實標準,把 Docker 作為容器技術的標準不就好了?事實並沒有想象的那麼簡單。因為那時候不僅有容器標準之爭,編排技術之爭也十分激烈。當時的編排技術有三大主力,分別是 Docker Swarm、Kubernetes 和 Mesos 。Swarm 毋庸置疑,肯定願意把 Docker 作為唯一的容器運行時,但是 Kubernetes 和 Mesos 就不同意了,因為它們不希望調度的形式過度單一。

在這樣的背景下,最終爆發了容器大戰,OCI也正是在這樣的背景下應運而生。

OCI全稱為開放容器標準(Open Container Initiative),它是一個輕量級,開放的治理結構。OCI組織在 Linux 基金會的大力支持下,於 2015 年 6 月份正式註冊成立。基金會旨在為用户圍繞工業化容器的格式和鏡像運行時,制定一個開放的容器標準。目前主要有兩個標準文檔:容器運行時標準 (runtime spec)和容器鏡像標準(image spec)

200-AREA/風清雲談/POST/1. 軟體工程/架構/原生雲/attachments/Pasted image 20250320102607.png

正是由於容器的戰爭,才導致 Docker 不得不在戰爭中改變一些技術架構。最終形成了下圖所示的技術架構。

200-AREA/風清雲談/POST/1. 軟體工程/架構/原生雲/attachments/Pasted image 20250320103732.png

我們可以看到,Docker 整體架構採用 C/S(客户端 / 服務器)模式,主要由客户端和服務端兩大部分組成。客户端負責發送操作指令,服務端負責接收和處理指令。客户端和服務端通信有多種方式,即可以同一台機器上通過UNIX SOCK通信,也可以通過網絡連接遠程通信。
200-AREA/風清雲談/POST/1. 軟體工程/架構/原生雲/attachments/Pasted image 20250320152930.png
下面逐一介紹客户端和服務端。

Docker 客户端

Docker 客户端其實是一種泛稱。其中 docker 命令是 Docker 用户與 Docker 服務端交互的主要方式。除了使用 docker 命令的方式,還可以使用直接請求 REST API 的方式與 Docker 服務端交互,甚至還可以使用各種語言的 SDK 與 Docker 服務端交互。目前社區維護着 Go、Java、Python、PHP 等數十種語言的 SDK,足以滿足日常需求。

Docker 服務端

Docker 服務端是 Docker 所有後端服務的統稱。其中 dockerd 是一個非常重要的後端管理進程,它負責響應和處理來自 Docker 客户端的請求,然後將客户端的請求轉化為 Docker 的具體操作。例如鏡像、容器、網絡和掛載卷等具體對象的操作和管理。

Docker 從誕生到現在,服務端經歷了多次架構重構。起初,服務端的組件是全部集成在 docker 二進制裏。但是從 1.11 版本開始, dockerd 已經成了獨立的二進制,此時的容器也不是直接由 dockerd 來啓動了,而是集成了 containerd、runC 等多個組件。

雖然 Docker 的架構在不停重構,但是各個模塊的基本功能和定位並沒有變化。它和一般的 C/S 架構系統一樣,Docker 服務端模塊負責和 Docker 客户端交互,並管理 Docker 的容器、鏡像、網絡等資源。

Docker 重要組件

下面,我以 Docker 最新版 28.0.1 版本為例,看下 Docker 都有哪些工具和組件。在 Docker 安裝路徑下執行 ls 命令可以看到以下與 docker 有關的二進制文件。

$ ls -l /usr/bin
-rwxr-xr-x. 1 root root 41146528  1月 11 02:14 containerd
-rwxr-xr-x. 1 root root 6226072  1月 11 02:14 containerd-shim
-rwxr-xr-x. 1 root root 20906305  1月 11 02:14 ctr
-rwxr-xr-x. 1 root root 34086776  2月 26 18:42 docker
-rwxr-xr-x. 1 root root 2732872  2月 26 18:40 docker-proxy
-rwxr-xr-x. 1 root root 80857400  2月 26 18:40 dockerd
-rwxr-xr-x. 1 root root 13817720  1月 11 02:14 runc
$ ls -l /usr/libexec/docker
-rwxr-xr-x. 1 root root 633264  2月 26 18:40 docker-init

可以看到,Docker 目前已經有了非常多的組件和工具。這裏我先介紹一下 Docker 的兩個至關重要的組件:runCcontainerd

  • runC是 Docker 官方按照 OCI 容器運行時標準的一個實現。通俗地講,runC 是一個用來運行容器的輕量級工具,是真正用來運行容器的。
  • containerd是 Docker 服務端的一個核心組件,它是從dockerd中剝離出來的 ,它的誕生完全遵循 OCI 標準,是容器標準化後的產物。containerd通過 containerd-shim 啓動並管理 runC,可以説containerd真正管理了容器的生命週期。

200-AREA/風清雲談/POST/1. 軟體工程/架構/原生雲/attachments/Pasted image 20250320104614.png

圖3 Docker 服務端組件調用關係圖

通過上圖,可以看到,dockerd通過 gRPC 與containerd通信,由於dockerd與真正的容器運行時,runC中間有了containerd這一 OCI 標準層,使得dockerd可以確保接口向下兼容。

containerd-shim 是一個用於管理容器進程的中介層,它的主要功能是將 containerd(一個容器管理工具)與實際運行的容器進程之間進行解耦。

[!quote] gRPC

  • gRPC 是一種遠程服務調用。想瞭解更多信息可以參考https://grpc.io 。
  • containerd-shim 的意思是墊片,類似於擰螺絲時夾在螺絲和螺母之間的墊片。containerd-shim 的主要作用是將 containerd 和真正的容器進程解耦,使用 containerd-shim 作為容器進程的父進程,從而實現重啓 containerd 不影響已經啓動的容器進程。

瞭解了 dockerd,containerd 和 runC 之間的關係,下面可以通過啓動一個 Docker 容器,來驗證它們進程之間的關係。

Docker 各組件之間的關係

首先通過以下命令來啓動一個 busybox 容器:sudo ps aux |grep dockerd

$ docker run -d busybox sleep 3600

容器啓動後,通過以下命令查看一下 dockerd 的 PID:

$ sudo ps aux |grep dockerd
root       35421  0.2  4.7 1976804 79464 ?       Ssl  15:00   0:00 /usr/bin/dockerd

通過上面的輸出結果可以得知 dockerd 的 PID 為 35421。為了驗證圖 3 中 Docker 各組件之間的調用關係,下面使用 pstree 命令查看一下進程父子關係:

$ sudo pstree -l -a -A 35421
dockerd
  |-containerd --config /var/run/docker/containerd/containerd.toml --log-level info
  |   |-containerd-shim -namespace moby -workdir /var/lib/docker/containerd/daemon/io.containerd.runtime.v1.linux/moby/d14d20507073e5743e607efd616571c834f1a914f903db6279b8de4b5ba3a45a -address /var/run/docker/containerd/containerd.sock -containerd-binary /usr/bin/containerd -runtime-root /var/run/docker/runtime-runc
  |   |   |-sleep 3600

事實上,dockerd 啓動的時候, containerd 就隨之啓動了,dockerd 與 containerd 一直存在。當執行 docker run 命令(通過 busybox 鏡像創建並啓動容器)時,containerd 會創建 containerd-shim 充當 “墊片” 進程,然後啓動容器的真正進程 sleep 3600 。這個過程和架構圖是完全一致的。


4. Docker指令操作 (15分鐘)

為了幫助使用者快速掌握Docker命令行的使用方法,許多資源和學習材料已經被開發出來。然而,隨著Docker技術的快速演進,這些資源可能無法完全滿足使用者的實際需求。因此,現在是時候深入探索Docker命令行的操作,進行一次全面的學習之旅。

[!example] Docker 官方為了讓用户快速上手,所提供了一個Docker workshop,用意在幫助用户掌握 Docker 命令行的使用方法。Docker官方交互式教程

首先,Docker 的命令清單可以通過運行  dockerd -help 或使用 docker命令運行。

在 Docker 容器技術不斷演化的過程中,Docker 的子命令已經達到41個之多,其中核心子命令(例如:run)還會有複雜的參數配置。筆者通過結合功能和應用場景方面的考慮,把命令行劃分為4個部分,方便我們快速概覽 Docker 命令行的組成結構:
200-AREA/風清雲談/POST/1. 軟體工程/架構/原生雲/attachments/Pasted image 20250320105822.png

功能劃分命令
環境信息相關1. info
2. version
系統運維相關1. attach
2. build
3. commit
4. cp 5. diff
6. images
7. export/ import / save / load
8. inspect
9. kill
10. port
11. pause / unpause
12. ps 13. rm
14. rmi 15. run
16. start / stop / restart
17. tag 18. top 19.wait
20. rename
21. stats
22. update
23. exec
24. deploy
25. create
日誌信息相關1. events
2. history
3. logs
Docker Hub服務相關1. login/ logout
2. pull / push
3. search

200-AREA/風清雲談/POST/1. 軟體工程/架構/原生雲/attachments/Pasted image 20250320105814.png

參數約定

單個字的參數可以放在一起組合配置,例如:

# 啟動一個名為 `test` 的容器,並在該容器中運行 `busybox` 映像的 `sh`(Shell)命令。
$ docker run -t -i --name test busybox sh

可以用這樣的方式等同上面指令:

docker run -ti --name test busybox sh

布林值約定

Boolean 參數形式如:-d=false。注意,當你聲明這個 Boolean 參數時,比如 docker run -d=true,它將直接把啓動的 Container 掛起放在後端運行。

使用Boolean值啟動容器

$ docker run -d=true my_container

字串和數字

參數如 -–name=“” 定義一個字串,它僅能被定義一次。同類型的如-c=0 定義一個數字,它也只能被定義一次。

定義字串參數

$ docker run --name="my_container" my_image

定義數字參數

# `-c=0` 表示不限制容器使用的 CPU 數量
$ docker run -c=0 my_image

後端進程

Docker 後端進程是一個常駐後端的系統進程,目前已經從 Docker 程序分離處理一份獨立的程序 dockerd 來執行守護後端進程。這個後端進程是用來啓動容器引擎的,使用 dockerd –help 可以得到更詳細的功能參數配置。如下圖:

$ dockerd –help
Usage:  dockerd [OPTIONS]

A self-sufficient runtime for containers.

Options:
      --add-runtime runtime                   Register an additional OCI compatible
                                              runtime (default [])
      --authorization-plugin list             Authorization plugins to load
      --bip string                            IPv4 address for the default bridge
      --bip6 string                           IPv6 address for the default bridge
  -b, --bridge string                         Attach containers to a network bridge
      --cdi-spec-dir list                     CDI specification directories to use
      --cgroup-parent string                  Set parent cgroup for all containers
      --config-file string                    Daemon configuration file (default
                                              "/etc/docker/daemon.json")
      --containerd string                     containerd grpc address
      --containerd-namespace string           Containerd namespace to use (default "moby")
      --containerd-plugins-namespace string   Containerd namespace to use for plugins
                                              (default "plugins.moby")
      --cpu-rt-period int                     Limit the CPU real-time period in
                                              microseconds for the parent cgroup for all
                                              containers (not supported with cgroups v2)
      --cpu-rt-runtime int                    Limit the CPU real-time runtime in
                                              microseconds for the parent cgroup for all
                                              containers (not supported with cgroups v2)
      --cri-containerd                        start containerd with cri
      --data-root string                      Root directory of persistent Docker state
                                              (default "/var/lib/docker")
  -D, --debug                                 Enable debug mode
      --default-address-pool pool-options     Default address pools for node specific
                                              local networks
      --default-cgroupns-mode string          Default mode for containers cgroup namespace
                                              ("host" | "private") (default "private")
      --default-gateway ip                    Default gateway IPv4 address for the default
                                              bridge network
      --default-gateway-v6 ip                 Default gateway IPv6 address for the default
                                              bridge network
      --default-ipc-mode string               Default mode for containers ipc ("shareable"
                                              | "private") (default "private")
      --default-network-opt mapmap            Default network options (default map[])
      --default-runtime string                Default OCI runtime for containers (default
                                              "runc")
      --default-shm-size bytes                Default shm size for containers (default 64MiB)
      --default-ulimit ulimit                 Default ulimits for containers (default [])
      --dns ipSlice                           DNS server to use (default [])
      --dns-opt list                          DNS options to use
      --dns-search list                       DNS search domains to use
      --exec-opt list                         Runtime execution options
      --exec-root string                      Root directory for execution state files
                                              (default "/var/run/docker")
      --experimental                          Enable experimental features
      --feature map                           Enable feature in the daemon (default map[])
      --fixed-cidr string                     IPv4 subnet for the default bridge network
      --fixed-cidr-v6 string                  IPv6 subnet for the default bridge network
  -G, --group string                          Group for the unix socket (default "docker")
      --help                                  Print usage
  -H, --host list                             Daemon socket(s) to connect to
      --host-gateway-ip list                  IP addresses that the special 'host-gateway'
                                              string in --add-host resolves to. Defaults
                                              to the IP addresses of the default bridge
      --http-proxy string                     HTTP proxy URL to use for outgoing traffic
      --https-proxy string                    HTTPS proxy URL to use for outgoing traffic
      --icc                                   Enable inter-container communication for the
                                              default bridge network (default true)
      --init                                  Run an init in the container to forward
                                              signals and reap processes
      --init-path string                      Path to the docker-init binary
      --insecure-registry list                Enable insecure registry communication
      --ip ip                                 Host IP for port publishing from the default
                                              bridge network (default 0.0.0.0)
      --ip-forward                            Enable IP forwarding in system configuration
                                              (default true)
      --ip-forward-no-drop                    Do not set the filter-FORWARD policy to DROP
                                              when enabling IP forwarding
      --ip-masq                               Enable IP masquerading for the default
                                              bridge network (default true)
      --ip6tables                             Enable addition of ip6tables rules (default true)
      --iptables                              Enable addition of iptables rules (default true)
      --ipv6                                  Enable IPv6 networking for the default
                                              bridge network
      --label list                            Set key=value labels to the daemon
      --live-restore                          Enable live restore of docker when
                                              containers are still running
      --log-driver string                     Default driver for container logs (default
                                              "json-file")
      --log-format string                     Set the logging format ("text"|"json")
                                              (default "text")
  -l, --log-level string                      Set the logging level
                                              ("debug"|"info"|"warn"|"error"|"fatal")
                                              (default "info")
      --log-opt map                           Default log driver options for containers
                                              (default map[])
      --max-concurrent-downloads int          Set the max concurrent downloads (default 3)
      --max-concurrent-uploads int            Set the max concurrent uploads (default 5)
      --max-download-attempts int             Set the max download attempts for each pull
                                              (default 5)
      --metrics-addr string                   Set default address and port to serve the
                                              metrics api on
      --mtu int                               Set the MTU for the default "bridge" network
                                              (default 1500)
      --network-control-plane-mtu int         Network Control plane MTU (default 1500)
      --no-new-privileges                     Set no-new-privileges by default for new
                                              containers
      --no-proxy string                       Comma-separated list of hosts or IP
                                              addresses for which the proxy is skipped
      --node-generic-resource list            Advertise user-defined resource
  -p, --pidfile string                        Path to use for daemon PID file (default
                                              "/var/run/docker.pid")
      --raw-logs                              Full timestamps without ANSI coloring
      --registry-mirror list                  Preferred Docker registry mirror
      --rootless                              Enable rootless mode; typically used with
                                              RootlessKit
      --seccomp-profile string                Path to seccomp profile. Set to "unconfined"
                                              to disable the default seccomp profile
                                              (default "builtin")
      --selinux-enabled                       Enable selinux support
      --shutdown-timeout int                  Set the default shutdown timeout (default 15)
  -s, --storage-driver string                 Storage driver to use
      --storage-opt list                      Storage driver options
      --swarm-default-advertise-addr string   Set default address or interface for swarm
                                              advertised address
      --tls                                   Use TLS; implied by --tlsverify
      --tlscacert string                      Trust certs signed only by this CA (default
                                              "/home/aaron/.docker/ca.pem")
      --tlscert string                        Path to TLS certificate file (default
                                              "/home/aaron/.docker/cert.pem")
      --tlskey string                         Path to TLS key file (default
                                              "/home/aaron/.docker/key.pem")
      --tlsverify                             Use TLS and verify the remote
      --userland-proxy                        Use userland proxy for loopback traffic
                                              (default true)
      --userland-proxy-path string            Path to the userland proxy binary (default
                                              "/usr/bin/docker-proxy")
      --userns-remap string                   User/Group setting for user namespaces
      --validate                              Validate daemon configuration and exit
  -v, --version                               Print version information and quit

Docker 後端進程參數清單如下表:

參數解釋
–add-runtime runtime選擇容器運行時引擎,默認 containerd
–allow-nondistributable-artifacts list因為類如 window base image 包含版權限制,所以配置指定的私有鏡像倉庫,可以幫助應用正常發佈
–api-cors-header string提供跨站 API 請求自定義包頭信息
–authorization-plugin list認證套件配置
–bip string配置網橋地址
-b, –bridge string連接網橋
–cgroup-parent string配置容器的父 cgroup 信息
–cluster-advertise string集羣廣播網絡地址
–cluster-store string集羣存儲支持
–cluster-store-opt map集羣存儲參數配置
–config-file string後端引擎參數配置文件
–containerd string容器引擎實例網絡套接字路徑
–cpu-rt-period int限制 CPU 間隔頻率(微秒級別)
–cpu-rt-runtime int限制 CPU 運行時頻率(微秒級別)
–data-root string容器引擎數據根目錄地址
-D, –debug調試信息
–default-gateway ip容器默認 IPv4 網絡網關
–default-gateway-v6 ip容器默認 IPv6 網絡網關
–default-runtime string容器運行時,默認 runc
–default-ulimit ulimit配置容器默認最大文件限制數,改善運行性能
–disable-legacy-registry廢棄老版本鏡像倉庫
–dns listDNS 服務地址
–dns-opt listDNS 服務參數
–dns-search listDNS服務查詢域名配置
–exec-opt list運行時執行參數
–exec-root string運行時執行根目錄地址
–experimental啓用實驗性特性
–fixed-cidr string固定 IPv4 網段
–fixed-cidr-v6 string固定 IPv6 網段
-G, –group string網絡套接字所屬組
–help幫助信息
-H, –host list後端進程連接地址
–icc啓用容器間的網絡互聯,默認啓用
–init在容器運行時啓動一個 init 程序,來統一管理進程
–init-path stringdocker init 的路徑地址
–insecure-registry list非安全鏡像倉庫地址列表
–ip ip默認容器綁定 IP 地址,默認 0.0.0.0
–ip-forward啓動 net.ipv4.ip_forward
–ip-masq啓動IP混淆
–iptables啓動默認的iptable規則
–ipv6啓動 IPv6 網絡
–label list配置鍵值對參數到引擎後端
–live-restore啓用容器熱遷移特性
–log-driver string日誌驅動配置,默認 json-file
-l, –log-level string日誌級別
–log-opt map日誌驅動參數
–max-concurrent-downloads int每次 pull 的最大下載線程數
–max-concurrent-uploads int每次 push 最大上傳線程數
–metrics-addr string監控地址
–mtu int網絡數據包 MTU 配置
–no-new-privileges去掉 nonewprivs 權限
–oom-score-adjust intOOM 閾值配置
-p, –pidfile string引擎後端進程文件地址
–raw-logs無 ANSI 顏色的日誌
–registry-mirror list鏡像倉庫同步鏡像地址
–seccomp-profile stringseccomp 文件地址
–selinux-enabled啓用 selinux
–shutdown-timeout int默認停機超時時間,默認15 秒
-s, –storage-driver string容器存儲驅動
–storage-opt list容器存儲驅動參數
–swarm-default-advertise-addr stringswarm 集羣廣播地址
–tls使用 TLS 認證
–tlscacert stringCA 文件地址
–tlscert stringTLS 認證文件地址
–tlskey stringTLS 私鑰地址
–tlsverify使用 TLS 認證
–userland-proxy使用用户態 proxy 來路由 loopback 流量
–userland-proxy-path string用户態 proxy 地址
–userns-remap string用户命令空間的用户、用户組配置
-v, –version版本

Docker 命令行探秘

環境信息相關
info

使用方法:docker info

例子:

$ docker info
Path:     /usr/libexec/docker/cli-plugins/docker-compose
Server:
 Containers: 2
  Running: 1
  Paused: 0
  Stopped: 1
 Images: 2
 Server Version: 28.0.1
 Storage Driver: overlay2
  Backing Filesystem: xfs
  Supports d_type: true
  Using metacopy: false
  Native Overlay Diff: true
  userxattr: false
 Logging Driver: json-file
 Cgroup Driver: systemd
 Cgroup Version: 2
 Plugins:
  Volume: local
  Network: bridge host ipvlan macvlan null overlay
  Log: awslogs fluentd gcplogs gelf journald json-file local splunk syslog
 Swarm: inactive
 Runtimes: io.containerd.runc.v2 runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: bcc810d6b9066471b0b6fa75f557a15a1cbf31bb
 runc version: v1.2.4-0-g6c52b3f
 init version: de40ad0
 Security Options:
  seccomp
   Profile: builtin
  cgroupns
 Kernel Version: 5.14.0-503.14.1.el9_5.aarch64
 Operating System: Rocky Linux 9.5 (Blue Onyx)
 OSType: linux
 Architecture: aarch64
 CPUs: 2
 Total Memory: 1.6GiB
 Name: localhost.localdomain
 ID: 88c9336f-13d2-4e8a-82c8-de0bc49cfc11
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
  File Descriptors: 30
  Goroutines: 48
  System Time: 2025-03-18T15:33:56.012638115+08:00
  EventsListeners: 0
 Experimental: false
 Insecure Registries:
  ::1/128
  127.0.0.0/8
 Live Restore Enabled: false

使用説明:

這個命令在開發者報告 Bug 時會非常有用,結合 docker vesion 一起,可以隨時使用這個命令把本地的配置信息提供出來,方便 Docker 的開發者快速定位問題。

version

使用方法:docker version

使用説明:

顯示 Docker 的版本號,API 版本號,Git commit,Docker 客户端和後端進程的 Go 版本號。

$ docker version 
Client: Docker Engine - Community
 Version:           28.0.1
 API version:       1.48
 Go version:        go1.23.6
 Git commit:        068a01e
 Built:             Wed Feb 26 10:41:22 2025
 OS/Arch:           linux/arm64
 Context:           default

Server: Docker Engine - Community
 Engine:
  Version:          28.0.1
  API version:      1.48 (minimum version 1.24)
  Go version:       go1.23.6
  Git commit:       bbd0a17
  Built:            Wed Feb 26 10:39:52 2025
  OS/Arch:          linux/arm64
  Experimental:     false
 containerd:
  Version:          1.7.25
  GitCommit:        bcc810d6b9066471b0b6fa75f557a15a1cbf31bb
 runc:
  Version:          1.2.4
  GitCommit:        v1.2.4-0-g6c52b3f
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

系統運維相關

attach

使用方法:docker attach [OPTIONS] CONTAINER

例子:

# 使用 Docker 啟動一個新的容器,並在該容器中運行 `ubuntu` 映像的 `/usr/bin/top -b` 命令,然後將該容器的 ID 存儲在變數 `ID` 中。
$ ID=$(docker run -d ubuntu /usr/bin/top -b)

$ docker attach $ID
top - 07:36:59 up  1:05,  0 user,  load average: 0.10, 0.04, 0.01
Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.5 us,  1.0 sy,  0.0 ni, 98.5 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st 
MiB Mem :   1638.7 total,     37.5 free,    805.4 used,    896.0 buff/cache     
MiB Swap:   2048.0 total,   2046.7 free,      1.2 used.    833.3 avail Mem 

    PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
      1 root      20   0    8488   4736   2816 R   0.0   0.3   0:00.01 top
$ docker stop $ID

使用説明:

使用這個命令可以掛載正在後端運行的容器,在開發應用的過程中運用這個命令可以隨時觀察容器內進程的運行狀況。開發者在開發應用的場景中,這個命令是一個非常有用的命令。

build

使用方法:docker build [OPTIONS] PATH | URL | -

例子:

FROM ubuntu:latest
LABEL maintainer="your_email@example.com"
RUN apt-get update && apt-get install -y curl
CMD ["bash"]
$ echo -e "FROM ubuntu:latest\nLABEL maintainer=\"your_email@example.com\"\nRUN apt-get update && apt-get install -y curl\nCMD [\"bash\"]" > Dockerfile
# 構建新的image
$ docker build .
[+] Building 0.0s (6/6) FINISHED                                                                                         docker:default
 => [internal] load build definition from Dockerfile                                                                               0.0s
 => => transferring dockerfile: 216B                                                                                               0.0s
 => [internal] load metadata for docker.io/library/ubuntu:latest                                                                   0.0s
 => [internal] load .dockerignore                                                                                                  0.0s
 => => transferring context: 2B                                                                                                    0.0s
 => [1/2] FROM docker.io/library/ubuntu:latest                                                                                     0.0s
 => CACHED [2/2] RUN apt-get update && apt-get install -y curl                                                                     0.0s
 => exporting to image                                                                                                             0.0s
 => => exporting layers                                                                                                            0.0s
 => => writing image sha256:134a2eca823cb7fdbf94dce029337eb15ba0ac2b34b30cc4a58ff6c75d9c8bb3                                       0.0s

使用説明:

這個命令是從源碼構建新 Image 的命令。因為 Image 是分層的,最關鍵的 Base Image 是如何構建的是用户比較關心的,Docker 官方文檔給出了構建方法,請參考這裏

commit

使用方法:docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

例子:

$ docker ps
CONTAINER ID   IMAGE     COMMAND             CREATED          STATUS          PORTS     NAMES
5980f2d64265   ubuntu    "/usr/bin/top -b"   10 seconds ago   Up 9 seconds              beautiful_elbakyan
1f8eca6ebd12   busybox   "sleep 3600"        32 minutes ago   Up 32 minutes             youthful_williamson

$ docker commit 1f8eca6ebd12 SvenDowideit/testimage:version3

$ docker images | head
REPOSITORY               TAG        IMAGE ID       CREATED         SIZE
SvenDowideit/testimage   version3   aeb5996bdcc0   6 seconds ago   4.04MB
<none>                   <none>     134a2eca823c   4 minutes ago   162MB
ubuntu                   latest     c3d1a3432580   7 weeks ago     101MB
hello-world              latest     f1f77a0f96b7   7 weeks ago     5.2kB
busybox                  latest     cfca16f8feae   5 months ago    4.04MB

使用説明:

這個命令的用處在於把有修改的 container 提交成新的 Image,然後導出此 Imange 分發給其他場景中調試使用。Docker 官方的建議是,當你在調試完 Image 的問題後,應該寫一個新的 Dockerfile 文件來維護此 Image。commit 命令僅是一個臨時創建 Imange 的輔助命令。

新建Dockerfile 在 SvenDowideit/testimage 基礎維護 image

# 使用已存在的映像作為基礎
FROM SvenDowideit/testimage:version3
LABEL maintainer="your_email@example.com"
CMD ["bash"]
cp

使用方法: cp CONTAINER:PATH HOSTPATH

使用説明:

使用 cp 可以把容器內的文件複製到 Host 主機上。這個命令在開發者開發應用的場景下,會需要把運行程序產生的結果複製出來的需求,在這個情況下就可以使用這個 cp 命令。

diff

使用方法:docker diff CONTAINER

例子:

# 創建一個 Docker 容器。這裡以 `ubuntu` 映像為例
$ docker run -it --name my-ubuntu-container ubuntu bash
# 在容器內進行一些變更
$ echo "Hello, Docker!" > /hello.txt apt-get update
# 退出容器
$ exit
# 查看容器的變更
$ docker diff 7bb0e258aefe
C /var
C /var/lib
C /var/lib/apt
C /var/lib/apt/lists
A /var/lib/apt/lists/ports.ubuntu.com_ubuntu-ports_dists_noble-security_multiverse_binary-arm64_Packages.lz4
A /var/lib/apt/lists/ports.ubuntu.com_ubuntu-ports_dists_noble-backports_InRelease
A /var/lib/apt/lists/ports.ubuntu.com_ubuntu-ports_dists_noble-security_InRelease
A /var/lib/apt/lists/ports.ubuntu.com_ubuntu-ports_dists_noble-updates_multiverse_binary-arm64_Packages.lz4
A /var/lib/apt/lists/ports.ubuntu.com_ubuntu-ports_dists_noble-backports_universe_binary-arm64_Packages.lz4
A /var/lib/apt/lists/ports.ubuntu.com_ubuntu-ports_dists_noble-security_universe_binary-arm64_Packages.lz4
A /var/lib/apt/lists/ports.ubuntu.com_ubuntu-ports_dists_noble-updates_InRelease
A /var/lib/apt/lists/ports.ubuntu.com_ubuntu-ports_dists_noble-updates_main_binary-arm64_Packages.lz4
A /var/lib/apt/lists/ports.ubuntu.com_ubuntu-ports_dists_noble_InRelease
A /var/lib/apt/lists/ports.ubuntu.com_ubuntu-ports_dists_noble_multiverse_binary-arm64_Packages.lz4
A /var/lib/apt/lists/ports.ubuntu.com_ubuntu-ports_dists_noble_universe_binary-arm64_Packages.lz4
A /var/lib/apt/lists/auxfiles
.....
# 清理環境
$ docker rm my-ubuntu-container

使用説明:

可以查看指定容器的文件系統變更。這個命令會列出自容器創建以來,對容器文件系統所做的所有變更,包括新增、修改和刪除的檔案。

images

使用方法:docker images [OPTIONS] [NAME]

例子:

$ docker images 
REPOSITORY TAG IMAGE ID CREATED VIRTUAL SIZE
REPOSITORY               TAG        IMAGE ID       CREATED          SIZE
SvenDowideit/testimage   version3   aeb5996bdcc0   13 minutes ago   4.04MB
<none>                   <none>     134a2eca823c   17 minutes ago   162MB
ubuntu                   latest     c3d1a3432580   7 weeks ago      101MB
hello-world              latest     f1f77a0f96b7   7 weeks ago      5.2kB
busybox                  latest     cfca16f8feae   5 months ago     4.04MB

使用説明:

用於列出 Docker 主機上所有可用的映像。

export/ import / save / load

使用方法:

$ docker ps -a
CONTAINER ID   IMAGE     COMMAND             CREATED          STATUS                        PORTS     NAMES
5980f2d64265   ubuntu    "/usr/bin/top -b"   20 minutes ago   Up 20 minutes                           beautiful_elbakyan
0c558b6465a8   ubuntu    "/usr/bin/top -b"   29 minutes ago   Exited (0) 29 minutes ago               quirky_archimedes
72164845ac1f   busybox   "sh"                36 minutes ago   Exited (130) 34 minutes ago             test
1f8eca6ebd12   busybox   "sleep 3600"        53 minutes ago   Up 53 minutes                           youthful_williamson
# export
$ docker export beautiful_elbakyan > latest.tar
# import
# docker import URL|- [REPOSITORY[:TAG]]
$ docker import latest.tar my-repo/my-image:latest
# save
# docker save IMAGE
$ docker save busybox > my-image1.tar
# load
# docker load
# 出錯指令
$ docker load -i my-image.tar
# 正確指令
$ docker load -i my-image1.tar

使用説明:

這一組命令是系統運維裏非常關鍵的命令。加載(兩種方法:import,load),導出(一種方法:save,export)容器系統文件。

問題分析

[!question] 執行 docker load 時出現問題
open /var/lib/docker/tmp/docker-import-4199989984/repositories: no such file or directory

主要因為壓縮包如果是用 docker save 打包,就用 docker load,但是如果壓縮包是用 docker export 打包,那就需要用 docker import

inspect

使用方法:

$ docker inspect CONTAINER|IMAGE [CONTAINER|IMAGE...]

例子:

$ docker inspect --format='{{.NetworkSettings.IPAddress}}' $INSTANCE_ID
172.17.0.3

使用説明:

查看容器運行時詳細信息的命令。瞭解一個 Image 或者 Container 的完整構建信息就可以通過這個命令實現。

kill

使用方法:

$ docker kill [OPTIONS] CONTAINER [CONTAINER...]

例子:

$ docker kill $INSTANCE_ID
1553732ae3df

使用説明:

殺掉容器的進程。

port

使用方法:

$ docker port CONTAINER PRIVATE_PORT

例子:

$ docker run -d --name my_nginx -p 8080:80 nginx
# 有一個名為 `my_nginx` 的容器,想查看其 80 端口的映射
$ docker port my_nginx 80
# 容器的 80 端口正確映射到主機的 8080 端口
0.0.0.0:8080
# 

使用説明:

印出出 Host 主機端口與容器暴露出的端口的 NAT 映射關係

pause / unpause

使用方法:

$ docker pause CONTAINER

例子:

$ docker pause my_nginx
my_nginx

使用説明:

使用 cgroup 的 freezer 順序暫停、恢復容器裏的所有進程。詳細 freezer 的特性,請參考官方文檔

ps

使用方法:

$ docker ps [OPTIONS]

例子:

$ docker ps
CONTAINER ID   IMAGE     COMMAND                   CREATED         STATUS                  PORTS                                     NAMES
998cfb625160   nginx     "/docker-entrypoint.…"   2 minutes ago   Up 2 minutes (Paused)   0.0.0.0:8080->80/tcp, [::]:8080->80/tcp   my_nginx

使用説明:

docker ps 印出出正在運行的容器,或是添加參數 -a ,則是印出出所有運行過的容器。

rm

使用方法:

docker rm [OPTIONS] CONTAINER [CONTAINER...]

例子:

$ docker rm my_nginx
Error response from daemon: cannot remove container "/my_nginx": container is paused and must be unpaused first
# 當嘗試刪除一個正在運行的容器時,Docker 會提示需要先停止(stop)該容器才能進行刪除,或者你可以使用強制刪除選項。
$ docker stop my_nginx
my_nginx
# 再次執行刪除指令的容器
docker rm my_nginx
my_nginx

使用説明:

刪除指定的容器。

rmi

使用方法:

$ docker rmi IMAGE [IMAGE...]

例子:

$ docker images
REPOSITORY               TAG        IMAGE ID       CREATED        SIZE
my-repo/my-image         latest     e69146db607d   18 hours ago   101MB
SvenDowideit/testimage   version3   aeb5996bdcc0   19 hours ago   4.04MB
<none>                   <none>     134a2eca823c   19 hours ago   162MB
nginx                    latest     2c9168b3c9a8   5 weeks ago    197MB
ubuntu                   latest     c3d1a3432580   7 weeks ago    101MB
hello-world              latest     f1f77a0f96b7   8 weeks ago    5.2kB
busybox                  latest     cfca16f8feae   5 months ago   4.04MB

$ docker rmi fd484f19954f
Untagged: my-repo/my-image:latest
Deleted: sha256:e69146db607d17c2f94ab2a1dae51dfb5b049311dafd294e60c3519b5d5e5964
Deleted: sha256:99fa42a931c41a7b59b5787b631e5d017c95d8c5826dbd76634f82c620713dea

$ docker rmi nginx
Untagged: nginx:latest
Untagged: nginx@sha256:124b44bfc9ccd1f3cedf4b592d4d1e8bddb78b51ec2ed5056c52d3692baebc19
Deleted: sha256:2c9168b3c9a84851f91e03534dc4136951e9f581ab3ac8ee38b28b49ad57ba38
Deleted: sha256:2cdcd9ae6804cbc2c8c8c66b8156d722fb7275eecdf691aa798da08aa3842e67
Deleted: sha256:5a9a0099da05feea7f90572b293886da5ca2ad1d168c753a64bbed84ca96cbdd
Deleted: sha256:fe5448bc54d2a21c260cb52bf6cbb7dd25d513326065f442b65a5611944f6bee
Deleted: sha256:08fb5c8b06bcff060329308109d4b306b4bfd2db4be01bddb77302d4e1f65659
Deleted: sha256:2dbb763aeeec1e9a0e44e99182a65fd450bcbaba296b7a049e242a257ee5bace
Deleted: sha256:6fcccaff183b2d53bf2d12e5c56e522ca610d1c7044c32d7c927cd27122da61a
Deleted: sha256:70a3ee4d4d38a5bb57ecd08c40c9a37d750d3f8f63591e97cdbf8277c3698e6f

$ docker images
REPOSITORY               TAG        IMAGE ID       CREATED        SIZE
SvenDowideit/testimage   version3   aeb5996bdcc0   19 hours ago   4.04MB
<none>                   <none>     134a2eca823c   19 hours ago   162MB
ubuntu                   latest     c3d1a3432580   7 weeks ago    101MB
hello-world              latest     f1f77a0f96b7   8 weeks ago    5.2kB
busybox                  latest     cfca16f8feae   5 months ago   4.04MB

使用説明:

指定刪除 Image 文件。

run

使用方法:

$ docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

例子:

$ docker run --cidfile /tmp/docker_test.cid ubuntu echo "test"
test

使用説明:

這個命令是核心命令,可以配置的子參數詳細解釋可以通過 docker run –help 列出。

start / stop / restart

使用方法:

$ docker start CONTAINER [CONTAINER...]

例子:

$ docker start test
test

使用説明:

這組命令可以開啓(兩個:start,restart),停止(一個:stop)一個容器。

tag

使用方法:

$ docker tag [OPTIONS] IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]

例子:

$ docker tag ubuntu ubuntu:v1.0

$ docker images ubuntu
ubuntu       v1.0      c3d1a3432580   7 weeks ago   101MB

使用説明:

組合使用用户名,Image 名字,標籤名來組織管理Image。

top

使用方法:

$ docker top CONTAINER [ps OPTIONS]

例子:

$ docker top test
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                3668                3643                0                   10:42               pts/0               00:00:00            sh

使用説明:

顯示容器內運行的進程。

wait

使用方法:

$ docker wait CONTAINER [CONTAINER...]

例子:

$ docker run -d --name my_app nginx
# 檢查容器狀態 
$ docker ps
45e68ca5433a   nginx     "/docker-entrypoint.…"   2 minutes ago   Up 2 minutes   80/tcp    my_app
# 停止容器
$ docker stop my_app
# 等待容器停止並獲取其退出狀態碼。
$ exit_code=$(docker wait my_app)
# 顯示退出狀態碼,這樣你就可以知道容器是正常停止還是因為錯誤停止。
$ echo "Container exited with code: $exit_code"

使用説明:

阻塞對指定容器的其他調用方法,直到容器停止後退出阻塞。

rename

使用方法:

$ docker rename CONTAINER NEW_NAME

例子:

$ docker ps -a
CONTAINER ID   IMAGE     COMMAND                   CREATED          STATUS                        PORTS     NAMES
e2a199060f07   nginx     "/docker-entrypoint.…"   2 minutes ago    Exited (0) 2 minutes ago                my_app

$ docker rename my_app my_nginx
CONTAINER ID   IMAGE     COMMAND                   CREATED          STATUS                          PORTS     NAMES
e2a199060f07   nginx     "/docker-entrypoint.…"   2 minutes ago    Exited (0) About a minute ago             my_nginx

使用説明:

重新命名一個容器。

stats

使用方法:

$ docker stats [OPTIONS] [CONTAINER...]

例子:

$ docker stats my_app
CONTAINER ID   NAME      CPU %     MEM USAGE / LIMIT   MEM %     NET I/O   BLOCK I/O   PIDS 
e2a199060f07   my_app    0.00%     0B / 0B             0.00%     0B / 0B   0B / 0B     0 

使用説明:

實時顯示容器資源使用監控指標。

update

使用方法:

$ docker update [OPTIONS] CONTAINER [CONTAINER...]

例子:

$ docker update --memory 512m --memory-swap 1g my_app
my_app

$ docker inspect --format='{{.HostConfig.Memory}} {{.HostConfig.MemorySwap}}' my_app
536870912 1073741824

使用説明:

更新一或多個容器實例的 IO、CPU、內存,啓動策略參數。

exec

使用方法:

$ docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

例子:

#啟動容器
$ docker run -d --name my_app nginx
#在容器中執行命令
$ docker exec my_app ls /usr/share/nginx/html
50x.html
index.html

使用説明:

在運行中容器中運行命令。

deploy

使用方法:

$ docker deploy [OPTIONS] STACK

例子:

# 初始化 Docker Swarm
$ docker swarm init
# 使用 `cat` 命令來創建文件,這樣可以避免轉義問題
$ cat <<EOF > docker-compose.yml version: '3' services: web: image: nginx ports: - "8080:80" db: image: mysql environment: MYSQL_ROOT_PASSWORD: example EOF

# 部署堆棧
$ docker stack deploy -c docker-compose.yml my_stack
Since --detach=false was not specified, tasks will be created in the background.
In a future release, --detach=false will become the default.
Creating network my_stack_default
Creating service my_stack_web
Creating service my_stack_db
# 查看堆棧服務
$ docker stack services my_stack
ID             NAME           MODE         REPLICAS   IMAGE          PORTS
169600uhwd8b   my_stack_db    replicated   1/1        mysql:latest   
oqjvfperovbd   my_stack_web   replicated   1/1        nginx:latest   *:8080->80/tcp
# 刪除堆棧
$ docker stack rm my_stack

使用説明:

命令用於在 Docker Swarm 模式下部署一個應用堆棧(stack)。這個命令通常與 Docker Compose 文件一起使用(當前使用趨勢來看,Compose 成為默認標準),以便在 Swarm 集群中創建和管理多個服務。

[!quote] Docker Swarm
Docker Swarm 模式是 Docker 的原生集群管理工具,允許用戶將多個 Docker 主機組織成一個虛擬的 Docker 主機集群。這樣可以實現容器的高可用性、負載均衡和擴展性。

create

使用方法:

$ docker create [OPTIONS] IMAGE [COMMAND] [ARG...]

例子:

$ docker create --name my_nginx -p 8080:80 nginx
# 查看創建的容器
$ docker ps -a
# 啟動容器
$ docker start my_nginx

使用説明:

這是一個重要的命令,可以創建容器但並不執行它。

日誌信息相關

events

使用方法:

$ docker events [OPTIONS]

例子:

# 在終端1執行
$ docker events
# 在終端2創建一個容器
$ docker run -d --name my_nginx nginx
# 切換至終端1
2025-03-19T18:15:51.389472422+08:00 container create 87c319a3aa536efeb5125d8e4f722d9d657cb13a45035e9ba850628cafe0bb0f (image=nginx, maintainer=NGINX Docker Maintainers <docker-maint@nginx.com>, name=my_nginx2)
2025-03-19T18:15:51.505517765+08:00 network connect 8c48e335584333978d62354f0fcbed023c80ddcf30a271108b900ca7fd7df346 (container=87c319a3aa536efeb5125d8e4f722d9d657cb13a45035e9ba850628cafe0bb0f, name=bridge, type=bridge)
2025-03-19T18:15:51.510557708+08:00 container start 87c319a3aa536efeb5125d8e4f722d9d657cb13a45035e9ba850628cafe0bb0f (image=nginx, maintainer=NGINX Docker Maintainers <docker-maint@nginx.com>, name=my_nginx2)

使用説明:

印出容器實時的系統事件。

history

使用方法:

$ docker history [OPTIONS] IMAGE

例子:

$ docker history nginx
IMAGE          CREATED       CREATED BY                                       SIZE      COMMENT
2c9168b3c9a8   5 weeks ago   CMD ["nginx" "-g" "daemon off;"]                 0B        buildkit.dockerfile.v0
<missing>      5 weeks ago   STOPSIGNAL SIGQUIT                               0B        buildkit.dockerfile.v0
<missing>      5 weeks ago   EXPOSE map[80/tcp:{}]                            0B        buildkit.dockerfile.v0
<missing>      5 weeks ago   ENTRYPOINT ["/docker-entrypoint.sh"]             0B        buildkit.dockerfile.v0
<missing>      5 weeks ago   COPY 30-tune-worker-processes.sh /docker-ent…   4.62kB    buildkit.dockerfile.v0
<missing>      5 weeks ago   COPY 20-envsubst-on-templates.sh /docker-ent…   3.02kB    buildkit.dockerfile.v0
<missing>      5 weeks ago   COPY 15-local-resolvers.envsh /docker-entryp…   389B      buildkit.dockerfile.v0
<missing>      5 weeks ago   COPY 10-listen-on-ipv6-by-default.sh /docker…   2.12kB    buildkit.dockerfile.v0
<missing>      5 weeks ago   COPY docker-entrypoint.sh / # buildkit           1.62kB    buildkit.dockerfile.v0
<missing>      5 weeks ago   RUN /bin/sh -c set -x     && groupadd --syst…   100MB     buildkit.dockerfile.v0
<missing>      5 weeks ago   ENV DYNPKG_RELEASE=1~bookworm                    0B        buildkit.dockerfile.v0
<missing>      5 weeks ago   ENV PKG_RELEASE=1~bookworm                       0B        buildkit.dockerfile.v0
<missing>      5 weeks ago   ENV NJS_RELEASE=1~bookworm                       0B        buildkit.dockerfile.v0
<missing>      5 weeks ago   ENV NJS_VERSION=0.8.9                            0B        buildkit.dockerfile.v0
<missing>      5 weeks ago   ENV NGINX_VERSION=1.27.4                         0B        buildkit.dockerfile.v0
<missing>      5 weeks ago   LABEL maintainer=NGINX Docker Maintainers <d…   0B        buildkit.dockerfile.v0
<missing>      5 weeks ago   # debian.sh --arch 'arm64' out/ 'bookworm' '…   97.1MB    debuerreotype 0.15
# 自定義輸出格式
$ docker history --format '{{.ID}}: {{.CreatedAt}}' nginx
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00
<missing>: 2025-02-06T05:27:16+08:00

使用説明:

印出指定 Image 中每一層 Image 命令行的歷史記錄。

logs

使用方法:

$ docker logs CONTAINER

例子:

$ docker logs my_app
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Sourcing /docker-entrypoint.d/15-local-resolvers.envsh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2025/03/19 09:56:32 [notice] 1#1: using the "epoll" event method
2025/03/19 09:56:32 [notice] 1#1: nginx/1.27.4
2025/03/19 09:56:32 [notice] 1#1: built by gcc 12.2.0 (Debian 12.2.0-14) 
2025/03/19 09:56:32 [notice] 1#1: OS: Linux 5.14.0-503.14.1.el9_5.aarch64
2025/03/19 09:56:32 [notice] 1#1: getrlimit(RLIMIT_NOFILE): 1073741816:1073741816
2025/03/19 09:56:32 [notice] 1#1: start worker processes
2025/03/19 09:56:32 [notice] 1#1: start worker process 29
2025/03/19 09:56:32 [notice] 1#1: start worker process 30

使用説明:

批量印出出容器中進程的運行日誌。

Hub服務相關

login/ logout

使用方法:

$ docker login [OPTIONS] [SERVER]
$ docker logout [SERVER]

例子:

# 登錄
$ docker login -u chukuo -p password
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your credentials are stored unencrypted in '/root/.docker/config.json'.
Configure a credential helper to remove this warning. See
https://docs.docker.com/go/credential-store/
Login Succeeded
# 登出
$ docker logout
Removing login credentials for https://index.docker.io/v1/

使用説明:

登錄及登出 Docker Hub 服務。

push/pull

使用方法:

$ docker push NAME[:TAG]

例子:

事前準備,安裝Java環境

# 匯入了 GPG 密鑰
$ sudo rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-Rocky-9
# 清除快取
$ sudo dnf clean all
$ sudo dnf makecache
# 更新系統
$ sudo dnf update
# 安裝JDK
$ sudo dnf install java-17-openjdk-devel
# 確認Java版本
$ java -version

push

# 創建 `HelloWorld.java` 文件
$ cat <<EOF > HelloWorld.java
public class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, Docker!");
    }
}
EOF
# 創建 `MANIFEST.MF` 文件
$ cat <<EOF > MANIFEST.MF
Main-Class: HelloWorld
EOF
# 編譯並打包為 JAR 文件
$ javac HelloWorld.java && jar cfm HelloWorld.jar MANIFEST.MF HelloWorld.class
$ 運行 JAR 文件
$ java -jar HelloWorld.jar
Hello, Docker!
# 創建 Dockerfile
$ cat <<EOF > Dockerfile
FROM openjdk:17-slim
WORKDIR /app
COPY HelloWorld.jar .
CMD ["java", "-jar", "HelloWorld.jar"]
EOF
# 構建 Docker 映像
$ docker build -t chukuo/helloworld:1.0 .
[+] Building 2.1s (9/9) FINISHED                                                                        docker:default
 => [internal] load build definition from Dockerfile                                                              0.0s
 => => transferring dockerfile: 195B                                                                              0.0s
 => [internal] load metadata for docker.io/library/openjdk:11-jre-slim                                            2.0s
 => [auth] library/openjdk:pull token for registry-1.docker.io                                                    0.0s
 => [internal] load .dockerignore                                                                                 0.0s
 => => transferring context: 2B                                                                                   0.0s
 => [1/3] FROM docker.io/library/openjdk:11-jre-slim@sha256:93af7df2308c5141a751c4830e6b6c5717db102b3b31f012ea29  0.0s
 => [internal] load build context                                                                                 0.0s
 => => transferring context: 94B                                                                                  0.0s
 => CACHED [2/3] WORKDIR /app                                                                                     0.0s
 => CACHED [3/3] COPY HelloWorld.jar .                                                                            0.0s
 => exporting to image                                                                                            0.0s
 => => exporting layers                                                                                           0.0s
 => => writing image sha256:fcce31d8e888eac286795f55b357d731822f80ec75720dc692e86a47dc449bd5                      0.0s
 => => naming to docker.io/chukuo/helloworld:1.0  
# 登錄到 Docker Hub
$ docker login -u chukuo -p password
# 推送映像到 Docker Hub
$ docker push chukuo/helloworld:1.0
The push refers to repository [docker.io/chukuo/helloworld]
50133d9fa271: Pushed 
455dfcf66c0a: Pushed 
095c43b397b5: Pushed 
c6494d1aa307: Pushed 
392801f05f02: Pushed 
e4f85c7c2b1f: Pushed 
1.0: digest: sha256:89d19946db94f34c4100d6890cbc6d0c7d425d3beddb5b2c20bc3f5c9da1dcf4 size: 1553732ae3df
# 確保images不存在,如果存在則刪除
$ docker rmi chukuo/helloworld:1.0
Untagged: chukuo/helloworld:1.0
Untagged: chukuo/helloworld@sha256:89d19946db94f34c4100d6890cbc6d0c7d425d3beddb5b2c20bc3f5c9da1dcf4
# 拉取
$ docker pull chukuo/helloworld:1.0
1.0: Pulling from chukuo/helloworld
Digest: sha256:89d19946db94f34c4100d6890cbc6d0c7d425d3beddb5b2c20bc3f5c9da1dcf4
Status: Downloaded newer image for chukuo/helloworld:1.0
docker.io/chukuo/helloworld:1.0
# 查詢
$ docker images chukuo/helloworld:1.0
REPOSITORY          TAG       IMAGE ID       CREATED          SIZE
chukuo/helloworld   1.0       fcce31d8e888   12 minutes ago   216MB
# 執行
$ docker build -t my_helloworld_image . && docker run my_helloworld_image
[+] Building 1.1s (8/8) FINISHED     
# ... 構建過程(略)
Hello, Docker!

使用説明:

通過此命令分享 Image 到 Hub 服務或者自服務的 Registry 服務。

使用方法:

$ docker search TERM

例子:

$ docker search chukuo/helloworld
NAME                                  DESCRIPTION                                      STARS     OFFICIAL
chukuo/helloworld                                                                      0         
testcontainers/helloworld             A Docker image to support Testcontainers' se…   7         
istio/examples-helloworld-v1          This image is used for Istio samples.            1         
istio/examples-helloworld-v2          This image is used for Istio samples.            0         
apache/causeway-app-helloworld        Apache Causeway App Helloworld                   0         
seabreeze/sbz-helloworld              A HelloWorld example to run on SeaBreeze.        1         
seabreeze/sbz-helloworld-sidecar      Sidecar hello world example for SeaBreeze.       0         
nimak/helloworld                                                                       0         
karthequian/helloworld                A simple helloworld nginx container to get y…   19        
wouterm/helloworld                     A simple Docker image with an Nginx server …   1         
seabreeze/azure-mesh-helloworld       Azure Service Fabric Mesh HelloWorld!            1         
strm/helloworld-http                  A hello world container for testing http bal…   10        
openhorizon/ibm.helloworld_amd64                                                       0         
buoyantio/helloworld                                                                   4         
agrawals18/helloworld                                                                  0         
saturnism/spring-boot-helloworld-ui                                                    5         
yiliao/aci-helloworld                                                                  1         
hakanssonlasse/helloworld                                                              1         
isaactl/helloworld                                                                     0         
tekstac/aci-helloworld                                                                 0         
containerinstance/helloworld          Demo image for SSL connection inside Node.js     0         
moseers/helloworld                                                                     0         
ibmcom/helloworld                     A sample used by IBM Cloud Code Engine           2         
neilpeterson/aks-helloworld                                                            0         
bihero/helloworld                                                                      0         
[aaron@localhost ~]$ docker search chukuo/helloworld
NAME                                  DESCRIPTION                                      STARS     OFFICIAL
chukuo/helloworld                                                                      0         
testcontainers/helloworld             A Docker image to support Testcontainers' se…   7         
istio/examples-helloworld-v1          This image is used for Istio samples.            1         
istio/examples-helloworld-v2          This image is used for Istio samples.            0         
apache/causeway-app-helloworld        Apache Causeway App Helloworld                   0         
seabreeze/sbz-helloworld              A HelloWorld example to run on SeaBreeze.        1         
seabreeze/sbz-helloworld-sidecar      Sidecar hello world example for SeaBreeze.       0         
nimak/helloworld                                                                       0         
karthequian/helloworld                A simple helloworld nginx container to get y…   19        
wouterm/helloworld                     A simple Docker image with an Nginx server …   1         
seabreeze/azure-mesh-helloworld       Azure Service Fabric Mesh HelloWorld!            1         
strm/helloworld-http                  A hello world container for testing http bal…   10        
openhorizon/ibm.helloworld_amd64                                                       0         
buoyantio/helloworld                                                                   4         
agrawals18/helloworld                                                                  0         
saturnism/spring-boot-helloworld-ui                                                    5         
yiliao/aci-helloworld                                                                  1         
hakanssonlasse/helloworld                                                              1         
isaactl/helloworld                                                                     0         
containerinstance/helloworld          Demo image for SSL connection inside Node.js     0         
tekstac/aci-helloworld                                                                 0         
moseers/helloworld                                                                     0         
ibmcom/helloworld                     A sample used by IBM Cloud Code Engine           2         
neilpeterson/aks-helloworld                                                            0         
bihero/helloworld                                                                      0         

使用説明:

通過關鍵字搜索Docker Hub分享的 Image。


5. 實際案例分享 (3分鐘)

  • 分享一個簡單的Docker應用案例

[!tip] GitHub Java微服務Docker demo 專案
這個專案包含了完整的Docker應用案例。您可以根據之前學到的步驟進行設置和運行,並在本地環境中練習如何使用Java微服務,透過Docker創建的容器來查詢商品項目。詳細資訊可以瀏覽我專案的README,GitHub網址:chukuolung/docker-demo

6. 開放問答 (2分鐘)

  • 開放問題與討論

重點

  1. Docker背景與重要性:強調Docker作為開源應用打包運行時引擎的角色及其業界支持。
  2. 環境建置:介紹Docker的系統需求,推薦在Linux平台上安裝,並提供安裝步驟。
  3. 核心概念:解釋鏡像、容器和倉庫的定義及其功能。
  4. 指令操作:詳細說明Docker指令的使用,包括環境信息、系統運維和日誌信息等。
  5. 實際案例:分享簡單的Docker應用案例,鼓勵讀者進行實踐。