Docker 指令介紹 === ###### tags: `Docker`、`Container`、`DevOps` ![](https://i.imgur.com/DHTpUuz.png) 圖片來源:[Gitbook - 《Docker —— 從入門到實踐》正體中文版 by Philipzheng](https://philipzheng.gitbooks.io/docker_practice/content/appendix_command/) > 詳情請參考官方的 [Docker (base command) | Docker Documentation](https://docs.docker.com/engine/reference/commandline/docker/) 文件。 ```shell $ docker [OPTIONS] COMMAND [ARG...] ``` ## `info`:查看 Docker 系統資訊 顯示以下訊息: - 目前擁有的 container 和 image 數量 - Docker Hub 登入的帳號 ```shell $ docker info ``` ## `pull`:取得 (拉取) image - 如果 pull image 時沒有指定 tag,預設 pull 的 image tag 會是 `latset` 版 - 在 pull 時為什麼會一層一層跑?因為整個 Docker image 是一層一層的結構 - 為甚麼會出現 `Already exists`?在 pull image 時,如果主機內已有的 image 中有某些地方相同,就不需要再 pull 一次,就很像 `git pull` 一樣,不會從頭到尾全部 pull,只會 pull 不同的地方 ```shell $ docker pull [repository name]:[TAG|@DIGEST] $ docker pull node:boron-slim boron-slim: Pulling from library/node ad74af05f5a2: Already exists 2b032b8bbe8b: Already exists a9a5b35f6ead: Pull complete 3245b5a1c52c: Extracting [========> ] 54.03MB/131.9MB afa075743392: Download complete 9fb9f21641cd: Download complete b1074d048a61: Download complete 602b2c2b7041: Download complete ``` ## `images`:查看目前 image - `-a`,`--all`:顯示所有 image (包含 intermediate layers 的 image) - `-q`,`--quiet`:只顯示 image id 在列出訊息的欄位介紹: - `REPOSITORY`:來自於哪個 repository,EX:ubuntu - `TAG`:image 的標記,如果沒有指定 TAG,預設使用 `latest`,EX:14.04 - `IMAGE` ID:image id(唯一) - `CREATED`:建立時間 - `SIZE`:image 大小 ```shell $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE php 7.1-apache a47f065418d5 3 weeks ago 391MB node boron-slim 3e1f10d602d5 3 days ago 215MB $ docker images -a REPOSITORY TAG IMAGE ID CREATED SIZE <none> <none> 77a90b6059cf About an hour ago 391MB php 7.1-apache a47f065418d5 3 weeks ago 391MB node boron-slim 3e1f10d602d5 3 days ago 215MB $ docker images -q a47f065418d5 3e1f10d602d5 ``` ## `ps`:顯示目前 container 狀態 - 預設:顯示正在執行的 container - `-a`,`--all`:顯示所有 container - `-q`,`--quiet`:只顯示 container id 列出訊息的欄位介紹: - `CONTAINER ID`:容器 id,唯一標識 - `IMAGE`:使用哪個 image 作為基底 - `COMMAND`:以什麼方式運行,==??? ??? ???== - `CREATED`:建立時間 - `STATUS`:執行狀態,什麼時候停止執行、執行多久時間,`Exited` 為停止執行狀態,`Up` 為執行狀態 - `PORTS`:host 對外開 x port -> container 內開 x port - `NAMES`:容器名稱 ```shell $ docker ps $ docker ps -a CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 0a6bae5fe144 hello_php "docker-php-entryp..." 10 seconds ago Up 6 seconds 0.0.0.0:8080->80/tcp hungry_goldstine 2170ecfc4460 node:boron-slim "/bin/bash" 3 minutes ago Up 3 minutes 0.0.0.0:49160->8080/tcp angry_bassi $ docker ps -aq 0a6bae5fe144 2170ecfc4460 ``` ## `port`:查詢 container port 的對應狀況 ```shell $ docker port angry_bassi 8080/tcp -> 0.0.0.0:49160 ``` ## `run`:新建並啟動 container - 如果沒有指定 image tag,使用的 image tag 預設是 `latset` 版 - `-d`:背景 (Daemonized) 執行並列印 container ID - 設定 port mapping - `-P`:會從 host 中隨機取一個 port 出來使用 - `-p [hostIP]:[hostPort]:[ContainerPort]` - `-p 8080:80`:指定一個 port,host 對外開 8080 port,container 對內開 80 port - `-p 5000:5000 -p 8080:80`:同時指定多個 port - `-p 127.0.0.1:5000:5000`:指定特定的 ip address & port - `-p 127.0.0.1::5000`:指定特定的 ip address,但不指定 port - `-p 127.0.0.1:5000:5000/udp`:指定不同協定,例如 udp - `--name [containerName]`:設定 container 名稱,不必經過 build 才設 - 如果沒使用此參數,預設會隨意取名字,EX:`boring_perlman` - 設定環境變數 - `-e` - `-e MYSQL_ROOT_PASSWORD=password`:設定 root 密碼 = password - `docker run --name mymariadb -e MYSQL_ROOT_PASSWORD=password -d -p 3306:3306 mariadb:10.3` - `--env` - `docker run --env VAR1=value1 --env VAR2=value2 ubuntu env` - `--env-file` - `docker run --env-file ./env.list ubuntu env` - `-it`:此 container 具備了標準輸入 (即你目前使用的鍵盤) 和標準輸出 (即你目前操作的終端) - `-i`,`--interactive`:互動模式,讓 container 的標準輸入 (STDIN) 保持打開 (建立與容器標準輸入的互動進行連結) - `-t`,`--tty`:可使用終端機操作,讓 Docker 分配一個虛擬終端 (pseudo-TTY,PTY) 並綁定到 container 的標準輸入 (STDIN) 上 - 不能和 `-d` 參數一起使用 - `-v`,`--volume`:掛載主機上的指定目錄到 container 的指定目錄上 (將主機上的目前目錄 bind 到 container 的指定目錄) - `-v [hostPath]:[containerPath]`:掛載主機上的指定 `[hostPath]` 目錄到 container 的指定目錄 `[containerPath]` 上 - 例如:``-v `pwd`:/home/app``:任何在 `pwd` (目前) 目錄的文件都將會出現在容器內。這對於在主機和容器之間共享文件是非常有幫助的,例如掛載需要編譯的源代碼。為了保證可移植性 (並不是所有的系統的主機目錄都是可以用的),掛載主機目錄不需要從 Dockerfile 指定。當使用 `-v` 參數時,鏡像目錄下的任何文件都不會被覆制到 Volume 中。 (註:Volume 會複製到鏡像目錄,鏡像不會複製到卷) - 如果沒有 mount local 的話,container 會在內部虛擬一個 volume 環境,讓我們有一樣的空間可以用 - 優點:可在本地開發,但環境是在 container 內 - 若要掛載 data volume 為 read-only,加入 `:ro` 即可,container 內的綁定目錄是唯讀 - ``docker run --name mynginx -v `pwd`:/usr/share/nginx/html:ro -d -p 80:80 nginx:1.13`` - 若要掛載 data volume 為 read-write,加入 `:rw` 即可 - ==用 `-v` 時會產生 volume (較進階),之後研究==:https://philipzheng.gitbooks.io/docker_practice/content/data_management/volume.html - `--rm`:container 執行結束後就刪除 container,可以避免 container 在執行結束後有殘存東西,EX:volume。 - `--link [containerName]:[containerAlias]`:連結某個 container,讓 container 之間安全的進行互動。其中 `containerName` 是要連接的容器名稱,而 `containerAlias` 是這個連接的別名。 - `--expose`:從 container 開放 port - `--privileged`:容器會被允許直接設定主機的網路堆棧 (Network stack) - Docker 預設不允許 container 去存取設備檔案,要在 `docker run` 時加上 `--privileged` 參數才行。 ```shell $ docker run -p 8080:80 helloworld $ docker run -d -p 8080:80 helloworld # Ctrl + C 可以關閉執行中的 docker ``` ## `exec` 在一個正在執行的容器執行指令 ```shell $ docker exec -it [container] bash ``` ## `rename`:Container 重新命名 ```shell $ docker rename [container] new-name ``` ## `cp`:從 Container 複製檔案出來 ```shell $ docker cp [container]:path local-storage $ docker cp [container]:/etc/group /tmp ``` ## `attach`:進入 Container `-d` 模式後,attach container 會回到此 conatiner console,"**ctrl-p, ctrl-q detach**" ```shell $ docker attach [container] ``` attach 進去此 Container,若沒有用 `detach` 而是 `exit` 離開,此 Container 也會跟著離開而結束 ## `logs`:列出 Logs ```shell $ docker logs [container] $ docker logs -f [container] ``` ### 檢視最近建立的容器記錄檔資訊 (未測試) ```shell $ docker logs $(docker ps -lq) ``` ## `inspect`:查看 Container 詳細資訊 ```shell docker inspect [container] # 查看該 container 的 IP docker inspect mysql | grep IPAddress ``` ## `stop`、`kill`:停止執行 container > Kill 跟 Stop 的差別: > > - kill:不管容器同不同意,發送 SIGKILL 信號,強行終止 > - stop:先給容器發送一個 TERM 信號,讓 container 做一些退出前必須的保護性、安全性操作,然後讓 container 自動停止執行,如果在一段時間 (10s) 內,container 還是沒有停止,再發送SIGKILL信號,強行終止 > > – 參考至 [Docker kill 和 stop 有什麼區別 | DockOne.io](http://dockone.io/question/158) ```shell $ docker stop [container] $ docker kill [container] ``` ## `tag`:修改 tag ```shell $ docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG] $ docker tag my-mysql my-mysql:1.0 ``` ## `commit`:提交 container 為 image ```shell $ docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]] ``` | 簡寫,名稱 | 預設 | 說明 | | ----------------- | ----- | ---------------- | | `-a`,`--author` | false | 作者 | | `-m`,`--message` | false | 提交訊息 | | `-p`,`--pause` | true | 提交期間暫停執行容器 | ```shell $ docker commit -a "titangene <titangene.tw@gmail.com>" -m "new image" mysql titangene/my-mysql:v1.0 ``` ## `push`:上傳 image 至 registry ```shell $ docker push [image] ``` ```shell # 登入 Docker Hub $ docker login # 更改 名稱 $ docker tag hello-world titangene/hello-world # push image 至 registry $ docker push titangene/hello-world ``` ## `rm`:刪除 container ```shell $ docker rm ``` | 簡寫,名稱 | 預設 | 說明 | | ----------------- | ----- | -------------------- | | `-f`,`--force` | false | 強制刪除正在執行的容器,Docker 會發送 SIGKILL 信號給容器 | | `-l`,`--link` | false | 清理指定的 link | | `-v`,`--volumes` | false | 清理與容器關聯的 volume | :::info 注意:在刪除 container 之前要先用 `docker stop` 指令停止執行此 container,要不然就要使用 `-f` 參數強制刪除正在執行的 container。 ::: ### 刪除處於終止狀態的 container ```shell # 可用空格隔開,一次刪除多個 container $ docker rm [container...] $ docker rm my-mysql $ docker rm my-mysql my-php ``` ### 強制刪除執行中的 container `-f`,`--force`:強制刪除正在執行的容器,Docker 會發送 SIGKILL 信號給容器 ```shell $ docker rm -f [container...] ``` ### 一次刪除所有 container - `$()`:變數 - `docker ps`:顯示目前 container 狀態 - `-a`,`--all`:,顯示所有 container - `-q`,`--quiet`:只顯示 container ID - `-f`,`--filter`:篩選 ```shell $ echo $(docker ps -aq) a20bea839e27 5c0efd7da26f 84080b55a848 8646c97f4e61 fcb862e6e7cc $ docker rm $(docker ps -aq) # 或 $ docker container prune ``` 參考連結:[清理 Docker 的 container、image 與 volume by 匿蟒 (yanqd0)](https://github.com/yangtao309/yangtao309.github.com/issues/1) ### 刪除停止執行的 container - `-l`,`--link`:清理指定的 link - `-v`,`--volumes`:清理與容器關聯的 volume ```shell $ docker rm -lv [container...] ``` ### 一次刪除所有已停止執行的 container 在 Docker 應用生態中,容器的生成和銷毀是很頻繁的,不過手動去開啟容器,還是利用第三方資源調度工具來開啟 (比如 k8s、mesos)。對於過期、廢棄的容器我們將採用如下方式進行清理。 ```shell $ docker rm $(docker ps -q -f status=exited) # 或 # 一次刪除所有已停止執行,而且是幾週前的 container $ docker ps -a | grep 'weeks ago' | awk '{print $1}' | xargs --no-run-if-empty docker rm # 或 # 一次刪除狀態是 exited,而且是幾週前的 container $ docker ps --filter "status=exited" | grep 'weeks ago' | awk '{print $1}' | xargs --no-run-if-empty docker rm ``` 參考連結:[Docker 廢棄資源、碎片清理 by yangtao309](https://github.com/yangtao309/yangtao309.github.com/issues/1) ### 刪除指定 image 所建立的 container (未測試) ```shell $ docker rm `docker ps -a | grep <image_name>:<image_version> | cut -f1 -d" "` ``` ## `rmi`:刪除 local image ```shell $ docker rmi ``` | 簡寫,名稱 | 預設 | 說明 | | ----------------- | ----- | --- | | `-f`,`--force` | false | 強制刪除 image | | `--no-prune` | false | 不要刪除未標記的 parent image | :::warning 注意:在刪除 image 之前要先用 `docker rm` 指令刪掉依賴於該 image 的所有 container。 ::: ### 刪除一個或多個 image ```shell # 可用空格隔開,一次刪除多個 image $ docker rmi [image...] $ docker rmi my-mysql $ docker rmi my-mysql my-php ``` ### 強制刪除 image `-f`,`--force`:強制刪除 image ```shell $ docker rmi -f [image...] ``` ### 一次刪除所有 image ```shell $ docker rmi $(docker images -q) ``` ### 一次刪除所有 dangling image (虛懸,懸掛,`<none>`,沒有 tag 的 image) 在 image 列表中,有一些特殊的 image,既沒有 repo 名,也沒有 tag,均為 `<none>`: ```shell $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE <none> <none> 77a90b6059cf About an hour ago 391MB ... ``` 這些 image 原本是有 image 名和 tag 的,有些隨著官方 image 維護,發佈了新版本後,重新 pull 同 tag 的 image 時,該 image 名被轉移到了新下載的 image 身上,而舊的 image 上的這個名稱則被取消,從而成為了 `<none>`。除了 `docker pull` 可能導致這種情況,`docker build` 也同樣可以導致這種現象。由於新舊 image 同名,舊 image 名稱被取消,從而出現 repo 名、tag 均為 `<none>` 的 image。這類無 tag 的 image 也被稱為 **dangling image** (虛懸鏡像,或稱 懸掛鏡像),可以用下面的指令專門顯示這類 image: ```shell $ docker images -f dangling=true REPOSITORY TAG IMAGE ID CREATED SIZE <none> <none> 77a90b6059cf About an hour ago 391MB ``` image 在 Docker 應用生態中扮演重要角色,對一個可運行單元的程式組合,呈現一個獨立的執行基 礎。一般我們在運行 Docker 容器時候,需要從倉庫拉取 image,同樣會出現廢棄 image 需要清理。 ```shell $ docker rmi $(docker images -q -f dangling=true) # 或 $ docker images | grep "<none>" | awk '{print $3}' | xargs docker rmi ``` ### 參考連結: - [Docker 廢棄資源、碎片清理 by yangtao309](https://github.com/yangtao309/yangtao309.github.com/issues/1) - [Github Gist:anildigital/gist:862675ec1b7bccabc311](https://gist.github.com/anildigital/862675ec1b7bccabc311) - [Docker —— 從入門到實踐:列出鏡像 - 虛懸鏡像 by yeasy](https://yeasy.gitbooks.io/docker_practice/content/image/list.html#%E8%99%9A%E6%82%AC%E9%95%9C%E5%83%8F) ## `stats`:顯示容器即時串流資源的使用統計資料 預設顯示所有正在執行的容器資源使用量,包括 CPU、記憶體、網路和磁碟 I/O - `-a`,`--all`:顯示所有容器 ```shell $ docker stats [OPTIONS] [CONTAINER...] $ docker stats CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % NET I/O BLOCK I/O PIDS b95a83497c91 bar 0.28% 5.629MiB / 1.952GiB 0.28% 916B / 0B 147kB / 0B 9 67b2525d8ad1 foobar 0.00% 1.727MiB / 1.952GiB 0.09% 2.48kB / 0B 4.11MB / 0B 2 ``` ### 相關連結 - [用 docker stats 指令觀察 container 的資源使用量 | EPHRAIN 亂打一通的心情日記](https://ephrain.net/docker-用-docker-stats-指令觀察-container-的資源使用量//) ## 其他指令 (未整理) ```shell attach Attach to a running container build Build an image from a 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 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 history Show the history of an image images List images import Import the contents from a tarball to create a filesystem image info Display system-wide information inspect Return low-level information on a container or image kill Kill a running container load Load an image from a tar archive or STDIN login Log in to a Docker registry logout Log out from a Docker registry logs Fetch the logs of a container network Manage Docker networks pause Pause all processes within a container 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 a container rm Remove one or more containers rmi Remove one or more images run Run a command in a new container save Save one or more images to a tar archive search Search the Docker Hub for images start Start one or more stopped containers stats Display a live stream of container(s) resource usage statistics stop Stop a running container tag Tag an image into a repository top Display the running processes of a container unpause Unpause all processes within a container update Update configuration of one or more containers version Show the Docker version information volume Manage Docker volumes wait Block until a container stops, then print its exit code ```