Docker學習
1. Docker概念
1.1 Docker基本概念
Docker 是一個開源的應用容器引擎,讓開發者可以打包他們的應用以及依賴包到一個可移植的容器中,然后發布到任何流行的Linux或Windows操作系統的機器上,也可以實現虛擬化,容器是完全使用沙箱機制,相互之間不會有任何接口。
Linux操作系統本身從系統層面就支持虛擬化技術LXC,LXC有三大特色:
-
cgroup
Linux Cgroups (Control Groups )提供了對組進程及將來子進程的資源限制、控制和統計的能力,這些資源包括 CPU、內存、存儲、網絡等 通過 Cgroups ,可以方便地限制某個進程的資源占用,並且可以實時地監控進程的監控和統計信息
-
namespace
Linux Namespace是Kernel的一個功能,它可以隔離一系列的系統資源,比如PID、UserID、Netwokr等。
-
unionFS
Union File System(UnionFS): 將其他文件系統聯合到一個聯合掛載點的文件系統服務。它使用branch把不同文件系統的文件和目錄透明的覆蓋,形成一個單一一致的文件系統,當對這個聯合文件系統進行寫操作時,系統是真正寫到了一個新的文件中,這個虛擬后的聯合文件系統是可以對任何文件進行操作的,但是它並沒有改變原來的文件,因為unionfs用到了一個重要的資源管理技術,叫做寫時復制。
寫時復制(Copy-on-write,CoW): 是一種對可修改的資源實現高校復制的資源管理技術。它的思想是,如果一個資源是重復的沒有任何修改,這時並不需要立即創建一個新的資源,這個資源可以被新舊實例共享。創建新資源發生在第一次寫操作,也就是對資源進行修改的時候。通過這種資源共享的方式,可以顯著地減少未修改資源復制帶來的消耗,但是資源也會在進行資源修改時增加小部分的開銷。
1.2 虛擬化技術
1.2.1 虛擬化分類
-
SaaS(軟件即服務)
SaaS,是Software-as-a-Service的縮寫名稱,意思為軟件即服務,即通過網絡提供軟件服務;簡單來說用戶需要使用某款軟件直接雙擊進行運行,無需對軟件進行下載安裝等等。由SaaS進行提供,例如Office365
- 各互聯網的應用
-
PaaS(平台即服務)
PaaS是(Platform as a Service)的縮寫,是指平台即服務。 把服務器平台作為一種服務提供的商業模式,通過網絡進行程序提供的服務稱之為SaaS;簡單來說就是通過互聯網提供:(虛擬化)硬件+(各種)軟件環境平台,例如做開發無需自行構建系統+編譯環境,由PaaS進行提供。
- Docker
- LXC
- OpenShitf
-
IaaS(基礎設施即服務)
IaaS(Infrastructure as a Service),即基礎設施即服務。指把IT基礎設施作為一種服務通過網絡對外提供;簡單來說就是通過網絡向用戶提供一套基礎的硬件設施(CPU、內存、主板、網卡.....)。常見的如阿里雲的雲服務器,在購買時選擇各種的硬件配置...
- 阿里雲ECS
1.2.2 傳統虛擬化與容器
-
傳統虛擬技術:
通過虛擬化技術模擬出一整套硬件設施,然后在此基礎上安裝一套完整的操作系統,並在這個系統上面安裝和運行軟件
-
容器技術:
直接運行在宿主機的內核,容器是沒有自己的內核;每個容器都是互相隔離互不影響,每個容器都有自己的文件系統
2. Docker安裝部署
2.1 Docker的基本組成
- 倉庫(Repository):
- 用於存放鏡像的地方;
- 倉庫分類:
- 公有倉庫:Docker_Hub、阿里雲等
- 私有倉庫:自行創建
- 鏡像(Image):
- Docker鏡像類似一個模板,可以通過模板進行創建容器
- 一個鏡像可以創建多個容器
- 容器(Container):
- 利用容器技術,獨立運行一個或一組應用,通過鏡像來進行創建
2.2 Docker安裝
2.2.1 准備系統環境
- 操作系統
- 操作系統:RedHat8.4(CentOS亦可)
- CPU:x4
- 內存:4GB
- 內核:4.18.0-305.el8.x86_64
[root@node1 ~]# uname -a
Linux node1 4.18.0-305.el8.x86_64 #1 SMP Thu Apr 29 08:54:30 EDT 2021 x86_64 x86_64 x86_64 GNU/Linux
[root@node1 ~]# cat /etc/redhat-release
Red Hat Enterprise Linux release 8.4 (Ootpa)
[root@node1 ~]# free -h
total used free shared buff/cache available
Mem: 3.6Gi 327Mi 3.0Gi 9.0Mi 285Mi 3.1Gi
Swap: 2.0Gi 0B 2.0Gi
[root@node1 ~]# lscpu | grep Core
Core(s) per socket: 4
2.2.2 卸載舊版本
如果有安裝舊版本先進行卸載,我這是全新的系統所以不用執行以下操作
[root@node1 ~]# dnf remove docker\
docker-client\
docker-client-latest\
docker-common\
docker-latest\
docker-logrotate\
docker-engine
Updating Subscription Management repositories.
Unable to read consumer identity
This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register.
No match for argument: dockerdocker-clientdocker-client-latestdocker-commondocker-latestdocker-logrotatedocker-engine
No packages marked for removal.
Dependencies resolved.
Nothing to do.
Complete!
[root@node1 ~]#
2.2.3 安裝方式
Docker的安裝方法有主要有3中,本文檔主要介紹在線安裝
- 設置Docker的存儲庫並從中進行安裝,以便后續進行升級
- 下載RPM包進行手動安裝或升級,在無法訪問互聯網的情況下使用
- 在特殊環境中使用自動化進行安裝Docker
2.2.4 使用存儲庫進行在線安裝
-
設置存儲庫
由於國外鏡像站速度雞肋,這里我們使用阿里雲的鏡像
[root@node1 ~]# wget -O /etc/yum.repos.d/docker-ce.repo https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo --2021-12-09 01:38:19-- https://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo Resolving mirrors.aliyun.com (mirrors.aliyun.com)... 110.188.28.225, 110.188.28.226, 110.188.28.230, ... Connecting to mirrors.aliyun.com (mirrors.aliyun.com)|110.188.28.225|:443... connected. HTTP request sent, awaiting response... 200 OK Length: 1919 (1.9K) [application/octet-stream] Saving to: ‘/etc/yum.repos.d/docker-ce.repo’ /etc/yum.repos.d/docker-ce.re 100%[=================================================>] 1.87K --.-KB/s in 0s 2021-12-09 01:38:19 (53.8 MB/s) - ‘/etc/yum.repos.d/docker-ce.repo’ saved [1919/1919] [root@node1 ~]# dnf makecache Updating Subscription Management repositories. Unable to read consumer identity This system is not registered to Red Hat Subscription Management. You can use subscription-manager to register. Docker CE Stable - x86_64 12 kB/s | 19 kB 00:01 Metadata cache created. [root@node1 ~]#
-
安裝Docker引擎
# 由於我的RedHat8.4存在Podman、cockpit等軟件包與Docker有沖突所以加了--allowerasing參數 [root@node1 ~]# dnf -y install docker-ce docker-ce-cli containerd.io --allowerasing ... Verifying : buildah-1.19.7-1.module+el8.4.0+10607+f4da7515.x86_64 6/9 Verifying : cockpit-podman-29-2.module+el8.4.0+10607+f4da7515.noarch 7/9 Verifying : podman-3.0.1-6.module+el8.4.0+10607+f4da7515.x86_64 8/9 Verifying : podman-catatonit-3.0.1-6.module+el8.4.0+10607+f4da7515.x86_64 9/9 Installed products updated. Installed: containerd.io-1.4.12-3.1.el8.x86_64 docker-ce-3:20.10.11-3.el8.x86_64 docker-ce-rootless-extras-20.10.11-3.el8.x86_64 libcgroup-0.41-19.el8.x86_64 Removed: buildah-1.19.7-1.module+el8.4.0+10607+f4da7515.x86_64 cockpit-podman-29-2.module+el8.4.0+10607+f4da7515.noarch podman-3.0.1-6.module+el8.4.0+10607+f4da7515.x86_64 podman-catatonit-3.0.1-6.module+el8.4.0+10607+f4da7515.x86_64 Complete! [root@node1 ~]#
-
啟動並設置Docker為開機自啟
[root@node1 ~]# systemctl enable --now docker Created symlink /etc/systemd/system/multi-user.target.wants/docker.service → /usr/lib/systemd/system/docker.service. [root@node1 ~]#
-
查看Docker版本
[root@node1 ~]# docker version Client: Docker Engine - Community Version: 20.10.11 API version: 1.41 Go version: go1.16.9 Git commit: dea9396 Built: Thu Nov 18 00:36:58 2021 OS/Arch: linux/amd64 Context: default Experimental: true Server: Docker Engine - Community Engine: Version: 20.10.11 API version: 1.41 (minimum version 1.12) Go version: go1.16.9 Git commit: 847da18 Built: Thu Nov 18 00:35:20 2021 OS/Arch: linux/amd64 Experimental: false containerd: Version: 1.4.12 GitCommit: 7b11cfaabd73bb80907dd23182b9347b4245eb5d runc: Version: 1.0.2 GitCommit: v1.0.2-0-g52b36a2 docker-init: Version: 0.19.0 GitCommit: de40ad0 [root@node1 ~]#
-
測試Docker
[root@node1 ~]# docker run hello-world Unable to find image 'hello-world:latest' locally latest: Pulling from library/hello-world 2db29710123e: Pull complete Digest: sha256:cc15c5b292d8525effc0f89cb299f1804f3a725c8d05e158653a563f15e4f685 Status: Downloaded newer image for hello-world:latest Hello from Docker! # 此消息顯示您的安裝似乎工作正常。 This message shows that your installation appears to be working correctly. # 為了生成此消息,Docker采取了以下步驟: To generate this message, Docker took the following steps: # Docker客戶端已聯系Docker守護程序。 1. The Docker client contacted the Docker daemon. # Docker守護進程從Docker中心提取“hello world”映像。(amd64) 2. The Docker daemon pulled the "hello-world" image from the Docker Hub. (amd64) # Docker守護進程從運行生成當前正在讀取的輸出的可執行文件。 3. The Docker daemon created a new container from that image which runs the executable that produces the output you are currently reading. # Docker守護進程將該輸出流式傳輸到Docker客戶端,后者將其發送到你的終點站 4. The Docker daemon streamed that output to the Docker client, which sent it to your terminal. To try something more ambitious, you can run an Ubuntu container with: $ docker run -it ubuntu bash Share images, automate workflows, and more with a free Docker ID: https://hub.docker.com/ For more examples and ideas, visit: https://docs.docker.com/get-started/ [root@node1 ~]#
2.3 卸載Docker
如需卸載請按照如下步驟
-
卸載 Docker Engine、CLI 和 Containerd 包:
dnf -y remove docker-ce docker-ce-cli containerd.io
-
主機上的映像、容器、卷或自定義配置文件不會自動刪除。刪除所有鏡像、容器和卷:
rm -rf /var/lib/docker rm -rf /var/lib/containerd
3. Docker命令
掌握本圖片的命令以及常用參數算是掌握Docker常用操作了
-
幫助命令
docker version # 顯示版本信息 docker info # 顯示docker系統詳細信息 docker 命令 --help # 顯示命令的詳細幫助
-
docker命令
[root@node1 ~]# docker #docker命令格式 #docker [可選選項] 命令 Usage: docker [OPTIONS] COMMAND A self-sufficient runtime for containers # 選項 Options: # 客戶端配置文件地址(默認在"/root/.docker") --config string Location of client config files (default "/root/.docker") # 用於連接到守護進程的上下文的名稱 -c, --context string Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use") # 開啟調試模式 -D, --debug Enable debug mode # 連接到的守護程序套接字 -H, --host list Daemon socket(s) to connect to # 設置日志記錄級別(“調試”|“信息”|“警告”|“錯誤”|“致命”)(默認為“信息”) -l, --log-level string Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info") # 使用TLS證書 --tls Use TLS; implied by --tlsverify # 僅由此CA簽署的信任證書 --tlscacert string Trust certs signed only by this CA (default "/root/.docker/ca.pem") # TLS證書文件的路徑(默認在"/root/.docker/cert.pem") --tlscert string Path to TLS certificate file (default "/root/.docker/cert.pem") # TLS密鑰文件的路徑(默認在"/root/.docker/key.pem") --tlskey string Path to TLS key file (default "/root/.docker/key.pem") # 使用TLS並驗證遠程 --tlsverify Use TLS and verify the remote # 打印版本信息並退出 -v, --version Print version information and quit # 管理命令 Management Commands: app* Docker App (Docker Inc., v0.9.1-beta3) # Docker應用 builder Manage builds # 管理構建 buildx* Build with BuildKit (Docker Inc., v0.6.3-docker) # 使用BuildKit構建 config Manage Docker configs # 管理Docker配置 container Manage containers #管理容器 context Manage contexts # 管理上下文 image Manage images # 管理鏡像 manifest Manage Docker image manifests and manifest lists # 管理Docker映像清單和清單列表 network Manage networks # 管理網絡 node Manage Swarm nodes # 管理群集節點 plugin Manage plugins # 管理插件 scan* Docker Scan (Docker Inc., v0.9.0) # Docker掃描 secret Manage Docker secrets # 管理Docker機密 service Manage services # 管理服務 stack Manage Docker stacks # 管理Docker堆棧 swarm Manage Swarm # 管理群集 system Manage Docker # 管理Docker trust Manage trust on Docker images # 管理對Docker映像的信任 volume Manage volumes # 管理卷 # 命令 Commands: # 將本地標准輸入、輸出和錯誤流附加到正在運行的容器 attach Attach local standard input, output, and error streams to a running container build Build an image from a Dockerfile # 從Dockerfile生成映像 commit Create a new image from a container's changes # 根據容器的更改創建新圖像 # 在容器和本地文件系統之間復制文件/文件夾 cp Copy files/folders between a container and the local filesystem create Create a new container # 創建一個新容器 # 檢查對容器文件系統上的文件或目錄的更改 diff Inspect changes to files or directories on a container's filesystem events Get real time events from the server # 從服務器獲取實時事件 exec Run a command in a running container # 在正在運行的容器中運行命令 export Export a container's filesystem as a tar archive # 將容器的文件系統導出為tar歸檔 history Show the history of an image # 顯示鏡像的歷史記錄 images List images # 列出鏡像 import Import the contents from a tarball to create a filesystem image # 從tarball導入內容以創建文件系統映像 info Display system-wide information # 顯示系統范圍的信息 inspect Return low-level information on Docker objects # 返回有關Docker對象的低級信息 kill Kill one or more running containers # 殺死一個或多個正在運行的容器 load Load an image from a tar archive or STDIN # 從tar存檔或STDIN加載鏡像 login Log in to a Docker registry # 登錄到Docker注冊表 logout Log out from a Docker registry # 從Docker注冊表注銷 logs Fetch the logs of a container # 獲取容器的日志 pause Pause all processes within one or more containers # 暫停一個或多個容器中的所有進程 port List port mappings or a specific mapping for the container # 列出容器的端口映射或特定映射 ps List containers # 列出容器 pull Pull an image or a repository from a registry # 從注冊表中提取鏡像或存儲庫 push Push an image or a repository to a registry # 將鏡像或存儲庫推送到注冊表 rename Rename a container # 重命名容器 restart Restart one or more containers # 重新啟動一個或多個容器 rm Remove one or more containers # 移除一個或多個容器 rmi Remove one or more images # 刪除一個或多個鏡像 run Run a command in a new container # 在新容器中運行命令 # 將一個或多個鏡像保存到tar存檔(默認情況下流式傳輸到stdout) save Save one or more images to a tar archive (streamed to STDOUT by default) search Search the Docker Hub for images # 在Docker Hub中搜索鏡像 start Start one or more stopped containers # 啟動一個或多個停止的容器 stats Display a live stream of container(s) resource usage statistics # 顯示容器資源使用統計信息的實時流 stop Stop one or more running containers # 停止一個或多個正在運行的容器 tag Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE # 創建引用源鏡像的標記目標鏡像;給鏡像打標簽 top Display the running processes of a container # 顯示容器的運行進程 unpause Unpause all processes within one or more containers # 取消暫停一個或多個容器中的所有進程 update Update configuration of one or more containers # 更新一個或多個容器的配置 version Show the Docker version information # 顯示Docker版本信息 # 阻止,直到一個或多個容器停止,然后打印其出口代碼 wait Block until one or more containers stop, then print their exit codes # 有關命令的詳細信息,請運行“docker 命令 --help”。 Run 'docker COMMAND --help' for more information on a command. [root@node1 ~]#
3.1 鏡像命令
-
docker images
查詢本地所有的鏡像
[root@node1 ~]# docker images # 存儲庫 標簽 鏡像ID 創建時間 大小 REPOSITORY TAG IMAGE ID CREATED SIZE hello-world latest feb5d9fea6a5 2 months ago 13.3kB [root@node1 ~]# docker images --help Usage: docker images [OPTIONS] [REPOSITORY[:TAG]] List images Options: -a, --all Show all images (default hides intermediate images) # 顯示所有鏡像 --digests Show digests # 顯示摘要 -f, --filter filter Filter output based on conditions provided --format string Pretty-print images using a Go template # 根據提供的條件篩選輸出 --no-trunc Don't truncate output # 不要截斷輸出 -q, --quiet Only show image IDs # 僅顯示鏡像ID [root@node1 ~]#
-
docker search
搜索鏡像命令
[root@node1 ~]# docker search nginx #鏡像名稱 描述 星星 正式的 自動化 NAME DESCRIPTION STARS OFFICIAL AUTOMATED nginx Official build of Nginx. 15928 [OK] jwilder/nginx-proxy Automated Nginx reverse proxy for docker con… 2101 [OK] richarvey/nginx-php-fpm Container running Nginx + PHP-FPM capable of… 820 [OK] jc21/nginx-proxy-manager Docker container for managing Nginx proxy ho… 288 linuxserver/nginx An Nginx container, brought to you by LinuxS… 160 tiangolo/nginx-rtmp Docker image with Nginx using the nginx-rtmp… 147 [OK] jlesage/nginx-proxy-manager Docker container for Nginx Proxy Manager 145 [OK] alfg/nginx-rtmp NGINX, nginx-rtmp-module and FFmpeg from sou… 111 [OK] nginxdemos/hello NGINX webserver that serves a simple page co… 79 [OK] privatebin/nginx-fpm-alpine PrivateBin running on an Nginx, php-fpm & Al… 61 [OK] nginx/nginx-ingress NGINX and NGINX Plus Ingress Controllers fo… 57 nginxinc/nginx-unprivileged Unprivileged NGINX Dockerfiles 55 nginxproxy/nginx-proxy Automated Nginx reverse proxy for docker con… 29 staticfloat/nginx-certbot Opinionated setup for automatic TLS certs lo… 25 [OK] nginx/nginx-prometheus-exporter NGINX Prometheus Exporter for NGINX and NGIN… 22 schmunk42/nginx-redirect A very simple container to redirect HTTP tra… 19 [OK] centos/nginx-112-centos7 Platform for running nginx 1.12 or building … 16 centos/nginx-18-centos7 Platform for running nginx 1.8 or building n… 13 bitwarden/nginx The Bitwarden nginx web server acting as a r… 11 flashspys/nginx-static Super Lightweight Nginx Image 11 [OK] mailu/nginx Mailu nginx frontend 9 [OK] sophos/nginx-vts-exporter Simple server that scrapes Nginx vts stats a… 7 [OK] ansibleplaybookbundle/nginx-apb An APB to deploy NGINX 3 [OK] wodby/nginx Generic nginx 1 [OK] arnau/nginx-gate Docker image with Nginx with Lua enabled on … 1 [OK] [root@node1 ~]# docker search --help Usage: docker search [OPTIONS] TERM Search the Docker Hub for images Options: -f, --filter filter Filter output based on conditions provided # 根據提供的條件篩選輸出 --format string Pretty-print search using a Go template --limit int Max number of search results (default 25) # 最大搜索結果數(默認值25) --no-trunc Don't truncate output # 不要截斷輸出 [root@node1 ~]# docker search tomcat -f STARS=1000 # 根據條件進行篩選 NAME DESCRIPTION STARS OFFICIAL AUTOMATED tomcat Apache Tomcat is an open source implementati… 3193 [OK] [root@node1 ~]#
-
docker pull
下載鏡像
[root@node1 ~]# docker pull "docker pull" requires exactly 1 argument. See 'docker pull --help'. Usage: docker pull [OPTIONS] NAME[:TAG|@DIGEST] Pull an image or a repository from a registry [root@node1 ~]# docker pull --help #用法: docker pull [選項] NAME[:Tag|@DIGEST] # []表示可選可不選 Usage: docker pull [OPTIONS] NAME[:TAG|@DIGEST] Pull an image or a repository from a registry Options: -a, --all-tags Download all tagged images in the repository # 下載存儲庫中所有標記的鏡像 --disable-content-trust Skip image verification (default true) # 跳過鏡像驗證(默認為開啟) # 如果服務器支持多平台,則設置平台 --platform string Set platform if server is multi-platform capable -q, --quiet Suppress verbose output # 抑制詳細輸出 [root@node1 ~]# [root@node1 ~]# docker pull mysql Using default tag: latest # 使用默認標記:最新 latest: Pulling from library/mysql # 最新版本:從庫/mysql中提取 ffbb094f4f9e: Pull complete # 分層下載,Docker的核心,聯合文件系統 df186527fc46: Pull complete fa362a6aa7bd: Pull complete 5af7cb1a200e: Pull complete 949da226cc6d: Pull complete bce007079ee9: Pull complete eab9f076e5a3: Pull complete 8a57a7529e8d: Pull complete b1ccc6ed6fc7: Pull complete b4af75e64169: Pull complete 3aed6a9cd681: Pull complete 23390142f76f: Pull complete Digest: sha256:ff9a288d1ecf4397967989b5d1ec269f7d9042a46fc8bc2c3ae35458c1a26727 # 摘要校驗 Status: Downloaded newer image for mysql:latest # 狀態:已下載mysql的較新鏡像:最新 docker.io/library/mysql:latest # 真實地址 [root@node1 ~]# [root@node1 ~]# docker pull mysql:5.7 # 指定版本下載,一定是官方有支持的版本! 5.7: Pulling from library/mysql ffbb094f4f9e: Already exists # Already exists表示已經存在 df186527fc46: Already exists fa362a6aa7bd: Already exists 5af7cb1a200e: Already exists 949da226cc6d: Already exists bce007079ee9: Already exists eab9f076e5a3: Already exists c7b24c3f27af: Pull complete 6fc26ff6705a: Downloading [=============> ] 29.4MB/108.6MB 6fc26ff6705a: Pull complete bec5cdb5e7f7: Pull complete 6c1cb25f7525: Pull complete Digest: sha256:d1cc87a3bd5dc07defc837bc9084f748a130606ff41923f46dec1986e0dc828d Status: Downloaded newer image for mysql:5.7 docker.io/library/mysql:5.7 [root@node1 ~]#
-
docker images
查看本機鏡像
[root@node1 ~]# docker images #存儲庫 #標簽 #鏡像ID # 創建時間 # 大小 REPOSITORY TAG IMAGE ID CREATED SIZE mysql 5.7 738e7101490b 8 days ago 448MB mysql latest bbf6571db497 8 days ago 516MB hello-world latest feb5d9fea6a5 2 months ago 13.3kB [root@node1 ~]# [root@node1 ~]# docker images --help Usage: docker images [OPTIONS] [REPOSITORY[:TAG]] List images Options: # 顯示所有鏡像(默認隱藏中間鏡像) -a, --all Show all images (default hides intermediate images) --digests Show digests # 顯示摘要 -f, --filter filter Filter output based on conditions provided # 根據提供的條件篩選輸出 --format string Pretty-print images using a Go template # 使用Go模板打印鏡像 --no-trunc Don't truncate output # 不要截斷輸出 -q, --quiet Only show image IDs # 僅顯示鏡像ID
-
docker rmi
刪除鏡像
[root@node1 ~]# docker images # 查詢鏡像 REPOSITORY TAG IMAGE ID CREATED SIZE mysql 5.7 738e7101490b 8 days ago 448MB mysql latest bbf6571db497 8 days ago 516MB hello-world latest feb5d9fea6a5 2 months ago 13.3kB [root@node1 ~]# docker rmi 738 # 刪除鏡像id為738開頭的 Untagged: mysql:5.7 Untagged: mysql@sha256:d1cc87a3bd5dc07defc837bc9084f748a130606ff41923f46dec1986e0dc828d Deleted: sha256:738e7101490b45decf606211a5437ed87aa6a82f1ff03c354564bf9375ce20f9 Deleted: sha256:addad8cfeac97b96eb6652a576269346ac96def9a6709ed2388e24fff4345837 Deleted: sha256:e288c3439a7e2f423f50bf22979a759371c51a70bbbaa450993c336978460b1a Deleted: sha256:33ece15accaa3bb20e3dee84e2e4501469b917c3abba3d5475cd1fec8bb3e82c Deleted: sha256:6b15390bceeca8424d82e75f5c9aca5eb4693f96849d6382168a99747877693d [root@node1 ~]# docker images # 查詢鏡像發現鏡像id738開頭的mysql5.7已經被刪除了 REPOSITORY TAG IMAGE ID CREATED SIZE mysql latest bbf6571db497 8 days ago 516MB hello-world latest feb5d9fea6a5 2 months ago 13.3kB [root@node1 ~]# [root@node1 ~]# docker rmi --help Usage: docker rmi [OPTIONS] IMAGE [IMAGE...] Remove one or more images Options: -f, --force Force removal of the image # 強制刪除鏡像 --no-prune Do not delete untagged parents # 不要刪除未標記的父項
# 批量刪除所有鏡像 $(將查詢出鏡像作為rmi的輸入) [root@node1 ~]# docker rmi -f $(docker images -qa) Untagged: mysql:latest Untagged: mysql@sha256:ff9a288d1ecf4397967989b5d1ec269f7d9042a46fc8bc2c3ae35458c1a26727 Deleted: sha256:bbf6571db4977fe13c3f4e6289c1409fc6f98c2899eabad39bfe07cad8f64f67 Deleted: sha256:a72da99dce60d6f8d4c4cffa4173153c990537fcdfaa27c35324c3348d55dd5c Deleted: sha256:8b535d432ef2fbd45d93958347b2587c5cbe334f07d6909ad9d2d480ebbafb65 Deleted: sha256:14d13a3b33fc76839f156cd24b4636dab121e6d3d026cefa2985a4b89e9d4df8 Deleted: sha256:77c21a5a897a1ba752f3d742d6c94ee7c6b0e373fd0aeecc4bf88b9a3982007e Deleted: sha256:189162becec8bb4588c54fb4ea7e62d20121812e68aeb0291fb4bb5df9ec0985 Deleted: sha256:34980dadfd6a5bb9d7f9e8d4e408000e0a8f4840cc7d3092dc94357ebe7a89b6 Deleted: sha256:15b2beb64a91785c8f3709ecd2410d13577b3174faad164524434ce6a7633506 Deleted: sha256:e38dd14d47b61171927ea4b928f7296123b65a81ad1cfde8f5d00cadf1e81bbb Deleted: sha256:865abdfd8444741f581ce582e4ac5746c4a00c282febf65aa808a235ec7abf78 Deleted: sha256:b1e35233e1ac953bd06fc8fa83afb3a88c39c1aeae0c89a46cb1b652d6821b38 Deleted: sha256:3bcfdf6641227ff63e3ddf9e38e45cf317b178a50a664e45c6ae596107d5bc46 Deleted: sha256:f11bbd657c82c45cc25b0533ce72f193880b630352cc763ed0c045c808ff9ae1 Untagged: hello-world:latest Untagged: hello-world@sha256:cc15c5b292d8525effc0f89cb299f1804f3a725c8d05e158653a563f15e4f685 Deleted: sha256:feb5d9fea6a5e9606aa995e879d862b825965ba48de054caab5ef356dc6b3412 [root@node1 ~]# # 刪除多個鏡像 [root@node1 ~]# docker rmi 鏡像id1 鏡像id2 ...
3.2 容器命令
在創建容器之前,得先下載一個鏡像
[root@node1 ~]# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
a1d0c7532777: Pull complete
Digest: sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177
Status: Downloaded newer image for centos:latest
docker.io/library/centos:latest
[root@node1 ~]#
-
docker run
運行容器
[root@node1 ~]# docker run --help Usage: docker run [OPTIONS] IMAGE [COMMAND] [ARG...] Run a command in a new container Options: --add-host list Add a custom host-to-IP mapping (host:ip) # 添加自定義主機到IP映射(主機:IP) -a, --attach list Attach to STDIN, STDOUT or STDERR # 連接到標准輸入、標准輸出或標准輸出 # 塊IO(相對權重),介於10和1000之間,或0禁用(默認為0) --blkio-weight uint16 Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0) # 塊IO權重(相對設備權重)(默認值[]) --blkio-weight-device list Block IO weight (relative device weight) (default []) --cap-add list Add Linux capabilities # 添加Linux功能 --cap-drop list Drop Linux capabilities # 放棄Linux功能 --cgroup-parent string Optional parent cgroup for the container # 容器的可選父cgroup --cgroupns string Cgroup namespace to use (host|private) # 要使用的Cgroup命名空間(主機|專用) # 在Docker主機的cgroup命名空間中運行容器 'host': Run the container in the Docker host's cgroup namespace # 在其自己的私有cgroup命名空間中運行容器 'private': Run the container in its own private cgroup namespace # 使用由配置的cgroup命名空間守護進程上的默認cgroupns模式選項(默認) '': Use the cgroup namespace as configured by the default-cgroupns-mode option on the daemon (default) --cidfile string Write the container ID to the file # 將容器ID寫入文件 # 限制CPU CFS(完全公平調度程序)周期 --cpu-period int Limit CPU CFS (Completely Fair Scheduler) period # 限制CPU CFS(完全公平調度程序)配額 --cpu-quota int Limit CPU CFS (Completely Fair Scheduler) quota # 以微秒為單位限制CPU實時周期 --cpu-rt-period int Limit CPU real-time period in microseconds # 以微秒為單位限制CPU實時運行時間 --cpu-rt-runtime int Limit CPU real-time runtime in microseconds -c, --cpu-shares int CPU shares (relative weight) # CPU份額(相對權重) --cpus decimal Number of CPUs # CPU數量 --cpuset-cpus string CPUs in which to allow execution (0-3, 0,1) # 允許執行的CPU(0-3,0,1) --cpuset-mems string MEMs in which to allow execution (0-3, 0,1) # 允許執行的MEMs(0-3,0,1) -d, --detach Run container in background and print container ID # 在后台運行容器並打印容器ID # 覆蓋用於分離容器的鍵序列 --detach-keys string Override the key sequence for detaching a container # 將主機設備添加到容器中 --device list Add a host device to the container # 將規則添加到cgroup allowed devices列表 --device-cgroup-rule list Add a rule to the cgroup allowed devices list # 限制設備的讀取速率(每秒字節數)(默認值[]) --device-read-bps list Limit read rate (bytes per second) from a device (default []) # 限制設備的讀取速率(IO/秒)(默認值[]) --device-read-iops list Limit read rate (IO per second) from a device (default []) # 限制對設備的寫入速率(每秒字節數)(默認值[]) --device-write-bps list Limit write rate (bytes per second) to a device (default []) # 限制對設備的寫入速率(IO/秒)(默認值[]) --device-write-iops list Limit write rate (IO per second) to a device (default []) # 跳過鏡像驗證(默認為開啟) --disable-content-trust Skip image verification (default true) --dns list Set custom DNS servers # 設置自定義DNS服務器 --dns-option list Set DNS options # 設置DNS選項 --dns-search list Set custom DNS search domains # 設置自定義DNS搜索域 --domainname string Container NIS domain name # 容器NIS域名 --entrypoint string Overwrite the default ENTRYPOINT of the image # 覆蓋圖像的默認入口點 -e, --env list Set environment variables # 設置環境變量 --env-file list Read in a file of environment variables # 讀入環境變量文件 --expose list Expose a port or a range of ports # 公開一個端口或一系列端口 # 要添加到容器中的GPU設備(“全部”用於傳遞所有GPU) --gpus gpu-request GPU devices to add to the container ('all' to pass all GPUs) --group-add list Add additional groups to join # 添加要加入的其他組 --health-cmd string Command to run to check health # 要運行以檢查運行狀況的命令 # 運行檢查之間的時間(ms | s | m | h)(默認為0秒) --health-interval duration Time between running the check (ms|s|m|h) (default 0s) --health-retries int Consecutive failures needed to report unhealthy # 需要報告連續故障 --health-start-period duration Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s) # 開始運行狀況重試倒計時之前要初始化的容器的開始時間(ms | s | m | h)(默認為0s) # 允許運行一次檢查的最長時間(ms | s | m | h)(默認為0秒) --health-timeout duration Maximum time to allow one check to run (ms|s|m|h) (default 0s) --help Print usage # 打印使用幫助 -h, --hostname string Container host name # 容器主機名 # 在容器內運行一個init,它轉發信號並接收進程 --init Run an init inside the container that forwards signals and reaps processes # 即使未連接,也保持標准輸入打開 -i, --interactive Keep STDIN open even if not attached --ip string IPv4 address (e.g., 172.30.100.104) # IPv4地址(例如172.30.100.104) --ip6 string IPv6 address (e.g., 2001:db8::33) # IPv6地址(例如,2001:db8::33) --ipc string IPC mode to use # 要使用的IPC模式 --isolation string Container isolation technology # 容器隔離技術 --kernel-memory bytes Kernel memory limit # 內核內存限制 -l, --label list Set meta data on a container # 在容器上設置元數據 --label-file list Read in a line delimited file of labels # 讀入以行分隔的標簽文件 --link list Add link to another container # 添加指向另一個容器的鏈接 --link-local-ip list Container IPv4/IPv6 link-local addresses # 容器IPv4/IPv6鏈路本地地址 --log-driver string Logging driver for the container # 容器的日志記錄驅動程序 --log-opt list Log driver options # 日志驅動程序選項 --mac-address string Container MAC address (e.g., 92:d0:c6:0a:29:33) # 容器MAC地址(例如,92:d0:c6:0a:29:33) -m, --memory bytes Memory limit # 內存限制 --memory-reservation bytes Memory soft limit # 內存軟限制 # 交換限制等於內存加交換:'-1'以啟用無限制交換 --memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap # 調整容器內存交換(0到100)(默認值-1) --memory-swappiness int Tune container memory swappiness (0 to 100) (default -1) --mount mount Attach a filesystem mount to the container # 將文件系統裝載附加到容器 --name string Assign a name to the container # 為容器指定一個名稱 --network network Connect a container to a network # 將容器連接到網絡 --network-alias list Add network-scoped alias for the container # 為容器添加網絡范圍的別名 --no-healthcheck Disable any container-specified HEALTHCHECK # 禁用任何指定的容器HEALTHCHECK --oom-kill-disable Disable OOM Killer # 禁用OOM殺手 --oom-score-adj int Tune host's OOM preferences (-1000 to 1000) # 調整主機的OOM首選項(-1000到1000) --pid string PID namespace to use # 要使用的PID命名空間 --pids-limit int Tune container pids limit (set -1 for unlimited) # 調整容器pids限制(設置為-1表示無限制) --platform string Set platform if server is multi-platform capable # 如果服務器支持多平台,則設置平台 --privileged Give extended privileges to this container # 為此容器授予擴展權限 -p, --publish list Publish a container's port(s) to the host # 將容器的端口發布到主機 -P, --publish-all Publish all exposed ports to random ports # 將所有公開端口發布到隨機端口 # 運行前拉取圖像(“始終”|“缺少”|“從不”)(默認為“缺少”) --pull string Pull image before running ("always"|"missing"|"never") (default "missing") --read-only Mount the container's root filesystem as read only # 以只讀方式裝載容器的根文件系統 # 容器退出時應用的重新啟動策略(默認為“否”) --restart string Restart policy to apply when a container exits (default "no") --rm Automatically remove the container when it exits # 當容器退出時自動將其移除 --runtime string Runtime to use for this container # 用於此容器的運行時 --security-opt list Security Options # 安全選項 --shm-size bytes Size of /dev/shm # /dev/shm的大小 --sig-proxy Proxy received signals to the process (default true) # 代理接收到進程的信號(默認為true) --stop-signal string Signal to stop a container (default "SIGTERM") # 停止容器的信號(默認為“SIGTERM”) --stop-timeout int Timeout (in seconds) to stop a container # 停止容器的超時(秒) --storage-opt list Storage driver options for the container # 容器的存儲驅動程序選項 --sysctl map Sysctl options (default map[]) # Sysctl選項(默認映射[]) --tmpfs list Mount a tmpfs directory # 安裝tmpfs -t, --tty Allocate a pseudo-TTY # 分配一個偽TTY --ulimit ulimit Ulimit options (default []) # Ulimit選項(默認值[]) # 用戶名或UID(格式:<name | UID>[:<group | gid>) -u, --user string Username or UID (format: <name|uid>[:<group|gid>]) --userns string User namespace to use # 要使用的用戶命名空間 --uts string UTS namespace to use # 要使用的名稱空間 -v, --volume list Bind mount a volume # 綁定並裝入卷 --volume-driver string Optional volume driver for the container # 容器的可選卷驅動程序 --volumes-from list Mount volumes from the specified container(s) # 從指定容器裝入卷 -w, --workdir string Working directory inside the container # 容器內的工作目錄
# 常用參數 --name='xxx' 設置容器名稱用於區分容器 -d 后台運行 -it 使用交互方式運行 -p 指定容器端口 -p 8080:8080/主機端口:容器端口 -P 隨機指定端口 # 示例 [root@node1 ~]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE centos latest 5d0da3dc9764 2 months ago 231MB [root@node1 ~]# docker run -it 5d /bin/bash [root@b267d2d19ef4 /]# # 已經進入到容器 [root@b267d2d19ef4 /]# exit
-
docker ps
列出所有運行中的容器
[root@node1 ~]# docker ps --help Usage: docker ps [OPTIONS] List containers Options: -a, --all Show all containers (default shows just running) # 顯示所有容器(默認顯示正在運行) -f, --filter filter Filter output based on conditions provided # 根據提供的條件篩選輸出 --format string Pretty-print containers using a Go template # 顯示n個上次創建的容器(包括所有狀態)(默認值-1) -n, --last int Show n last created containers (includes all states) (default -1) -l, --latest Show the latest created container (includes all states) # 顯示最新創建的容器(包括所有狀態) --no-trunc Don't truncate output # 不要截斷輸出 -q, --quiet Only display container IDs # 僅顯示容器ID -s, --size Display total file sizes # 顯示總文件大小 [root@node1 ~]# docker ps -a # 容器ID #鏡像 # 命令 # 創建時間 # 狀態 # 端口 # 容器名稱 CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES fe8edecbd757 centos "/bin/bash" 13 seconds ago Exited (0) 11 seconds ago mystifying_satoshi 2c3fb40f1d3e centos "/bin/bash" 6 minutes ago Up 3 minutes exciting_morse
-
退出容器
exit #直接退出容器 Ctrl + q + p #不停止容器並退出
-
docker rm
刪除容器
[root@node1 ~]# docker rm --help Usage: docker rm [OPTIONS] CONTAINER [CONTAINER...] Remove one or more containers Options: # 強制移除正在運行的容器(使用SIGKILL) -f, --force Force the removal of a running container (uses SIGKILL) -l, --link Remove the specified link # 刪除指定的鏈接 -v, --volumes Remove anonymous volumes associated with the container # 刪除與容器關聯的匿名卷 [root@node1 ~]# docker ps -a # 查看所有容器 CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES fe8edecbd757 centos "/bin/bash" 7 minutes ago Exited (0) 7 minutes ago mystifying_satoshi 2c3fb40f1d3e centos "/bin/bash" 13 minutes ago Up 11 minutes exciting_morse [root@node1 ~]# docker rm fe8edecbd757 # 刪除一個已經停止的容器 fe8edecbd757 [root@node1 ~]# docker ps -a # 再次查看發現已經被刪除了 CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 2c3fb40f1d3e centos "/bin/bash" 14 minutes ago Up 11 minutes exciting_morse [root@node1 ~]#
-
容器的啟動刪除退出
docker start 容器ID # 啟動容器 docker stop 容器ID # 停止容器 docker restart 容器ID # 重啟容器 docker kill 容器ID # 強制停止容器
-
docker exec
以新的TTY進入容器
[root@node1 ~]# docker exec --help Usage: docker exec [OPTIONS] CONTAINER COMMAND [ARG...] Run a command in a running container Options: -d, --detach Detached mode: run command in the background # 分離模式:在后台運行命令 --detach-keys string Override the key sequence for detaching a container # 覆蓋用於分離容器的鍵序列 -e, --env list Set environment variables # 設置環境變量 --env-file list Read in a file of environment variables # 讀入環境變量文件 -i, --interactive Keep STDIN open even if not attached # 即使未連接,也保持標准輸入打開 --privileged Give extended privileges to the command # 為命令授予擴展權限 -t, --tty Allocate a pseudo-TTY # 分配一個偽TTY # 用戶名或UID(格式:<name | UID>[:<group | gid>) -u, --user string Username or UID (format: <name|uid>[:<group|gid>]) -w, --workdir string Working directory inside the container # 容器內的工作目錄 [root@node1 ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5db7847b3285 centos "/bin/bash -c 'while…" 25 minutes ago Up 25 minutes shell3 2c3fb40f1d3e centos "/bin/bash" About an hour ago Up 58 minutes exciting_morse [root@node1 ~]# docker exec -it 5db /bin/bash [root@5db7847b3285 /]#
-
docker attach
打開正在運行的TTY
[root@node1 ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5db7847b3285 centos "/bin/bash -c 'while…" 34 minutes ago Up 34 minutes shell3 2c3fb40f1d3e centos "/bin/bash" About an hour ago Up About an hour exciting_morse [root@node1 ~]# docker attach 5db
3.3 其他命令
-
后台啟動容器
docker -d
-
docker log
查看容器日志
[root@node1 ~]# docker logs --help Usage: docker logs [OPTIONS] CONTAINER Fetch the logs of a container Options: --details Show extra details provided to logs # 顯示提供給日志的其他詳細信息 -f, --follow Follow log output # 跟蹤日志輸出 # 顯示自時間戳(例如2013-01-02T13:23:37Z)或相對時間戳(例如42分鍾的42m)以來的日志 --since string Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes) # 從日志末尾顯示的行數(默認為“全部”) -n, --tail string Number of lines to show from the end of the logs (default "all") -t, --timestamps Show timestamps # 顯示時間戳 # 在時間戳(例如2013-01-02T13:23:37Z)或相對時間戳(例如42分鍾的42m)之前顯示日志 --until string Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)
-
docker top
查看容器進程
[root@node1 ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5db7847b3285 centos "/bin/bash -c 'while…" 3 minutes ago Up 3 minutes shell3 2c3fb40f1d3e centos "/bin/bash" 39 minutes ago Up 36 minutes exciting_morse [root@node1 ~]# docker top 5db UID PID PPID C STIME TTY TIME CMD root 10825 10804 0 22:08 ? root 11202 10825 0 22:12 ? [root@node1 ~]#
-
docker inspect
查看容器元數據
[root@node1 ~]# docker inspect --help Usage: docker inspect [OPTIONS] NAME|ID [NAME|ID...] Return low-level information on Docker objects Options: -f, --format string Format the output using the given Go template -s, --size Display total file sizes if the type is container # 如果類型為容器,則顯示總文件大小 --type string Return JSON for specified type # 返回指定類型的JSON [root@node1 ~]# docker ps CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5db7847b3285 centos "/bin/bash -c 'while…" 8 minutes ago Up 8 minutes shell3 2c3fb40f1d3e centos "/bin/bash" 43 minutes ago Up 40 minutes exciting_morse [root@node1 ~]# docker inspect 5db [ { "Id": "5db7847b3285ebb0bc78785808ed597f85c5476e84d24541cc5d135abc199bc2", "Created": "2021-12-11T14:08:37.31918904Z", "Path": "/bin/bash", "Args": [ "-c", "while true;do echo hhhh;sleep 1;done" ], "State": { "Status": "running", "Running": true, "Paused": false, "Restarting": false, "OOMKilled": false, "Dead": false, "Pid": 10825, "ExitCode": 0, "Error": "", "StartedAt": "2021-12-11T14:08:37.712499657Z", "FinishedAt": "0001-01-01T00:00:00Z" }, "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6", "ResolvConfPath": "/var/lib/docker/containers/5db7847b3285ebb0bc78785808ed597f85c5476e84d24541cc5d135abc199bc2/resolv.conf", "HostnamePath": "/var/lib/docker/containers/5db7847b3285ebb0bc78785808ed597f85c5476e84d24541cc5d135abc199bc2/hostname", "HostsPath": "/var/lib/docker/containers/5db7847b3285ebb0bc78785808ed597f85c5476e84d24541cc5d135abc199bc2/hosts", "LogPath": "/var/lib/docker/containers/5db7847b3285ebb0bc78785808ed597f85c5476e84d24541cc5d135abc199bc2/5db7847b3285ebb0bc78785808ed597f85c5476e84d24541cc5d135abc199bc2-json.log", "Name": "/shell3", "RestartCount": 0, "Driver": "overlay2", "Platform": "linux", "MountLabel": "", "ProcessLabel": "", "AppArmorProfile": "", "ExecIDs": null, "HostConfig": { "Binds": null, "ContainerIDFile": "", "LogConfig": { "Type": "json-file", "Config": {} }, "NetworkMode": "default", "PortBindings": {}, "RestartPolicy": { "Name": "no", "MaximumRetryCount": 0 }, "AutoRemove": false, "VolumeDriver": "", "VolumesFrom": null, "CapAdd": null, "CapDrop": null, "CgroupnsMode": "host", "Dns": [], "DnsOptions": [], "DnsSearch": [], "ExtraHosts": null, "GroupAdd": null, "IpcMode": "private", "Cgroup": "", "Links": null, "OomScoreAdj": 0, "PidMode": "", "Privileged": false, "PublishAllPorts": false, "ReadonlyRootfs": false, "SecurityOpt": null, "UTSMode": "", "UsernsMode": "", "ShmSize": 67108864, "Runtime": "runc", "ConsoleSize": [ 0, 0 ], "Isolation": "", "CpuShares": 0, "Memory": 0, "NanoCpus": 0, "CgroupParent": "", "BlkioWeight": 0, "BlkioWeightDevice": [], "BlkioDeviceReadBps": null, "BlkioDeviceWriteBps": null, "BlkioDeviceReadIOps": null, "BlkioDeviceWriteIOps": null, "CpuPeriod": 0, "CpuQuota": 0, "CpuRealtimePeriod": 0, "CpuRealtimeRuntime": 0, "CpusetCpus": "", "CpusetMems": "", "Devices": [], "DeviceCgroupRules": null, "DeviceRequests": null, "KernelMemory": 0, "KernelMemoryTCP": 0, "MemoryReservation": 0, "MemorySwap": 0, "MemorySwappiness": null, "OomKillDisable": false, "PidsLimit": null, "Ulimits": null, "CpuCount": 0, "CpuPercent": 0, "IOMaximumIOps": 0, "IOMaximumBandwidth": 0, "MaskedPaths": [ "/proc/asound", "/proc/acpi", "/proc/kcore", "/proc/keys", "/proc/latency_stats", "/proc/timer_list", "/proc/timer_stats", "/proc/sched_debug", "/proc/scsi", "/sys/firmware" ], "ReadonlyPaths": [ "/proc/bus", "/proc/fs", "/proc/irq", "/proc/sys", "/proc/sysrq-trigger" ] }, "GraphDriver": { "Data": { "LowerDir": "/var/lib/docker/overlay2/c3c47f255c9d1db61b969601df06f580012e1783c6aa2bbbbe03e9bc970d105f-init/diff:/var/lib/docker/overlay2/41ea41b839add0b7e657a3b18b47d03f209199589ea6e20e52503cce2f8d580f/diff", "MergedDir": "/var/lib/docker/overlay2/c3c47f255c9d1db61b969601df06f580012e1783c6aa2bbbbe03e9bc970d105f/merged", "UpperDir": "/var/lib/docker/overlay2/c3c47f255c9d1db61b969601df06f580012e1783c6aa2bbbbe03e9bc970d105f/diff", "WorkDir": "/var/lib/docker/overlay2/c3c47f255c9d1db61b969601df06f580012e1783c6aa2bbbbe03e9bc970d105f/work" }, "Name": "overlay2" }, "Mounts": [], "Config": { "Hostname": "5db7847b3285", "Domainname": "", "User": "", "AttachStdin": false, "AttachStdout": false, "AttachStderr": false, "Tty": false, "OpenStdin": false, "StdinOnce": false, "Env": [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin" ], "Cmd": [ "/bin/bash", "-c", "while true;do echo hhhh;sleep 1;done" ], "Image": "centos", "Volumes": null, "WorkingDir": "", "Entrypoint": null, "OnBuild": null, "Labels": { "org.label-schema.build-date": "20210915", "org.label-schema.license": "GPLv2", "org.label-schema.name": "CentOS Base Image", "org.label-schema.schema-version": "1.0", "org.label-schema.vendor": "CentOS" } }, "NetworkSettings": { "Bridge": "", "SandboxID": "a70d09048c929f2be067a98b10fb37d64287fd39d5fe0001a536fe70c8e9e002", "HairpinMode": false, "LinkLocalIPv6Address": "", "LinkLocalIPv6PrefixLen": 0, "Ports": {}, "SandboxKey": "/var/run/docker/netns/a70d09048c92", "SecondaryIPAddresses": null, "SecondaryIPv6Addresses": null, "EndpointID": "8799f54ad2618d76893aeed3c1dafc959d83e63a7c153555fc0fe946d3c52ce9", "Gateway": "172.17.0.1", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "IPAddress": "172.17.0.3", "IPPrefixLen": 16, "IPv6Gateway": "", "MacAddress": "02:42:ac:11:00:03", "Networks": { "bridge": { "IPAMConfig": null, "Links": null, "Aliases": null, "NetworkID": "d7122c9cff979c8ad84c9d6f473ade3c87f211708febd877b1e6d5b0f50a9d79", "EndpointID": "8799f54ad2618d76893aeed3c1dafc959d83e63a7c153555fc0fe946d3c52ce9", "Gateway": "172.17.0.1", "IPAddress": "172.17.0.3", "IPPrefixLen": 16, "IPv6Gateway": "", "GlobalIPv6Address": "", "GlobalIPv6PrefixLen": 0, "MacAddress": "02:42:ac:11:00:03", "DriverOpts": null } } } } ] [root@node1 ~]#
-
docker cp
Docker拷貝命令;用於從Docker中將文件拷貝至主機
[root@node1 ~]# docker cp --help Usage: docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|- docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH Copy files/folders between a container and the local filesystem Use '-' as the source to read a tar archive from stdin and extract it to a directory destination in a container. Use '-' as the destination to stream a tar archive of a container source to stdout. Options: -a, --archive Archive mode (copy all uid/gid information) # 存檔模式(復制所有uid/gid信息) -L, --follow-link Always follow symbol link in SRC_PATH # 始終遵循SRC_路徑中的符號鏈接
# 使用示例 [root@node1 ~]# docker ps -a # 查看歷史容器 CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 5db7847b3285 centos "/bin/bash -c 'while…" 2 hours ago Exited (137) 11 minutes ago shell3 df37e27d97c6 centos "/bin/sh -C 'while t…" 2 hours ago Exited (127) 2 hours ago shell2 6e442975e003 centos "/bin/bash -C 'while…" 2 hours ago Exited (127) 2 hours ago shell 2c3fb40f1d3e centos "/bin/bash" 3 hours ago Exited (0) 52 seconds ago exciting_morse [root@node1 ~]# docker start -a -i 2c # 運行容器 [root@2c3fb40f1d3e /]# echo hello,world > /root/xiaowangc [root@2c3fb40f1d3e /]# ls /root/ abc anaconda-ks.cfg anaconda-post.log original-ks.cfg xiaowangc [root@2c3fb40f1d3e /]# # 使用ctrl q p 退出 [root@node1 ~]# docker ps # 查看容器還在運行 CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 2c3fb40f1d3e centos "/bin/bash" 3 hours ago Up About a minute exciting_morse [root@node1 ~]# ls anaconda-ks.cfg initial-setup-ks.cfg [root@node1 ~]# docker cp 2c:/root/xiaowangc ./ [root@node1 ~]# ls anaconda-ks.cfg initial-setup-ks.cfg xiaowangc [root@node1 ~]# cat xiaowangc hello,world [root@node1 ~]# # 如果需要將主機文件考至容器 即: docker cp 主機文件 容器:路徑
3.4 Docker commit
從容器創建一個新的鏡像
[root@node1 ~]# docker commit
"docker commit" requires at least 1 and at most 2 arguments.
See 'docker commit --help'.
Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
Create a new image from a container's changes
[root@node1 ~]# docker commit --help
Usage: docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
Create a new image from a container's changes
Options:
# 作者(例如,“約翰·漢尼拔·史密斯<hannibal@a-team.com>)
-a, --author string Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
# 將Dockerfile指令應用於創建的鏡像
-c, --change list Apply Dockerfile instruction to the created image
-m, --message string Commit message # 提交消息
-p, --pause Pause container during commit (default true) # 提交期間暫停容器(默認為true)
[root@node1 ~]# docker pull tomcat
[root@node1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat latest 24207ccc9cce 3 days ago 680MB
centos latest 5d0da3dc9764 2 months ago 231MB
elasticsearch latest 5acf0e8da90b 3 years ago 486MB
[root@node1 ~]# docker run -d -P 24
efa6bf9baf159b64b4b82d5f7d3330d6f83eddfe834d88ea8af21570ddb74ab4
[root@node1 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
efa6bf9baf15 24 "catalina.sh run" 28 seconds ago Up 27 seconds 0.0.0.0:49154->8080/tcp, :::49154->8080/tcp hungry_zhukovsky
[root@node1 ~]# docker exec -it efa /bin/bash
root@efa6bf9baf15:/usr/local/tomcat# ls
BUILDING.txt LICENSE README.md RUNNING.txt conf logs temp webapps.dist
CONTRIBUTING.md NOTICE RELEASE-NOTES bin lib native-jni-lib webapps work
root@efa6bf9baf15:/usr/local/tomcat# cp -a webapps.dist/* webapps/
root@efa6bf9baf15:/usr/local/tomcat# exit
# 訪問當前宿主機IP:49154
# 官方鏡像默認是無法打開此頁面
[root@node1 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
efa6bf9baf15 24 "catalina.sh run" 4 minutes ago Up 4 minutes 0.0.0.0:49154->8080/tcp, :::49154->8080/tcp hungry_zhukovsky
# 作者 描述 容器id 鏡像:tag[版本]
[root@node1 ~]# docker commit -a xiaowangc -m "Modify home page" efa tomcat01:1.0
sha256:fb71bc6566f66ab89c1b2c7b17358ade7a44f17c89f5c8193fa054b5d771f658
[root@node1 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat01 1.0 fb71bc6566f6 3 seconds ago 684MB # 打包可以查看鏡像
tomcat latest 24207ccc9cce 3 days ago 680MB
centos latest 5d0da3dc9764 2 months ago 231MB
elasticsearch latest 5acf0e8da90b 3 years ago 486MB
[root@node1 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
efa6bf9baf15 24 "catalina.sh run" 9 minutes ago Up 9 minutes 0.0.0.0:49154->8080/tcp, :::49154->8080/tcp hungry_zhukovsky
[root@node1 ~]# docker stop efa # 停止之前的容器
efa
[root@node1 ~]# docker run -d -P fb71 # 通過我們打包后的鏡像創建容器
a1b1c2987c3fee9546335a0070a31c3f5d903c3e17f04f34452aca775e7e1b10
[root@node1 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
a1b1c2987c3f fb71 "catalina.sh run" 2 seconds ago Up 2 seconds 0.0.0.0:49155->8080/tcp, :::49155->8080/tcp compassionate_fermat
# 直接訪問 宿主機IP:49155
# 官方的tomcat鏡像不做修改,無法訪問這個主頁,現在我們通過修改后的容器打包成鏡像,再創建就可以直接訪問
4.容器卷(容器數據持久化)
數據可以存儲在容器中,但是一旦將容器進行刪除就等同刪庫跑路了qwq。
Docker對於宿主機來說,只是一個運行在Linux上的應用程序,因此它的的數據存儲還是會依賴宿主機,實現數據持久化的兩種方式:
-
Bind Mount
Bind Mount數據持久化的方式,如果掛載本地的一個目錄,則對應容器的目錄下的內容會被本地的數據覆蓋。使用Bind Mount還需要指定本地的某個目錄掛載到容器的某個目錄。
-
Docker Manager Volume
Docker Manager Volume相比Bind Mount,掛載目錄到容器中數據不會被覆蓋,同時也不需要管理員指定從宿主機掛載到容器中的某個目錄,只需要指定對容器的某個目錄進行掛載,而掛載到宿主機的某個目錄是由Docker來進行統一管理。
任一一種方式的持久化都不會在容器被刪除后導致數據丟失
4.1 Bind Mount
Bind Mount掛載卷有兩種方式:
-
-v [主機路徑:]容器路徑 [:可選參數]
[root@node1 ~]# ls /root/ # 查看主機root下並沒有docker-volume目錄 anaconda-ks.cfg Documents initial-setup-ks.cfg Pictures quick_start.sh Videos Desktop Downloads Music Public Templates xiaowangc [root@node1 ~]# docker run --help | grep volume -v, --volume list Bind mount a volume # 使用方式 -v 宿主機路徑:容器路徑 --volume-driver string Optional volume driver for the container --volumes-from list Mount volumes from the specified container(s) [root@node1 ~]# docker run -it -v /root/docker-volume:/root/docker centos /bin/bash # 啟動容器並進行綁定 [root@e8136a876260 /]# ls bin dev etc home lib lib64 lost+found media mnt opt proc root run sbin srv sys tmp usr var [root@e8136a876260 /]# touch /root/docker/abc # 在對於的掛載位置創建一個文件 [root@e8136a876260 /]# exit # 退出 exit [root@node1 ~]# ls /root/docker-volume/ # 查看本機對於的目錄位置,可以看到我們之前在容器中創建的abc文件 abc [root@node1 ~]# docker ps -a # 查看更改創建的容器id CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e8136a876260 centos "/bin/bash" 3 minutes ago Exited (0) 3 minutes ago distracted_bose a1b1c2987c3f fb71 "catalina.sh run" 3 hours ago Exited (143) 5 minutes ago compassionate_fermat efa6bf9baf15 24 "catalina.sh run" 3 hours ago Exited (143) 3 hours ago hungry_zhukovsky a1099bfaa7ff tomcat "catalina.sh run" 13 hours ago Exited (143) 11 hours ago clever_carson ca73206e78db tomcat "catalina.sh run" 13 hours ago Exited (130) 13 hours ago keen_mclean 62d75c8f96c8 tomcat "/bin/bash" 13 hours ago Exited (0) 13 hours ago strange_rhodes afecd5719875 elasticsearch "/docker-entrypoint.…" 22 hours ago Exited (130) 22 hours ago modest_hawking [root@node1 ~]# docker inspect e8 # 獲取容器元數據 ... "Binds": [ "/root/docker-volume:/root/docker" ], ... "Mounts": [ { "Type": "bind", # 類型 "Source": "/root/docker-volume", # 源目錄(宿主機路徑) "Destination": "/root/docker", # 目的目錄(Docker容器中路徑) "Mode": "", "RW": true, "Propagation": "rprivate" } ], ... # 我們試着將容器進行刪除 [root@node1 ~]# docker ps -a # 找到更改創建的容器id CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES e8136a876260 centos "/bin/bash" 10 minutes ago Exited (0) 10 minutes ago distracted_bose a1b1c2987c3f fb71 "catalina.sh run" 3 hours ago Exited (143) 12 minutes ago compassionate_fermat efa6bf9baf15 24 "catalina.sh run" 3 hours ago Exited (143) 3 hours ago hungry_zhukovsky a1099bfaa7ff tomcat "catalina.sh run" 13 hours ago Exited (143) 11 hours ago clever_carson ca73206e78db tomcat "catalina.sh run" 13 hours ago Exited (130) 13 hours ago keen_mclean 62d75c8f96c8 tomcat "/bin/bash" 13 hours ago Exited (0) 13 hours ago strange_rhodes afecd5719875 elasticsearch "/docker-entrypoint.…" 22 hours ago Exited (130) 22 hours ago modest_hawking [root@node1 ~]# docker rm e81 # 刪除容器 e81 [root@node1 ~]# ls /root/docker-volume/ # 再次查看發現數據還存在 abc [root@node1 ~]#
下面我們再深入了解一下-v
[root@node1 ~]# man docker run # 有興趣的可以自己閱讀翻譯
-v|--volume[=[[HOST-DIR:]CONTAINER-DIR[:OPTIONS]]]
Create a bind mount. If you specify, -v /HOST-DIR:/CONTAINER-DIR, Docker
bind mounts /HOST-DIR in the host to /CONTAINER-DIR in the Docker
container. If 'HOST-DIR' is omitted, Docker automatically creates the new
volume on the host. The OPTIONS are a comma delimited list and can be:
#創建綁定掛載。如果指定-v/HOST-DIR:/CONTAINER-DIR,則為Docker將主機中的mounts/HOST-DIR綁定到Docker中的/CONTAINER-DIR容器如果省略“HOST-DIR”,Docker會自動創建新的主機上的卷。選項是逗號分隔的列表,可以是:
· [rw|ro] # 設置卷是否可讀寫,在上面的實例中我們看到一行 "RW": true,表示可讀寫,當然我們也可以在掛載之前設置為ro(只讀)
· [z|Z]
· [[r]shared|[r]slave|[r]private]
· [delegated|cached|consistent]
· [nocopy]
# 這里告訴我們CONTAINER-DIR(容器目錄)必須使用絕對路徑,而HOST-DIR可以使用相對/絕對路徑
The CONTAINER-DIR must be an absolute path such as /src/docs. The HOST-DIR can be an absolute path or a name value. A name value must start with an alphanumeric character, followed by a-z0-9, _ (underscore), . (period) or -
(hyphen). An absolute path starts with a / (forward slash).
# 如果HOST-DIR是絕對路徑,Docker Bind會裝載到指定路徑。如果是名稱docker會使用該名稱創建一個以改名稱命名的卷
If you supply a HOST-DIR that is an absolute path, Docker bind-mounts to the path you specify. If you supply a name, Docker creates a named volume by that name. For example, you can specify either /foo or foo for a HOST-DIR value. If you supply the /foo value, Docker creates a bind mount. If you supply the foo specification, Docker creates a named volume.
# 可以使用-v綁定一個或多個,如果其他容器也要使用請用--volumes-from選項
You can specify multiple -v options to mount one or more mounts to a container. To use these same mounts in other containers, specify the --volumes-from option also.
#你還可以在:后面使用多個參數,設置讀寫權限rw、ro 例如: -v 主機路徑:容器路徑:ro...;還能使用Z/z設置Docker重新標記共享卷上的文件對象,Z選項告訴Docker使用私有非共享標簽。只有當前容器才能使用專用卷。z表示共享卷內容
You can supply additional options for each bind mount following an additional colon. A :ro or :rw suffix mounts a volume in read-only or read-write mode, respectively. By default, volumes are mounted in read-write mode.
You can also specify the consistency requirement for the mount, either :consistent (the default), :cached, or :delegated. Multiple options are separated by commas, e.g. :ro,cached.
Labeling systems like SELinux require that proper labels are placed on volume content mounted into a container. Without a label, the security system might prevent the processes running inside the container from using the
content. By default, Docker does not change the labels set by the OS.
To change a label in the container context, you can add either of two suffixes :z or :Z to the volume mount. These suffixes tell Docker to relabel file objects on the shared volumes. The z option tells Docker that two con‐
tainers share the volume content. As a result, Docker labels the content with a shared content label. Shared volume labels allow all containers to read/write content. The Z option tells Docker to label the content with a
private unshared label. Only the current container can use a private volume.
By default bind mounted volumes are private. That means any mounts done inside container will not be visible on host and vice-a-versa. One can change this behavior by specifying a volume mount propagation property. Making a
volume shared mounts done under that volume inside container will be visible on host and vice-a-versa. Making a volume slave enables only one way mount propagation and that is mounts done on host under that volume will be
visible inside container but not the other way around.
# 要控制卷的裝載傳播屬性,可以使用:[r]共享、:[r]從屬或:[r]專用傳播標志。只能為綁定裝入的卷指定傳播屬性,而不能為內部卷或命名卷指定傳播屬性卷。要使裝載傳播工作,源裝載點(裝載源目錄的裝載點)必須具有正確的傳播屬性。對於共享卷,必須共享源裝載點。對於從卷,源裝載必須是共享的或從的。
To control mount propagation property of volume one can use :[r]shared, :[r]slave or :[r]private propagation flag. Propagation property can be specified only for bind mounted volumes and not for internal volumes or named
volumes. For mount propagation to work source mount point (mount point where source dir is mounted on) has to have right propagation properties. For shared volumes, source mount point has to be shared. And for slave volumes,
source mount has to be either shared or slave.
...
To disable automatic copying of data from the container path to the volume, use the nocopy flag. The nocopy flag can be set on bind mounts and named volumes.
# 另請參見--mount,它是--tmpfs和--volume的繼承者。即使沒有計划棄用--volume,也建議使用--mount。
See also --mount, which is the successor of --tmpfs and --volume. Even though there is no plan to deprecate --volume, usage of --mount is recommended.
-
--mount
第二種通過--mount也是官方建議使用的方法,它相比-v跟靈活、可讀性高。
[root@node1 ~]# man docker run # 有興趣的可以自己閱讀翻譯 --mount type=TYPE,TYPE-SPECIFIC-OPTION[,...] Attach a filesystem mount to the container # 當前支持的裝載類型有bind、volume和tmpfs。 Current supported mount TYPES are bind, volume, and tmpfs. e.g. # 例如 # bind類型(Bind Mount),源地址,目錄地址 type=bind,source=/path/on/host,destination=/path/in/container # volume類型(Docker Manager Volume),源地址,目的地址,卷標,卷標 type=volume,source=my-volume,destination=/path/in/container,volume-label="color=red",volume-label="shape=round" # 前面圖上的tmpfs type=tmpfs,tmpfs-size=512M,destination=/path/in/container # 常用選項 Common Options: # 設置源地址 · src, source: mount source spec for bind and volume. Mandatory for bind. # 設置目的地址 · dst, destination, target: mount destination spec. # 設置權限 · ro, readonly: true or false (default). ...
4.2 Docker Manager Volume
通過上面對--mount參數的了解,我想對使用Docker Manager Volume方法掛載或綁定應該知道改怎么操作了~
下面來實踐一下
[root@node1 ~]# docker run -it --mount src=docker_home,dst=/home centos /bin/bash
[root@69a38a458cb7 /]# #ctrl + q + p 不停止退出容器
[root@node1 ~]# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
69a38a458cb7 centos "/bin/bash" 41 seconds ago Up 41 seconds mystifying_satoshi
[root@node1 ~]# docker inspect 69
"Mounts": [
{
"Type": "volume", # 掛載類型 volume
"Name": "docker_home", # 前面有提到過,如果設置名稱那么將以名稱來創建對於卷
"Source": "/var/lib/docker/volumes/docker_home/_data", # 主機上目錄地址(Docker自行創建)
"Destination": "/home", # 目錄地址
"Driver": "local", # 設備為本地
"Mode": "z", # z表示共享卷內容
"RW": true, # 表示可讀寫
"Propagation": ""
}
4.3 聚名和匿名掛載
在通過docker volume ls 查看卷的時候會發現有卷名為哈希值命名的是因為在掛載的時候並未指定卷名,bind不能通過--mount設置卷名,但可以直接使用-v 進行設置例: -v 卷名:容器路徑 ,volume方式可以通過--mount 卷名:容器路徑進行設置卷名,如果未設置將以哈希值進行命名
[root@node1 ~]# docker volume ls # 查看卷
DRIVER VOLUME NAME
local 15d9a94c6a8cdbffa66b3d9c76d476243c312f70f7e54d46549d137193036479 # 匿名掛載,這是因為在掛載的時候並未指定源路徑的名稱
local docker_home # 聚名掛載,如果指定了名稱那么將會以名稱創建對於的卷
[root@node1 ~]# docker volume inspect 15d9a94c6a8cdbffa66b3d9c76d476243c312f70f7e54d46549d137193036479
[
{
"CreatedAt": "2021-12-12T04:57:10+08:00",
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/15d9a94c6a8cdbffa66b3d9c76d476243c312f70f7e54d46549d137193036479/_data",
"Name": "15d9a94c6a8cdbffa66b3d9c76d476243c312f70f7e54d46549d137193036479",
"Options": null,
"Scope": "local"
}
]
[root@node1 ~]# docker volume inspect docker_home
[
{
"CreatedAt": "2021-12-13T04:19:01+08:00",
"Driver": "local",
"Labels": null,
"Mountpoint": "/var/lib/docker/volumes/docker_home/_data",
"Name": "docker_home",
"Options": null,
"Scope": "local"
}
]
[root@node1 ~]#
5.Docker File
此鏡像在構建基本鏡像(例如
debian
和busybox
)或超級小鏡像(僅包含單個二進制文件和它需要的任何內容,例如hello-world
)的上下文中最有用。
CentOS的官方Dockerfile
FROM scratch # 最基礎的鏡像
ADD centos-8-x86_64.tar.xz / # 添加centos-8-x86_64軟件包
LABEL org.label-schema.schema-version="1.0"/ # 添加元數據到鏡像
org.label-schema.name="CentOS Base Image"/
org.label-schema.vendor="CentOS"/
org.label-schema.license="GPLv2"/
org.label-schema.build-date="20210915"
CMD ["/bin/bash"]
DockerFile常用命令:
[root@node1 ~]# docker build --help
Usage: docker build [OPTIONS] PATH | URL | -
Build an image from a Dockerfile # 從Dockerfile生成鏡像
Options:
# 添加自定義主機到IP映射(主機:IP)
--add-host list Add a custom host-to-IP mapping (host:ip)
--build-arg list Set build-time variables # 設置構建時變量
--cache-from strings Images to consider as cache sources # 視為高速緩存源的鏡像
--cgroup-parent string Optional parent cgroup for the container # 容器的可選父cgroup
--compress Compress the build context using gzip # 使用gzip壓縮構建上下文
# 限制CPU CFS(完全公平調度程序)周期
--cpu-period int Limit the CPU CFS (Completely Fair Scheduler) period
# 限制CPU CFS(完全公平調度程序)配額
--cpu-quota int Limit the CPU CFS (Completely Fair Scheduler) quota
-c, --cpu-shares int CPU shares (relative weight) # CPU份額(相對權重)
--cpuset-cpus string CPUs in which to allow execution (0-3, 0,1) # 允許執行的CPU(0-3,0,1)
--cpuset-mems string MEMs in which to allow execution (0-3, 0,1) # 允許執行的MEMs(0-3,0,1)
--disable-content-trust Skip image verification (default true) # 跳過鏡像驗證(默認為真)
# Dockerfile的名稱(默認值為“路徑/Dockerfile”)
-f, --file string Name of the Dockerfile (Default is 'PATH/Dockerfile')
--force-rm Always remove intermediate containers # 務必拆下中間容器
--iidfile string Write the image ID to the file # 將鏡像ID寫入文件
--isolation string Container isolation technology # 容器隔離技術
--label list Set metadata for an image # 設置鏡像的元數據
-m, --memory bytes Memory limit # 內存限制
# 交換限制等於內存加交換:'-1'以啟用無限制交換
--memory-swap bytes Swap limit equal to memory plus swap: '-1' to enable unlimited swap
# 在構建期間為運行指令設置網絡模式(默認值為“默認值”)
--network string Set the networking mode for the RUN instructions during build (default "default")
--no-cache Do not use cache when building the image # 生成鏡像時不要使用緩存
--pull Always attempt to pull a newer version of the image # 始終嘗試提取鏡像的更新版本
# 成功時抑制生成輸出並打印鏡像ID
-q, --quiet Suppress the build output and print image ID on success
# 成功生成后刪除中間容器(默認為true)
--rm Remove intermediate containers after a successful build (default true)
--security-opt strings Security options # 安全選項
--shm-size bytes Size of /dev/shm # /dev/shm的大小
# 名稱和可選的“名稱:標記”格式的標記
-t, --tag list Name and optionally a tag in the 'name:tag' format
--target string Set the target build stage to build. # 將目標構建階段設置為build。
--ulimit ulimit Ulimit options (default []) # Ulimit選項(默認值[])
[root@node1 docker]# vim Dockerfile
FROM centos
MAINTAINER xiaowangc<780312916@qq.com>
ADD jdk-8u202-linux-x64.tar.gz /usr/local
ADD apache-tomcat-10.0.14.tar.gz /usr/local
ENV MYPATH /usr/local
WORKDIR $MYPATH
ENV JAVA_HOME /usr/local/jdk1.8.0_202
ENV CLASSPATH $JAVA_HOME/lib/dt.jar;$JAVA_HOME/lib/tools.jar
ENV CATALINA_HOME /usr/local/apache-tomcat-10.0.14
ENV CATALINA_BASH /usr/local/apache-tomcat-10.0.14
ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin
EXPOSE 8080
CMD /usr/local/apache-tomcat-10.0.14/bin/startup.sh && tail -F /usr/local/apache-tomcat-10.0.14/bin/logs/catalina.out
[root@node1 docker]# docker build -t tomcat:1.0 .
Sending build context to Docker daemon 626.3MB
Step 1/13 : FROM centos
---> 5d0da3dc9764
Step 2/13 : MAINTAINER xiaowangc<780312916@qq.com>
---> Running in c4eb917f2af7
Removing intermediate container c4eb917f2af7
---> ce301fca9581
Step 3/13 : ADD jdk-8u202-linux-x64.tar.gz /usr/local
---> 80553040d2a3
Step 4/13 : ADD apache-tomcat-10.0.14.tar.gz /usr/local
---> e817c2abc0ea
Step 5/13 : ENV MYPATH /usr/local
---> Running in dc72d266f4eb
Removing intermediate container dc72d266f4eb
---> 9a11104f7a13
Step 6/13 : WORKDIR $MYPATH
---> Running in cdf0377b61ad
Removing intermediate container cdf0377b61ad
---> e94e866312c7
Step 7/13 : ENV JAVA_HOME /usr/local/jdk1.8.0_202
---> Running in 460df16b993a
Removing intermediate container 460df16b993a
---> 6523add551dc
Step 8/13 : ENV CLASSPATH $JAVA_HOME/lib/dt.jar;$JAVA_HOME/lib/tools.jar
---> Running in c3243bb658ab
Removing intermediate container c3243bb658ab
---> d27761de5003
Step 9/13 : ENV CATALINA_HOME /usr/local/apache-tomcat-10.0.14
---> Running in a202f40d116f
Removing intermediate container a202f40d116f
---> 3e2b79eac04f
Step 10/13 : ENV CATALINA_BASH /usr/local/apache-tomcat-10.0.14
---> Running in 75aa2512492c
Removing intermediate container 75aa2512492c
---> 69f0cf1dfa7c
Step 11/13 : ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin
---> Running in 61d1715c1996
Removing intermediate container 61d1715c1996
---> 9c10da8b965f
Step 12/13 : EXPOSE 8080
---> Running in 27eb03392b67
Removing intermediate container 27eb03392b67
---> 29061051cbe8
Step 13/13 : CMD /usr/local/apache-tomcat-10.0.14/bin/startup.sh && tail -F /usr/local/apache-tomcat-10.0.14/bin/logs/catalina.out
---> Running in 96463dc0a1e7
Removing intermediate container 96463dc0a1e7
---> c6bbae39158e
Successfully built c6bbae39158e
Successfully tagged tomcat:1.0
[root@node1 docker]# docker run -itdp 80:8080 c6 # 將容器8080映射到主機80
212d00ffa33649ac8f4370feab11a36552d2ae40719d398718c29c233e3c09ed
[root@node1 docker]# docker ps # 查看容器是否正在運行
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
212d00ffa336 c6 "/bin/sh -c '/usr/lo…" 3 seconds ago Up 3 seconds 0.0.0.0:80->8080/tcp, :::80->8080/tcp confident_archimedes
[root@node1 docker]#
訪問宿主機IP
6.Docker Network
Docker網絡模式
Docker網絡 | 說明 |
---|---|
Host | 容器和宿主機共用Network/Port |
Container | 容器和另外的容器共用Network/Port |
None | 關閉該容器的網絡 |
Bridge | 容器會分配到屬於各自的IP,並連接到Docker0的虛擬網橋,通過Docker0與宿主機通信(默認模式) |
6.1 Bridge
橋接(Bridge)網絡從上圖就可以看出來,我們創建的兩台容器是不能直接進行通信而是經過Docker0進行橋接實現的(二層交換)。在創建容器時,如果沒有更改容器網絡那么容器默認將加入到Docker0中。
通過在宿主機和容器通過命令對網絡進行查看,我們還會會看到宿主機和容器的網卡的名稱有着微妙的聯系,if7-if8、if9-if10...
這里是因為容器使用了veth-pair,veth設備的特點(在Bridge的第一張圖就能看出):
- veth設備是成對出現的,另一端兩個設備彼此相連
- 一個設備收到協議棧的數據發送請求后,會將數據發送到另一個設備上去
# 創建一個新橋並加入容器
[root@node1 ~]# docker network
Usage: docker network COMMAND
Manage networks
Commands:
connect Connect a container to a network # 將容器連接到網絡
create Create a network # 創建一個新網絡
disconnect Disconnect a container from a network # 斷開容器與網絡的連接
inspect Display detailed information on one or more networks # 顯示一個或多個網絡上的詳細信息
ls List networks # 列出所有網絡
prune Remove all unused networks # 刪除所有未使用的網絡
rm Remove one or more networks # 刪除一個或多個網絡
由Docker默認創建的網絡
[root@node1 ~]# docker network create --subnet 192.168.233.0/24 --gateway 192.168.233.254 netWork
8e707433b97d58fb6329ec3cf6cf770d34df82b1050e16b56c4f7e6090cfbcc5
[root@node1 ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
712b32668ed2 bridge bridge local
ca94de41081d host host local
8e707433b97d netWork bridge local # 這是我們新建出來的網絡
2ef78fbe2411 none null local
[root@node1 ~]# docker run -it --network=8e centos /bin/bash # 通過--network來指定容器網絡
[root@d9c64ba08629 /]# ip add
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
14: eth0@if15: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:c0:a8:e9:01 brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet 192.168.233.1/24 brd 192.168.233.255 scope global eth0 # 已經獲取到我們設置的地址
valid_lft forever preferred_lft forever
[root@d9c64ba08629 /]#
#不同Bridge的容器之間不能互通
6.2 Container
Container模式是將創建好的新容器和已經存在的容器共享同一個網絡(IP/Port),而不是跟Bridge模式一樣,新容器也不會創建一個屬於自己的網卡和配置IP地址等等。當然,除了網絡環境容器的其他資源還是默認進行隔離的。
6.3 None
None模式Docker不會為容器進行任何網絡的設置,當創建好這個容器它不會擁有IP地址、DNS、路由等等,需要我們手動對容器進行設置,這種網絡類型的容器是沒有辦法進行聯網的。
# 創建容器並設置網絡為None
[root@node1 ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
712b32668ed2 bridge bridge local
ca94de41081d host host local
8e707433b97d netWork bridge local
2ef78fbe2411 none null local
[root@node1 ~]# docker run -itd --network=none centos
0f2e0509e81bb5e34f68eabe429eaf0ab4eca6d1937c62626635fdb625b16676
[root@node1 ~]# docker exec -it 0f ip add
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
[root@node1 ~]#
6.4 Host
Host模式是指容器可以直接使用宿主機的IP地址進行通信,容器內的端口可以直接使用宿主機的端口不需要進行NAT。
# 創建容器並設置網絡為Host
[root@node1 ~]# docker network ls
NETWORK ID NAME DRIVER SCOPE
712b32668ed2 bridge bridge local
ca94de41081d host host local
8e707433b97d netWork bridge local
2ef78fbe2411 none null local
[root@node1 ~]# docker run -itd --network host centos
3ef7cf52eba35f6286ecc863f896ff96386fb61b79815100fe1666a7a0381e3e
[root@node1 ~]# docker exec -it 3e ip add
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1000
link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
inet 127.0.0.1/8 scope host lo
valid_lft forever preferred_lft forever
inet6 ::1/128 scope host
valid_lft forever preferred_lft forever
2: ens160: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc mq state UP group default qlen 1000
link/ether 00:0c:29:d0:69:a9 brd ff:ff:ff:ff:ff:ff
inet 172.25.250.9/24 brd 172.25.250.255 scope global noprefixroute ens160
valid_lft forever preferred_lft forever
inet6 fe80::20c:29ff:fed0:69a9/64 scope link noprefixroute
valid_lft forever preferred_lft forever
3: virbr0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc noqueue state DOWN group default qlen 1000
link/ether 52:54:00:69:3a:f3 brd ff:ff:ff:ff:ff:ff
inet 192.168.122.1/24 brd 192.168.122.255 scope global virbr0
valid_lft forever preferred_lft forever
4: virbr0-nic: <BROADCAST,MULTICAST> mtu 1500 qdisc fq_codel master virbr0 state DOWN group default qlen 1000
link/ether 52:54:00:69:3a:f3 brd ff:ff:ff:ff:ff:ff
5: docker0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:b7:51:5a:38 brd ff:ff:ff:ff:ff:ff
inet 172.17.0.1/16 brd 172.17.255.255 scope global docker0
valid_lft forever preferred_lft forever
inet6 fe80::42:b7ff:fe51:5a38/64 scope link
valid_lft forever preferred_lft forever
13: br-8e707433b97d: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
link/ether 02:42:a0:c6:26:d2 brd ff:ff:ff:ff:ff:ff
inet 192.168.233.254/24 brd 192.168.233.255 scope global br-8e707433b97d
valid_lft forever preferred_lft forever
inet6 fe80::42:a0ff:fec6:26d2/64 scope link
valid_lft forever preferred_lft forever
17: vethbe82798@if16: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether d2:95:6d:24:8b:5f brd ff:ff:ff:ff:ff:ff link-netnsid 0
inet6 fe80::d095:6dff:fe24:8b5f/64 scope link
valid_lft forever preferred_lft forever
19: veth76775e3@if18: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master br-8e707433b97d state UP group default
link/ether 1a:48:2c:6f:f5:01 brd ff:ff:ff:ff:ff:ff link-netnsid 1
inet6 fe80::1848:2cff:fe6f:f501/64 scope link
valid_lft forever preferred_lft forever
21: vethfd72d16@if20: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether ae:d3:7c:80:fc:4e brd ff:ff:ff:ff:ff:ff link-netnsid 2
inet6 fe80::acd3:7cff:fe80:fc4e/64 scope link
valid_lft forever preferred_lft forever
25: vethafacb9a@if24: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue master docker0 state UP group default
link/ether a2:dc:c1:1d:0d:66 brd ff:ff:ff:ff:ff:ff link-netnsid 3
inet6 fe80::a0dc:c1ff:fe1d:d66/64 scope link
valid_lft forever preferred_lft forever
[root@node1 ~]#