docker容器的使用和操作


一、容器概念

1、什么是容器

容器(Container):在docker中指的是從鏡像創建的應用程序運行實例。

可以將容器看作將一個 應用程序及其依賴環境打包 而成的集裝箱。

容器的實質是進程,與直接在主機執行不同,容器進程在屬於自己的獨立的命名空間內運行。這種特性使得容器封裝的應用程序比直接在主機上運行的應用程序更加安全。

2、容器的基本信息

# docker ps -a 顯示本地所有的容器
[root@hqs imglayers]# docker ps -a
容器ID             容器使用的鏡像         啟動容器時執行的命令       容器創建時間         容器運行狀態               容器對外發布端口    容器名稱
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS            NAMES
0d5df0735154        imglayers-test      "/bin/sh -c 'python …"   32 minutes ago      Exited (0) 32 minutes ago                    wizardly_lehmann
cd866d55dc6a        imglayers-test      "/bin/sh -c 'python …"   41 minutes ago      Exited (0) 41 minutes ago                    charming_zhukovsky

# --no-trunc顯示完整ID
[root@hqs imglayers]# docker ps -a --no-trunc
CONTAINER ID                                                       IMAGE               COMMAND                             CREATED             STATUS                          PORTS               NAMES
0d5df073515409bd606139f4c0dd8d5bf91360fa15700a7e64935e8da35bb8cd   imglayers-test      "/bin/sh -c 'python /app/app.py'"   40 minutes ago      Exited (0) About a minute ago                       wizardly_lehmann
cd866d55dc6a8b626b3c8f2695bc43cc2bcf91adc58c549413dad3855cfd6947   imglayers-test      "/bin/sh -c 'python /app/app.py'"   48 minutes ago      Exited (0) 48 minutes ago                           charming_zhukovsky

容器的唯一標識容器ID與鏡像ID一樣采用UUID形式,由64個十六進制字符組成。通常采用前12個字符,也可以使用更短格式(前幾個字符)。

# 完整ID標識
[root@hqs imglayers]# docker start 0d5df073515409bd606139f4c0dd8d5bf91360fa15700a7e64935e8da35bb8cd
0d5df073515409bd606139f4c0dd8d5bf91360fa15700a7e64935e8da35bb8cd
# 前12字符ID標識
[root@hqs imglayers]# docker start 0d5df0735154
0d5df0735154
# 更短字符ID標識
[root@hqs imglayers]# docker start 0d5
0d5

容器ID能保證唯一性,但是不方便記憶,可以使用容器名稱來引用容器。
容器名稱默認是Docker自動生成的,也可以在執行 docker run 的時候用 --name 選項自行指定。
還可以使用 docker rename 命令重命名容器。

# 創建容器docker自動生成名字
[root@hqs imglayers]# docker run -tid ubuntu:16.04 /bin/bash
C6e384fa3274d59bf7820cb3a23911fcf7e17dd8a2d6316a917422bfea93a2898
[root@hqs imglayers]# docker ps -a          
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
6e384fa3274d        ubuntu:16.04        "/bin/bash"         2 minutes ago       Up 2 minutes                            quirky_liskov

# 容器名稱引用容器
[root@hqs imglayers]# docker stop quirky_liskov
quirky_liskov

# 創建時用--name指定容器名
[root@hqs imglayers]# docker run --name hqs_test  imglayers-test
Hello,  World!@!!!!!!
[root@hqs imglayers]# docker ps -a
CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                      PORTS               NAMES
89076ab59bd1        imglayers-test      "/bin/sh -c 'python …"   47 seconds ago      Exited (0) 46 seconds ago                       hqs_test

3、可寫的容器層

每個容器都有自己的可寫容器層,所有的改變都存儲在這個容器層。

容器被刪除時,可寫層也被刪除,底層鏡像沒有影響。——》容器操作不會影響到鏡像。

Docker使用存儲驅動來管理鏡像層和容器層的內容。

4、磁盤的容器大小

可以使用 docker ps -s可以輸出SIZE列,顯示容器所用的空間。

[root@hqs ~]# docker ps -s
CONTAINER ID        IMAGE            COMMAND          CREATED          STATUS          PORTS        NAMES           SIZE
6e384fa3274d        ubuntu:16.04     "/bin/bash"      7 hours ago      Up 4 minutes                 newbee         164B (virtual 135MB)

SIZE列第一個值:容器可寫層當前所用的數據大小。
SIZE列第二個值:虛擬大小,在括號中用virtual標注,容器所用只讀鏡像的數據量和容器可寫層大小的和。

磁盤上正在運行的容器所用的磁盤空間是每個容器大小和只讀鏡像值的總和。

# 再啟動一個ubuntu容器
[root@hqs ~]# docker run -tid ubuntu:16.04 /bin/bash
ed278a030f5a9ae3f6cfe87a765c94b34975cc14cd4d90fa1bf11fb51ee345ba
# 復制一個文件到容器中
[root@hqs hqs]# docker cp ./asdadw.pdf ed278a030f5a:/home
# 查看容器大小
[root@hqs hqs]# docker ps -s
CONTAINER ID        IMAGE             COMMAND         CREATED           STATUS          PORTS     NAMES            SIZE
ed278a030f5a        ubuntu:16.04      "/bin/bash"     7 minutes ago     Up 7 minutes              kind_bartik      6.58MB (virtual 141MB)
6e384fa3274d        ubuntu:16.04      "/bin/bash"     7 hours ago       Up 15 minutes             newbee           164B (virtual 135MB)
# 兩個容器所用的磁盤空間:164B+6.58M+135M由三值的和得到。

5、寫時復制策略

寫時復制策略:高效的文件共享和復制策略。特性如下:

  1. 容器任意層要讀取某一層文件時,可以直接使用。
  2. 容器任意層要修改某一層文件時,文件將復制到該層並修改,隱藏原文件。
  3. 一層層拉取鏡像時,可以不拉取已經下載好的共享鏡像層。
  4. 復制提升容器效率,僅需修改的文件會復制到可寫層,讓可寫層盡量少占用空間。

修改容器已有文件,存儲驅動執行寫時復制策略,aufs、overlay、overlay2驅動執行步驟:

  1. 從鏡像各層中搜索要修改的文件。從最新的層開始直到最底層,一次一層。被找到的文件將被添加到緩存中以加速后續操作。
  2. 對找到的文件的第1個副本執行copy_up操作,將其復制到容器的可寫層中。
  3. 任何修改只針對該文件的這個副本,容器不能看見該文件位於低層的只讀副本
# 登錄容器后刪除文件和命令
[root@hqs hqs]# docker exec -ti 6e384fa3274d /bin/bash
root@6e384fa3274d:/usr/bin# rm find && rm wc && rm du && rm tr

# 查看容器空間變化——》可寫層數據變多
[root@hqs hqs]# docker ps -s
CONTAINER ID      IMAGE            COMMAND         CREATED           STATUS          PORTS    NAMES            SIZE
ed278a030f5a      ubuntu:16.04     "/bin/bash"     14 minutes ago    Up 14 minutes            kind_bartik      6.58MB (virtual 141MB)
6e384fa3274d      ubuntu:16.04     "/bin/bash"     7 hours ago       Up 23 minutes            newbee           244B (virtual 135MB)

6、網絡問題處理

(1)方法一:重置docker0網絡

# 安照brctl
yum install -y autoconf
yum install -y gcc
wget http://mirrors.edge.kernel.org/pub/linux/utils/net/bridge-utils/bridge-utils-1.6.tar.xz
tar -xvf bridge-utils-1.6.tar.xz 
cd bridge-utils-1.6
autoconf
./configure
make
make install

# 重置docker0網橋,並重啟docker服務
systemctl stop docker
ps auxf  | grep dockerd
kill -9 1675
brctl show
ip link set dev docker0 down
brctl delbr docker0
systemctl restart docker

(2)升級centos系統的內核

docker 加載內核的bridge.ko 驅動異常,導致docker0 網卡無法轉發數據包,也就是系統內核的網橋模塊bridge.ko 加載失敗導致的。
具體的解決辦法就是升級centos系統的內核.

[root@localhost ~]# rpm --import https://www.elrepo.org/RPM-GPG-KEY-elrepo.org
[root@localhost ~]# rpm -Uvh http://www.elrepo.org/elrepo-release-7.0-3.el7.elrepo.noarch.rpm
[root@localhost ~]# yum --enablerepo=elrepo-kernel install kernel-ml
[root@localhost ~]# vim /etc/default/grub 
   修改 GRUB_DEFAULT=0
[root@localhost ~]# grub2-mkconfig -o /boot/grub2/grub.cfg
[root@localhost ~]# reboot

# 重啟后創建容器可以ping通
[root@localhost ~]# ping 172.17.0.2
PING 172.17.0.2 (172.17.0.2) 56(84) bytes of data.
64 bytes from 172.17.0.2: icmp_seq=1 ttl=64 time=0.042 ms
64 bytes from 172.17.0.2: icmp_seq=2 ttl=64 time=0.040 ms

二、容器操作命令

容器操作命令:容器生命周期管理操作(創建、啟動、停止、刪除等)、容器運維操作(查看、連接、日志、事件等)。
操作容器可以使用容器的ID或容器的名稱進行標識。
Docker新提供了一個統一的容器管理命令 docker container,功能和語法基本和 docker 子命令相同。

1、容器操作大全

# docker container 語法
Usage:  docker container COMMAND
Manage containers
Commands:
  attach      Attach local standard input, output, and error streams to a running container    # 連接正在運行的容器
  commit      Create a new image from a containers 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 containers filesystem           # 檢查容器創建以來文件系統上文件或目錄的更改
  exec        Run a command in a running container                                         # 從正在運行的容器中執行命令
  export      Export a containers filesystem as a tar archive                              # 將容器文件系統導出為歸檔文件
  inspect     Display detailed information on one or more containers                       # 顯示容器詳細信息
  kill        Kill one or more running containers                                          # 殺死一個正在運行的容器(強關)
  logs        Fetch the logs of a container                                                # 獲取容器的日志信息
  ls          List containers                                                         # 輸出容器列表(docker ps)
  pause       Pause all processes within one or more containers                            # 暫停一個或多個容器的所有進程
  port        List port mappings or a specific mapping for the container                   # 列出容器的端口映射或特定的映射
  prune       Remove all stopped containers                                           # 刪除所有停止的容器(docker子命令沒有的)
  rename      Rename a container                                                           # 對容器改名
  restart     Restart one or more containers                                               # 重啟容器
  rm          Remove one or more containers                                                # 刪除容器
  run         Run a command in a new container                                             # 創建新容器並執行命令
  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                                          # 停止容器
  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                               # 更新容器配置
  wait        Block until one or more containers stop, then print their exit codes         # 阻塞容器運行,直到容器停止運行,輸出退出碼

2、run創建並啟動容器

使用 docker run 創建一個新的容器並啟動,docker在后台運行的操作如下:

1.檢查本地是否存在指定的鏡像,如沒有就從倉庫自動下載
2.基於鏡像創建容器並啟動
3.為容器分配文件系統,並在鏡像層頂部增加一個可讀寫的容器層
4.從主機配置的網橋接口將一個虛擬接口橋接到容器
5.從網橋的地址池給容器分配一個IP地址
6.運行用戶指定的應用程序
7.根據設置決定是否終止容器運行

網絡相關選項案例和使用

# 語法
docker container run [OPTIONS選項] IMAGE鏡像 [COMMAND命令] [ARG參數...]
# 常用選項
-d(--detach):后台運行容器,並返回容器ID。
-i(--interactive):容器的標准輸入保持打開。
-t(--tty):為容器重新分配一個偽輸入終端(Pseudo TTY)。
-p(--publish):設置端口映射,格式:'主機端口:容器端口'。
-P:發布容器中所有暴露的端口。
--name:為容器指定名稱。
--rm:容器退出時自動刪除。
--restart:設置重啟策略,如設置always,表示容器即使異常退出也會自動重啟
--dns:為容器設置DNS服務器的IP地址(默認是和主機的dns設置一致).可以使用多個--dns為容器指定多個DNS服務器。
--dns-option:為容器設置表示DNS選項及值的鍵值對
--dns-search:為容器指定一個DNS搜索域.搜索非全稱的主機名。可以使用多個--dns-search的選項
-h, --hostname:為容器指定自定義的主機名
--mac-address:為容器指定一個MAC地址
--ip, --ip6:明確指定分配給該網絡容器的ip地址
--network-alias:指定容器在網絡中的別名
--network:選項設置容器要連接的網絡,即網絡模式
-v(--volume):將主機本地的目錄和容器目錄綁定,實現數據的持久化,將數據存儲在本地文件系統中
--mount:綁定掛載、卷、tmpfs類型都支持,參數由多個以逗號分隔的鍵值對組成
--volumes-from:可基於`卷容器`創建一個新的容器,新容器掛載 `卷容器` 提供的卷。

(1)啟動容器執行命令后自動終止容器

[root@hqs hqs]# docker run ubuntu:16.04 /bin/echo '這是一個自動終止的容器'
這是一個自動終止的容器
[root@hqs hqs]# docker ps -a
CONTAINER ID      IMAGE             COMMAND             CREATED           STATUS                     PORTS        NAMES
d16fabb6b96e      ubuntu:16.04     "/bin/echo 這是一個…"  7 seconds ago    Exited (0) 6 seconds ago               blissful_mccarthy

# 后台運行的示例
[root@localhost ~]# docker run -dit centos/httpd /bin/echo '自動停止的容器'
[root@localhost ~]# docker logs 75b83820ce59
自動停止的容器

(2)啟動容器執行命令后退出自動刪除

# --rm 容器退出自動刪除
[root@hqs hqs]# docker run --name test-kobe  --rm  centos  /bin/bash 
[root@hqs hqs]# docker run --rm ubuntu:16.04  /bin/echo '這是一個自動終止的容器'
這是一個自動終止的容器
[root@hqs hqs]# docker ps -a

(3)啟動容器並允許用戶交互

# -t:分配一個偽終端並綁定到容器的標准輸入;-i:讓容器的標准輸入保持打卡,自動進入容器交互模式
# 不加-d的話,只要退出容器(exit或者Ctrl+D均可退出容器),容器自動終止
[root@hqs hqs]# docker run -ti ubuntu:16.04 /bin/bash
root@5565c81f49bb:/# ls
bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@5565c81f49bb:/# exit
[root@hqs ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                   PORTS          NAMES
5565c81f49bb        ubuntu:16.04        "/bin/bash"         34 seconds ago      Exited (1) 3 seconds ago               cranky_kapitsa

(4)啟動容器並讓其以守護進程的形式在后台運行

很多情況下容器都會采用守護進程方式運行。需要使用 -d 選項。

[root@hqs hqs]# docker pull httpd
[root@hqs hqs]# docker run -d -p 80:80 --name testweb httpd
dbad1b30d9e76523be5b13967edefe5585f4a333d1dfb4637d32c38b97986c59
[root@hqs hqs]# docker ps 
CONTAINER ID        IMAGE        COMMAND              CREATED             STATUS              PORTS                NAMES
dbad1b30d9e7        httpd        "httpd-foreground"   8 seconds ago       Up 7 seconds        0.0.0.0:80->80/tcp   testweb
# 使用docker logs查看容器的輸出信息
[root@hqs hqs]# docker logs testweb
AH00558: httpd: Could not reliably determine the servers fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
AH00558: httpd: Could not reliably determine the servers fully qualified domain name, using 172.17.0.2. Set the 'ServerName' directive globally to suppress this message
[Wed Mar 16 01:42:27.920912 2022] [mpm_event:notice] [pid 1:tid 140667220098368] AH00489: Apache/2.4.52 (Unix) configured -- resuming normal operations
[Wed Mar 16 01:42:27.920990 2022] [core:notice] [pid 1:tid 140667220098368] AH00094: Command line: 'httpd -D FOREGROUND'

# 直接-d啟動ubuntu容器:命令/bin/bash默認情況下,容器立即退出,如同bash沒有連接到終端且無法運行
[root@hqs ~]# docker run -d ubuntu:16.04 /bin/bash  

[root@hqs ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
dd1120bff856        ubuntu:16.04        "/bin/bash"         6 seconds ago       Exited (0) 5 seconds ago                       gallant_bel
# -t選項分配“偽tty”,可以讓bash繼續無限期地運行(它認為連接到了交互式TTY)
[root@hqs ~]# docker run -td ubuntu:16.04 /bin/bash
849eeb5ea98bedd1120bff856114be2afa110c874c9cec2f73f22ad736f6f244b246e7f1f4ed404bd6d019f8b480d72170be6f2d4fab576f2362327dcb42bf28
[root@hqs ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                PORTS             NAMES
849eeb5ea98b        ubuntu:16.04        "/bin/bash"         2 seconds ago       Up 1 second                             crazy_gates

(5)-P發布容器所有暴露的端口

通過docker run命令創建容器時使用-P選項將容器中所有暴露的端口發布到Docker主機上隨機的高端地址端口中。
要求容器中要發布的端口必須提前暴露出來。
有兩種方式可以暴露端口:一種是在Dockerfile中使用EXPOSE指令定義,另一種是執行docker run命令創建容器時使用--expose選項指定。

# 1.創建容器使用-P選項發布httpd服務
[root@hqs ~]# docker pull httpd
[root@hqs ~]# docker run --rm -d --name websrv -P httpd
adc5a789b20c170b229d6aafa879fd2cad54eb363259be994e6d21841ecf08f5

# 2.使用docker port 查看容器的端口映射設置
[root@hqs ~]# docker port websrv
80/tcp -> 0.0.0.0:49153               《————左邊是容器發布的端口80,右邊是映射到主機上的IP地址和端口49153
80/tcp -> :::49153

# 3.使用curl命令訪問服務測試
[root@hqs ~]# curl http://192.168.100.111:49153
<html><body><h1>It works!</h1></body></html>

(6)-p發布容器特定端口

通過 docker run 命令啟動容器,可以使用 -p 選項將容器的一個或多個端口映射到主機上。

可以多次使用 -p 設置任意數量的端口映射。

選項格式 說明 示例
-p 主機端口:容器端口 映射主機上所有網絡接口的地址 -p 8080:80
-p 主機IP地址:主機端口:容器端口 映射指定地址的指定端口 -p 192.168.10.10:80:5000
-p 主機IP地址::容器端口 映射指定地址的任一端口 -p 127.0.0.1::5010
-p 容器端口 自動分配主機端口 -p 5200
-p 以上各種格式/udp 發布UDP端口(默認為TCP端口) -p 8080:80/udp
-p 以上各種格式/tcp -p 以上各種格式/udp 同時發布TCP和UDP端口 -p 8080:80/tcp -p 8080:80/udp
# 案例1:映射主機上所有網絡接口的地址
[root@hqs ~]# docker run -dti --name websrv -p 8000:80 httpd
edc35a9e8b6dded9abb82906e02258cba32c608bf7e3face09e9d3d4308a60fc
[root@hqs ~]# docker port websrv
80/tcp -> 0.0.0.0:8000
80/tcp -> :::8000
[root@hqs ~]# curl http://192.168.100.111:8000
<html><body><h1>It works!</h1></body></html>

# 案例2:映射指定地址的指定端口
[root@hqs ~]# docker run -dti --name websrv2 -p 192.168.100.111:8001:80 httpd
1d19b8a06483811bab9b5b5767cf8c38aabe911f3ed2df5250a1e155a7276e7e
[root@hqs ~]# docker port websrv2
80/tcp -> 192.168.100.111:8001
[root@hqs ~]# curl http://192.168.100.111:8001
<html><body><h1>It works!</h1></body></html>

# 案例3:映射指定地址的任一端口
[root@hqs ~]# docker stop websrv websrv2
websrv
websrv2
[root@hqs ~]# docker run -dti --name websrv3 -p 127.0.0.1::80 httpd
19057827c1c7477e860a2f6ebd6c1dd4c1f2fd4386c61a3c6aafcf39a317ea65
[root@hqs ~]# docker port websrv3
80/tcp -> 127.0.0.1:49153
[root@hqs ~]# curl http://127.0.0.1:49153
<html><body><h1>It works!</h1></body></html>

# 案例4:自動分配主機端口
[root@hqs ~]# docker run -dti --name websrv4 -p 80 httpd
3ccb4a496636eb774452c900acdd8f3ca0f4d5bf99c58618e266e6f83ae6c55b
[root@hqs ~]# docker stop websrv3
websrv3
[root@hqs ~]# docker port websrv4
80/tcp -> 0.0.0.0:49154
80/tcp -> :::49154
[root@hqs ~]# curl http://192.168.100.111:49154
<html><body><h1>It works!</h1></body></html>

# 案例5:發布UDP端口
[root@hqs ~]# docker run -dti --name websrv5 -p 8080:80/udp httpd
9ae61cbd4e67b606ee38ace205036c458edf6eecb67b908a87e9363ae63a8f55
[root@hqs ~]# docker port websrv5
80/udp -> 0.0.0.0:8080
80/udp -> :::8080

# 案例6:同時發布TCP和UDP端口
[root@hqs ~]# docker run -dti --name websrv6 -p 8080:80/tcp -p 8080:80/udp httpd
d13977a616392d890c6335ba4446d88eeb033e65c8fafb9379c0593e50dde861
[root@hqs ~]# docker port websrv6
80/tcp -> 0.0.0.0:8080
80/tcp -> :::8080
80/udp -> 0.0.0.0:8080
80/udp -> :::8080

3、create創建容器

使用 docker create 命令創建一個新的容器,但不啟動。
語法和參數和docker run 基本相同。

# 語法
docker container create [OPTIONS選項] IMAGE鏡像 [COMMAND命令] [ARG參數...]

# 案例:基於busybox鏡像創建一個容器
[root@hqs ~]# docker create -t -i busybox
Unable to find image 'busybox:latest' locally
latest: Pulling from library/busybox
5cc84ad355aa: Pull complete 
Digest: sha256:5acba83a746c7608ed544dc1533b87c737a0b0fb730301639a0179f9344b1678
Status: Downloaded newer image for busybox:latest
95127ca1f247c7d94e9e838432e5f137adef78efe3ea3ae10bc59e58eaffb451
[root@hqs ~]# docker ps -a
CONTAINER ID     IMAGE      COMMAND     CREATED          STATUS         PORTS       NAMES
95127ca1f247     busybox    "sh"        3 minutes ago    Created                   keen_visvesvaray

容器處於Created(已創建)狀態,后面可以使用 docker start 啟動容器。

4、start啟動容器

使用 docker start 啟動一個或多個停止的容器。

# 語法
[root@hqs ~]# docker start --help
Usage:  docker start [OPTIONS] CONTAINER [CONTAINER...]
Start one or more stopped containers
Options:
  -a, --attach               Attach STDOUT/STDERR and forward signals                # 連接標准輸出/標准錯誤並轉發信號
      --detach-keys string   Override the key sequence for detaching a container     # 覆蓋分離容器的鍵順序
  -i, --interactive          Attach containers STDIN            # 附加容器的標准輸入

# 啟動前面創建的busybox容器
[root@hqs ~]# docker start 95127ca1f247
95127ca1f247
[root@hqs ~]# docker ps 
CONTAINER ID        IMAGE        COMMAND     CREATED             STATUS            PORTS        NAMES
95127ca1f247        busybox      "sh"        10 minutes ago      Up 8 seconds                   keen_visvesvaraya

5、停止\強停\暫停容器

(1)stop停止容器

停止一個或多個處於運行狀態的容器。

# 語法:
[root@hqs ~]# docker container stop --help
Usage:  docker container stop [OPTIONS] CONTAINER [CONTAINER...]
Stop one or more running containers
Options:
  -s, --signal string   Signal to send to the container             # 發送給容器的信號
  -t, --time int   Seconds to wait for stop before killing it       # 等多少秒之后停止容器(默認是10秒)
                   (default 10)

# 案例
[root@hqs ~]# docker stop 95127ca1f247
95127ca1f247
[root@hqs ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND              CREATED             STATUS                         PORTS          NAMES
95127ca1f247        busybox             "sh"                 About an hour ago   Exited (137) 5 seconds ago                    keen_visvesvaraya
[root@hqs ~]# docker container stop f8cf60a42d01
f8cf60a42d01
[root@hqs ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND              CREATED             STATUS                         PORTS               NAMES
95127ca1f247        busybox             "sh"                 About an hour ago   Exited (137) 2 minutes ago                         keen_visvesvaraya
f8cf60a42d01        httpd               "httpd-foreground"   About an hour ago   Exited (0) 14 seconds ago                          testweb

# -t等一段時間后停止容器
[root@hqs ~]# docker stop -t 3 6b15972463bc 994f78b1a1bd
執行后等待了三秒繼續輸出id
6b15972463bc
994f78b1a1bd

# 批量停止運行的容器
[root@localhost ~]# docker stop $(docker ps -q)
b858556198c4
8e2f2883fddf

(2)kill殺死(強停)容器

使用 docker kill 命令可以殺死(強行停止)一個或多個容器。

# 語法
[root@hqs ~]# docker container kill --help
Usage:  docker container kill [OPTIONS選項] CONTAINER容器 [CONTAINER...]
Kill one or more running containers
Options:
  -s, --signal string   Signal to send to the container       # 傳給容器的信號,默認是傳遞kill
                        (default "KILL")

# 案例
[root@hqs ~]# docker kill bf1128a4d870
bf1128a4d870
[root@hqs ~]# docker container kill 5565c81f49bb
5565c81f49bb
[root@hqs ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND              CREATED             STATUS                         PORTS          NAMES
bf1128a4d870        centos              "/bin/bash"          2 hours ago         Exited (137) 26 seconds ago                   reverent_shamir
5565c81f49bb        ubuntu:16.04        "/bin/bash"          9 hours ago         Exited (137) 17 seconds ago                   quizzical_buck

(3)pause暫停(掛起)容器

使用 docker pause 命令可以暫停容器中所有的進程。
使用 docker unpause 命令可以恢復容器中被暫停的所有進程。

# 語法
[root@hqs ~]# docker pause --help
Usage:  docker pause CONTAINER [CONTAINER...]
Pause all processes within one or more containers
[root@hqs ~]# docker unpause --help
Usage:  docker unpause CONTAINER [CONTAINER...]
Unpause all processes within one or more containers

# 案例
[root@hqs ~]# docker start 379effe4cc2a bf1128a4d870
379effe4cc2a
bf1128a4d870
[root@hqs ~]# docker pause 379effe4cc2a
379effe4cc2a
[root@hqs ~]# docker ps 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                       PORTS        NAMES
379effe4cc2a        centos              "/bin/bash"         2 hours ago         Up About a minute (Paused)                dreamy_hertz
bf1128a4d870        centos              "/bin/bash"         2 hours ago         Up About a minute                         reverent_shamir
[root@hqs ~]# docker unpause 379effe4cc2a
379effe4cc2a
[root@hqs ~]# docker ps 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
379effe4cc2a        centos              "/bin/bash"         2 hours ago         Up About a minute                       dreamy_hertz
bf1128a4d870        centos              "/bin/bash"         2 hours ago         Up About a minute                       reverent_shamir

6、刪除容器相關

(1)rm刪除容器

可以使用 docker rm 命令刪除一個或多個容器。

# 語法
[root@hqs ~]# docker rm --help
Usage:  docker rm [OPTIONS選項] CONTAINER [CONTAINER...]
Remove one or more containers
Options:
  -f, --force     Force the removal of a running container (uses SIGKILL)     # 使用SIGKILL信號強制刪除運行中的容器
  -l, --link      Remove the specified link                                   # 刪除容器的網絡連接
  -v, --volumes   Remove the volumes associated with the container            # 刪除容器關聯的卷

# 正常刪除運行中容器:先停止后刪除
[root@hqs ~]# docker rm 379effe4cc2a
Error response from daemon: You cannot remove a running container 379effe4cc2a25175892e3720c30293bf0d21f0f60513052aeb29e0b7f0bd7df. Stop the container before attempting removal or force remove
[root@hqs ~]# docker stop 379effe4cc2a
379effe4cc2a
[root@hqs ~]# docker rm 379effe4cc2a  
379effe4cc2a

# -f強制刪除運行中容器
[root@hqs ~]# docker rm -f bf1128a4d870
bf1128a4d870

# 正則表達式篩選批量刪除容器
[root@hqs hqs]# docker ps -a | grep imglayers-test | awk '{print $1}'
1d54e625e6db
0d5df0735154
cd866d55dc6a
[root@hqs hqs]# docker rm $(docker ps -a | grep imglayers-test | awk '{print $1}') 
1d54e625e6db
0d5df0735154
cd866d55dc6a

# -q選項獲取id批量刪除
[root@hqs ~]# docker ps -aq
95127ca1f247
f8cf60a42d01
482f41cde0d4
f06b3e532208
3700446ead6f
5565c81f49bb
[root@hqs ~]# docker rm -f $(docker ps -qa)
95127ca1f247
f8cf60a42d01
482f41cde0d4
f06b3e532208
3700446ead6f
5565c81f49bb
[root@hqs ~]# docker ps -a

(2)prune刪除容器

使用 docker container prune 命令刪除所有停止執行的容器。docker子命令沒有對應的命令。

# 語法:
[root@hqs ~]# docker container prune --help
Usage:  docker container prune [OPTIONS]
Remove all stopped containers
Options:
      --filter filter   Provide filter values (e.g. 'until=<timestamp>')     # 提供過濾值
  -f, --force           Do not prompt for confirmation                    # 不要提示確認

# 示例:prune命令將created和exited狀態的容器均刪除
# 經測試處於pause狀態的容器不會被刪除
[root@localhost ~]# docker create ubuntu
2c0d462749595267d6ab465fa2c269e491aef72223079bf90371b711cefc977f
[root@localhost ~]# docker run ubuntu /bin/bash
[root@localhost ~]# docker run ubuntu /bin/bash
[root@localhost ~]# docker run ubuntu /bin/bash
[root@localhost ~]# docker run -tid ubuntu /bin/bash
0dbce79c6dcbaf4ff16f182d6d5dffd5e9c26411b95046dcc5392fbd04d1b596
[root@localhost ~]# docker run -tid ubuntu /bin/bash
cf06c4d31abd19c4d2d71693b733d0373b33f37f6aa6481180714b5e5622c8fc
[root@localhost ~]# docker run -tid ubuntu /bin/bash
deede844f4e068dffb6b0e02c4a340d026784b8b7576ef1616b6134e804c39e5
[root@localhost ~]# docker pause musing_thompson
musing_thompson
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                      PORTS     NAMES
deede844f4e0   ubuntu    "/bin/bash"   18 seconds ago   Up 17 seconds (Paused)                musing_thompson
cf06c4d31abd   ubuntu    "/bin/bash"   19 seconds ago   Up 18 seconds                         ecstatic_jepsen
0dbce79c6dcb   ubuntu    "/bin/bash"   20 seconds ago   Up 20 seconds                         pensive_dewdney
aab6d833ca60   ubuntu    "/bin/bash"   31 seconds ago   Exited (0) 30 seconds ago             great_yonath
9b028538463a   ubuntu    "/bin/bash"   32 seconds ago   Exited (0) 31 seconds ago             blissful_wright
dee6d8ed24e8   ubuntu    "/bin/bash"   33 seconds ago   Exited (0) 32 seconds ago             compassionate_herschel
2c0d46274959   ubuntu    "bash"        47 seconds ago   Created                               hopeful_greider
# prune刪除停止的容器
[root@localhost ~]# docker container prune
WARNING! This will remove all stopped containers.
Are you sure you want to continue? [y/N] y
Deleted Containers:
aab6d833ca60c4dd472966d3c2a4c1f9d7657eb0cac5b60f6a8fd3e7dc3cadc7
9b028538463acde99ea451da8834fba1f4f6b4df2140eb00c3ef207ca744d7ea
dee6d8ed24e8fca026393422f4df61f6f3f4f95b98e7a47924e38ff691683d8e
2c0d462749595267d6ab465fa2c269e491aef72223079bf90371b711cefc977f
# 結果發現up 和paused的容器未刪除
[root@localhost ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                  PORTS     NAMES
deede844f4e0   ubuntu    "/bin/bash"   2 minutes ago   Up 2 minutes (Paused)             musing_thompson
cf06c4d31abd   ubuntu    "/bin/bash"   2 minutes ago   Up 2 minutes                      ecstatic_jepsen
0dbce79c6dcb   ubuntu    "/bin/bash"   2 minutes ago   Up 2 minutes                      pensive_dewdney

7、rename重命名容器

使用 docker rename 命令為容器重新命名。

# 語法
[root@hqs ~]# docker rename --help
Usage:  docker rename CONTAINER容器 NEW_NAME新名字
Rename a container

# 案例
# ID標識改
[root@hqs ~]# docker rename d16fabb6b96e  newbee02
[root@hqs ~]# docker ps -a
CONTAINER ID        IMAGE             COMMAND             CREATED            STATUS                   PORTS       NAMES
d16fabb6b96e        ubuntu:16.04      "/bin/echo 這是一個…"    7 hours ago    Exited (0) 7 hours ago              newbee02
# 容器名標識改
[root@hqs imglayers]# docker rename quirky_liskov newbee
[root@hqs imglayers]# docker ps -a
CONTAINER ID        IMAGE               COMMAND            CREATED             STATUS                          PORTS               NAMES
6e384fa3274d        ubuntu:16.04        "/bin/bash"        4 minutes ago       Exited (0) About a minute ago                       newbee

8、顯示容器列表

可以使用 docker psdocker container ls 命令顯示容器列表。
不帶任何選項執行命令會列出所有正在運行的容器信息。

# 語法
[root@hqs ~]# 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                             # go模式格式化打印容器
  -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        Dont truncate output                                                # 不截斷輸出(ID和COMMAND)
  -q, --quiet           Only display numeric IDs                                            # 只顯示容器ID
  -s, --size            Display total file sizes                                            # 顯示總文件大小

# 不帶選項列出正在運行的容器
[root@hqs ~]# docker ps
CONTAINER ID        IMAGE               COMMAND          CREATED             STATUS              PORTS         NAMES
9de5fc313142        ubuntu:16.04        "/bin/bash"      39 minutes ago      Up 39 minutes                     charming_shirley

# -a選項列出所有的容器
[root@hqs ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS        NAMES
f2fff5915399        ubuntu:16.04        "/bin/bash"         16 seconds ago      Exited (0) 15 seconds ago                magical_chaplygin
9de5fc313142        ubuntu:16.04        "/bin/bash"         38 minutes ago      Up 38 minutes                            charming_shirley

# --no-trunc顯示完整信息
[root@hqs ~]# docker ps --no-trunc
CONTAINER ID                                                       IMAGE               COMMAND             CREATED             STATUS                   PORTS               NAMES
9de5fc3131423c539fef73f7d558128eda4a491a85e27a99fddc34182ec91082   ubuntu:16.04        "/bin/bash"         49 minutes ago      Up 49 minutes (Paused)                       charming_shirley
ad712d8eb9812209a768ebc3a9da74546473a9ca45202c829cac08b5e5a01b99   ubuntu:16.04        "/bin/bash"         49 minutes ago      Up 49 minutes (Paused)                       flamboyant_jepsen

# -l列出最新容器(含所有狀態)
[root@hqs ~]# docker ps -l
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
f2fff5915399        ubuntu:16.04        "/bin/bash"         12 minutes ago      Exited (0) 12 minutes ago                       magical_chaplygin

# -n列出最近的幾個容器(含所有狀態)
[root@hqs ~]# docker ps -n 3
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                      PORTS               NAMES
f2fff5915399        ubuntu:16.04        "/bin/bash"         12 minutes ago      Exited (0) 12 minutes ago                       magical_chaplygin
9de5fc313142        ubuntu:16.04        "/bin/bash"         51 minutes ago      Up 51 minutes (Paused)                          charming_shirley
ad712d8eb981        ubuntu:16.04        "/bin/bash"         51 minutes ago      Up 51 minutes (Paused)                          flamboyant_jepsen

# -s顯示容器所用的空間。
[root@hqs ~]# docker ps -s
CONTAINER ID        IMAGE            COMMAND          CREATED          STATUS          PORTS        NAMES           SIZE
6e384fa3274d        ubuntu:16.04     "/bin/bash"      7 hours ago      Up 4 minutes                 newbee         164B (virtual 135MB)

# -f選項可以通過多種條件過濾容器
# 根據id過濾
[root@hqs ~]# docker ps -af id=f2fff5915399   
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
f2fff5915399        ubuntu:16.04        "/bin/bash"         5 minutes ago       Exited (0) 5 minutes ago                       magical_chaplygin
# 根據name過濾
[root@hqs ~]# docker ps -af name=flamboyant_jepsen
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
ad712d8eb981        ubuntu:16.04        "/bin/bash"         44 minutes ago      Up 44 minutes                           flamboyant_jepsen
# 狀態過濾(created、restarting、running、removing、paused、exited、dead)
[root@hqs ~]# docker ps -f status=exited                   
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                     PORTS               NAMES
f2fff5915399        ubuntu:16.04        "/bin/bash"         6 minutes ago       Exited (0) 6 minutes ago                       magical_chaplygin
[root@hqs ~]# docker ps -f status=created
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@hqs ~]# docker ps -f status=running
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
9de5fc313142        ubuntu:16.04        "/bin/bash"         45 minutes ago      Up 45 minutes                           charming_shirley
ad712d8eb981        ubuntu:16.04        "/bin/bash"         45 minutes ago      Up 45 minutes                           flamboyant_jepsen
# 根據標簽過濾
[root@localhost ~]# docker run -tid --label filter-test ubuntu
[root@localhost ~]# docker run -tid --label filter-test02 ubuntu
[root@localhost ~]# docker ps --filter label=filter-test
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
0378e4835df7   ubuntu    "/bin/bash"   34 seconds ago   Up 33 seconds             boring_bohr
[root@localhost ~]# docker ps --filter label=filter-test02
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
2ac5af25e9ab   ubuntu    "/bin/bash"   29 seconds ago   Up 29 seconds             compassionate_elgamal

# 其他過濾(待補充)

# 利用-q選項完成批量操作
[root@hqs ~]# docker pause $(docker ps -f status=running -q)
9de5fc313142
ad712d8eb981
[root@hqs ~]# docker ps 
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                   PORTS         NAMES
9de5fc313142        ubuntu:16.04        "/bin/bash"         47 minutes ago      Up 47 minutes (Paused)                 charming_shirley
ad712d8eb981        ubuntu:16.04        "/bin/bash"         47 minutes ago      Up 47 minutes (Paused)                 flamboyant_jepsen

# --format格式化輸出
[root@localhost ~]# docker ps -a --format='{{.ID}}-{{.Image}}-{{.Command}}-{{.Names}}'
db2fffd7594e-ubuntu-"/bin/bash"-dazzling_nash
991be3bfc9a9-ubuntu-"/bin/bash"-wonderful_roentgen
1c84311dd8d1-ubuntu-"/bin/bash"-happy_bohr

9、inspect查看容器詳細信息

使用 docker container inspect 命令查看容器的詳細信息(元數據)。
默認情況下,以JSON數組格式輸出所有結果。

[root@hqs ~]# docker container inspect --help
Usage:  docker container inspect [OPTIONS選項] CONTAINER容器 [CONTAINER...]
Display detailed information on one or more containers
Options:
  -f, --format string   Format the output using the given Go template     # 格式化輸出
  -s, --size            Display total file sizes                          # 顯示所有文件大小

# -s顯示文件大小
[root@hqs ~]# docker container inspect -s  7021d506cf27 > test1
[root@hqs ~]# docker container inspect  7021d506cf27 > test2
[root@hqs ~]# diff test1 test2
135,136d134
<         "SizeRw": 0,
<         "SizeRootFs": 134821261,
# 以上兩行為 -s 參數多出來的數據

# -f(--format)篩選輸出內容
# 案例:獲取容器的名稱
[root@hqs ~]# docker container inspect -f='{{.Name}}' 7021d506cf27  
/elegant_perlman
[root@hqs ~]# docker container inspect --format='{{.Name}}' 7021d506cf27 
/elegant_perlman

# 案例:通過JSON格式的State子節獲取容器的狀態元數據
# 注意:json要小寫、json和.之間要空格
[root@hqs ~]# docker container inspect --format='{{.State}}' 7021d506cf27      
{running true false false false false 1510 0  2022-03-22T14:17:09.74156524Z 2022-03-22T22:16:31.416509298+08:00 <nil>}
[root@hqs ~]# docker container inspect --format='{{json .State}}' 7021d506cf27 
{"Status":"running","Running":true,"Paused":false,"Restarting":false,"OOMKilled":false,"Dead":false,"Pid":1510,"ExitCode":0,"Error":"","StartedAt":"2022-03-22T14:17:09.74156524Z","FinishedAt":"2022-03-22T22:16:31.416509298+08:00"}

# -f多層次篩選信息
[root@hqs ~]# docker container inspect --format='{{.NetworkSettings}}' 7021d506cf27                  # 第一層
{{ 111b5c2bdbc9c32fb9092b7aef3d954561256c890ad1d295457201a1482ead96 false  0 map[] /var/run/docker/netns/111b5c2bdbc9 [] []} {1f36ba204543684fb326104de0d63e3800b19ec116516304c84cc366897cbf18 172.17.0.1  0 172.17.0.3 16  02:42:ac:11:00:03} map[bridge:0xc000374000]}
[root@hqs ~]# docker container inspect --format='{{.NetworkSettings.Networks}}' 7021d506cf27         # 第二層
map[bridge:0xc0004b6000]
[root@hqs ~]# docker container inspect --format='{{.NetworkSettings.Networks.bridge}}' 7021d506cf27           # 第三層
{<nil> [] [] aafc7efe7bfd2294e8ad66662f94670dfcd8d4a29df825eab1b975ca5afceb21 1f36ba204543684fb326104de0d63e3800b19ec116516304c84cc366897cbf18 172.17.0.1 172.17.0.3 16   0 02:42:ac:11:00:03 map[]}
[root@hqs ~]# docker container inspect --format='{{.NetworkSettings.Networks.bridge.Gateway}}' 7021d506cf27   # 第四層
172.17.0.1

10、進入容器(重點)

用戶可以通過執行相應的 docker 命令進入正在運行的容器進行交互操作。

(1)attach命令

可以使用 docker attach 連接正在運行的容器。
實質是將 Docker 主機本地的標准輸入、標准輸出和錯誤流連接到了一個正在運行的容器上。

  • 標准輸入文件(STDIN):通常對應終端的鍵盤。
  • 標准輸出文件(STDOUT)、標准錯誤輸出文件(STDERROR):通常對應終端的屏幕。
# 語法
[root@hqs ~]# docker attach --help
Usage:  docker attach [OPTIONS選項] CONTAINER容器
Attach local standard input, output, and error streams to a running container
Options:
      --detach-keys string   Override the key sequence for detaching a container            # 覆蓋分離容器的鍵順序
      --no-stdin             Do not attach STDIN                   # 不連接標准輸入(問題:ctrl+C依然將容器停掉?)                              
      --sig-proxy            Proxy all received signals to the process (default true)       # 將所有接收的信號代理給進程

# 示例1:連接到一個運行中的容器並從中退出(top 和 top -b 的區別?用top不行)
[root@hqs ~]# docker run -d --name topdemo ubuntu /usr/bin/top -b
Unable to find image 'ubuntu:latest' locally
latest: Pulling from library/ubuntu
7b1a6ab2e44d: Pull complete 
Digest: sha256:626ffe58f6e7566e00254b638eb7e0f3b11d4da9675088f4781a50ae288f3322
Status: Downloaded newer image for ubuntu:latest
23e12fa1111971ff1d50d0eec9f4b8614c3ac045010d9fd6b4f3929c300d06af
[root@hqs ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND              CREATED             STATUS              PORTS                NAMES
23e12fa11119        ubuntu              "/usr/bin/top -b"    7 seconds ago       Up 6 seconds                             topdemo
[root@hqs ~]# docker attach topdemo
top - 15:09:32 up 53 min,  0 users,  load average: 0.04, 0.03, 0.05
Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.2 us,  0.3 sy,  0.0 ni, 99.5 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :   1982.6 total,    909.5 free,    356.1 used,    717.0 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.   1468.3 avail Mem 
# 此案例中會一直刷新輸出top信息,如果按ctrl+c退出容器,容器也會停止。
[root@hqs ~]# docker ps -a
CONTAINER ID        IMAGE        COMMAND              CREATED              STATUS                      PORTS         NAMES
23e12fa11119        ubuntu       "/usr/bin/top -b"    About a minute ago   Exited (0) 51 seconds ago                 topdemo

# 示例2:--sig-proxy選項如果設置為false,則可以不將信息代理給進程,ctrl+C或ctrl+D不能停止容器
[root@hqs ~]# docker attach --sig-proxy=false topdemo
top - 15:14:55 up 58 min,  0 users,  load average: 0.00, 0.01, 0.05
Tasks:   1 total,   1 running,   0 sleeping,   0 stopped,   0 zombie
%Cpu(s):  0.2 us,  0.3 sy,  0.0 ni, 99.5 id,  0.0 wa,  0.0 hi,  0.0 si,  0.0 st
MiB Mem :   1982.6 total,    909.3 free,    356.0 used,    717.3 buff/cache
MiB Swap:   2048.0 total,   2048.0 free,      0.0 used.   1468.4 avail Mem 
   PID USER      PR  NI    VIRT    RES    SHR S  %CPU  %MEM     TIME+ COMMAND
     1 root      20   0    5960   1700   1276 R   0.0   0.1   0:00.01 top
# 按ctrl+c退出容器,容器沒有停止
[root@hqs ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND              CREATED             STATUS              PORTS                NAMES
23e12fa11119        ubuntu              "/usr/bin/top -b"    6 minutes ago       Up 29 seconds                            topdemo

# 示例3:
[root@localhost ~]# docker run -dti --name alpine1 alpine ash
667caa0d0690c95de34e41bfebaf983e897f3a7e028fda892fca884f1f94dc49
[root@localhost ~]# docker attach alpine1            《————連接到alpine容器
/ # ip addr show                                      《———— ‘#’說明當前容器用戶以root登錄
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 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
19: eth0@if20: <BROADCAST,MULTICAST,UP,LOWER_UP,M-DOWN> mtu 1500 qdisc noqueue state UP 
    link/ether 02:42:ac:11:00:02 brd ff:ff:ff:ff:ff:ff
    inet 172.17.0.2/16 brd 172.17.255.255 scope global eth0              《————地址為172.17.0.2
       valid_lft forever preferred_lft forever
/ # ping -c 2 www.163.com
PING www.163.com (221.233.240.107): 56 data bytes
64 bytes from 221.233.240.107: seq=0 ttl=127 time=4.929 ms
64 bytes from 221.233.240.107: seq=1 ttl=127 time=5.103 ms
--- www.163.com ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max = 4.929/5.016/5.103 ms
# 測試后,再通過ctrl+P+Q退出容器alpine1。

使用 attach 命令的問題:當多個窗口同時 attach 到同一個容器的時候,所有窗口都會同步顯示。當某個窗口因命令阻塞時,其他窗口也無法執行操作了。

(2)exec命令

使用 docker exec 命令在運行中的容器執行命令。

[root@hqs ~]# 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                               # 設置環境變量
  -i, --interactive          Keep STDIN open even if not attached                    # 保持標准輸入開啟
      --privileged           Give extended privileges to the command                 # 給予擴展權限
  -t, --tty                  Allocate a pseudo-TTY                                   # 分配一個偽輸入終端
  -u, --user string          Username or UID (format: <name|uid>[:<group|gid>])      # 用戶名或ID
  -w, --workdir string       Working directory inside the container                  # 容器內工作目錄

# 案例:進入容器,交互執行命令
[root@hqs ~]# docker exec -ti topdemo /bin/bash
root@23e12fa11119:/# ps
   PID TTY          TIME CMD
     6 pts/0    00:00:00 bash
    13 pts/0    00:00:00 ps
root@23e12fa11119:/# exit
exit
[root@hqs ~]# 

# 案例:不進入容器執行命令
[root@hqs ~]# docker exec -i topdemo echo '1111'
1111
[root@hqs ~]# docker exec -i topdemo /bin/ls
bin
boot
dev
etc
home
lib

11、查看容器狀態

docker stats 命令是用來實時監視運行中的容器的資源使用情況。

可以指定一個或多個容器的名稱或ID。

# 語法
[root@localhost ~]# docker container stats -h
Usage:  docker container stats [OPTIONS] [CONTAINER...]
Display a live stream of container(s) resource usage statistics

Options:
  -a, --all             Show all containers (default shows just running)      # 顯示所有容器
      --format string   Pretty-print images using a Go template               # 格式化輸出
      --no-stream       Disable streaming stats and only pull the first result   # 禁用流狀態,僅拉取第一次的結果
      --no-trunc        Do not truncate output         # 不階段輸出

# 案例:顯示指定容器狀態
[root@localhost ~]# docker stats 8601952b7194
容器ID         容器名     CPU使用率   內存使用率                  網絡IO       磁盤IO      
CONTAINER ID   NAME       CPU %     MEM USAGE / LIMIT   MEM %     NET I/O     BLOCK I/O   PIDS
8601952b7194   topdemo1   0.00%     500KiB / 1.779GiB   0.03%     648B / 0B   0B / 0B     1

# 案例:顯示運行中容器狀態
[root@localhost ~]# docker stats
CONTAINER ID   NAME                 CPU %     MEM USAGE / LIMIT   MEM %     NET I/O       BLOCK I/O   PIDS
8601952b7194   topdemo1             0.00%     500KiB / 1.779GiB   0.03%     648B / 0B     0B / 0B     1
17844117f3be   topdemo              0.00%     492KiB / 1.779GiB   0.03%     648B / 0B     0B / 0B     1
991be3bfc9a9   wonderful_roentgen   0.00%     556KiB / 1.779GiB   0.03%     648B / 0B     0B / 0B     1

# 案例:顯示所有容器狀態
[root@localhost ~]# docker stats -a
CONTAINER ID   NAME                 CPU %     MEM USAGE / LIMIT   MEM %     NET I/O       BLOCK I/O   PIDS
8601952b7194   topdemo1             0.00%     500KiB / 1.779GiB   0.03%     648B / 0B     0B / 0B     1
17844117f3be   topdemo              0.00%     492KiB / 1.779GiB   0.03%     648B / 0B     0B / 0B     1
ecc0bc02ce73   wonderful_gould      0.00%     0B / 0B             0.00%     0B / 0B       0B / 0B     0
db2fffd7594e   dazzling_nash        0.00%     0B / 0B             0.00%     0B / 0B       0B / 0B     0
991be3bfc9a9   wonderful_roentgen   0.00%     556KiB / 1.779GiB   0.03%     648B / 0B     0B / 0B     1
1c84311dd8d1   happy_bohr           0.00%     556KiB / 1.779GiB   0.03%     1.09kB / 0B   0B / 0B     1

# 案例:資源信息只顯示一次,不再動態刷新
[root@localhost ~]# docker stats --no-stream
CONTAINER ID   NAME                 CPU %     MEM USAGE / LIMIT   MEM %     NET I/O       BLOCK I/O   PIDS
8601952b7194   topdemo1             0.00%     500KiB / 1.779GiB   0.03%     648B / 0B     0B / 0B     1
17844117f3be   topdemo              0.00%     492KiB / 1.779GiB   0.03%     648B / 0B     0B / 0B     1
991be3bfc9a9   wonderful_roentgen   0.00%     556KiB / 1.779GiB   0.03%     648B / 0B     0B / 0B     1
1c84311dd8d1   happy_bohr           0.00%     556KiB / 1.779GiB   0.03%     1.09kB / 0B   0B / 0B     1

# 案例:--no-trunc 完整顯示ID
[root@localhost ~]# docker stats --no-trunc 17844117f3be
CONTAINER ID                                                       NAME      CPU %     MEM USAGE / LIMIT   MEM %     NET I/O     BLOCK I/O   PIDS
17844117f3be8c9d4d79fee4f15e8d43085ea0d2d15fd25412deff01c322bbf4   topdemo   0.00%     492KiB / 1.779GiB   0.03%     648B / 0B   0B / 0B     1

# 案例:--format格式化輸出
[root@localhost ~]# docker stats --format='{{.ID}}-{{.Name}}' --no-stream  17844117
17844117f3be-topdemo
[root@localhost ~]# docker stats --format='{{.ID}}-{{.Name}}-{{.CPUPerc}}-{{.MemUsage}}-{{.NetIO}}-{{.BlockIO}}-{{.MemPerc}}-{{.PIDs}}' --no-stream  17844117
17844117f3be-topdemo-0.03%-492KiB / 1.779GiB-648B / 0B-0B / 0B-0.03%-1


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM