• 欢迎访问金笔头博客,这是一个菜鸟(伪)程序员的自留地,欢迎访问我的github:点击进入

Docker笔记(4)-关于容器的一些基本操作

Docker eason 977次浏览 0个评论 扫描二维码

1.查看当前系统中容器列表

  • docker ps 列出正在运行的容器
  • docker ps -a 列出所有容器,包括已经停止的.
    $ sudo docker ps
    CONTAINER ID        IMAGE              COMMAND            CREATED            STATUS              PORTS              NAMES
    $ sudo docker ps -a
    CONTAINER ID        IMAGE              COMMAND                  CREATED            STATUS                    PORTS              NAMES
    a54bb4bd4885        mysql              "docker-entrypoint..."  4 minutes ago      Exited (0) 3 minutes ago                      blissful_lalande
    a96af7cad4c7        hello-world        "/hello"                About an hour ago  Created                                        thirsty_fermat
    c1926fd00edf        hello-world        "/hello"                About an hour ago  Created                                        hardcore_cray
    

    列出来的信息包括:

  • CONTAINER ID: 容器id, 例如a54bb4bd4885
  • IMAGE: 容器的镜像
  • COMMAND: 容器运行的命令
  • CREATED: 容器创建时间
  • STATUS: 运行状态
  • PORTS: 端口
  • NAMES: 容器名

2.创建容器但不运行

使用docker create命令可以创建容器,但是创建好的容器不会马上运行。

$ sudo docker create mysql
a6b43220a35ea17839405b73b0a46044add6ee6d106aa92eb24bd2c97fc87c0a
$ sudo docker ps -a
CONTAINER ID        IMAGE              COMMAND                  CREATED            STATUS                    PORTS              NAMES
a6b43220a35e        mysql              "docker-entrypoint..."  4 seconds ago      Created                                        musing_lumiere
a54bb4bd4885        mysql              "docker-entrypoint..."  6 minutes ago      Exited (0) 5 minutes ago                      blissful_lalande
a96af7cad4c7        hello-world        "/hello"                About an hour ago  Created                                        thirsty_fermat
c1926fd00edf        hello-world        "/hello"                About an hour ago  Created                                        hardcore_cray

如上所示,创建成功后会返回所创建容器的UUIDa6b43220a35ea17839405b73b0a46044add6ee6d106aa92eb24bd2c97fc87c0a,该UUID是一个长UUID,可以使用该ID做为容器标识,进行后续操作。

3.创建容器的时候命名

可以使用--name参数为创建的容器命名 使用格式为:sudo docker create --name 容器名称 镜像名称

$ sudo docker create --name mysql_test01 mysql
a3760719cd933a3f288490c9718dde70f499e68b2200ca5e569be47aa59cf922
$ sudo docker ps -a
CONTAINER ID        IMAGE              COMMAND                  CREATED              STATUS                    PORTS              NAMES
a3760719cd93        mysql              "docker-entrypoint..."  3 seconds ago        Created                                        mysql_test01
a6b43220a35e        mysql              "docker-entrypoint..."  About a minute ago  Created                                        musing_lumiere
a54bb4bd4885        mysql              "docker-entrypoint..."  8 minutes ago        Exited (0) 6 minutes ago                      blissful_lalande
a96af7cad4c7        hello-world        "/hello"                About an hour ago    Created                                        thirsty_fermat
c1926fd00edf        hello-world        "/hello"                About an hour ago    Created                                        hardcore_cray

4.创建容器并运行

使用docker run命令可以创建并运行容器,可以使用docker run --help查看具体用法

$ sudo 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) (default [])
  -a, --attach list                Attach to STDIN, STDOUT or STDERR (default [])
      --blkio-weight uint16        Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)
      --blkio-weight-device list  Block IO weight (relative device weight) (default [])
      --cap-add list              Add Linux capabilities (default [])
      --cap-drop list              Drop Linux capabilities (default [])
      --cgroup-parent string      Optional parent cgroup for the container
      --cidfile string            Write the container ID to the file
      --cpu-period int            Limit CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int              Limit CPU CFS (Completely Fair Scheduler) quota
      --cpu-rt-period int          Limit CPU real-time period in microseconds
      --cpu-rt-runtime int        Limit CPU real-time runtime in microseconds
  -c, --cpu-shares int            CPU shares (relative weight)
      --cpus decimal              Number of CPUs (default 0.000)
      --cpuset-cpus string        CPUs in which to allow execution (0-3, 0,1)
      --cpuset-mems string        MEMs in which to allow execution (0-3, 0,1)
  -d, --detach                    Run container in background and print container ID
      --detach-keys string        Override the key sequence for detaching a container
      --device list                Add a host device to the container (default [])
      --device-cgroup-rule list    Add a rule to the cgroup allowed devices list (default [])
      --device-read-bps list      Limit read rate (bytes per second) from a device (default [])
      --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 [])
      --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 (default [])
      --dns-option list            Set DNS options (default [])
      --dns-search list            Set custom DNS search domains (default [])
      --entrypoint string          Overwrite the default ENTRYPOINT of the image
  -e, --env list                  Set environment variables (default [])
      --env-file list              Read in a file of environment variables (default [])
      --expose list                Expose a port or a range of ports (default [])
      --group-add list            Add additional groups to join (default [])
      --health-cmd string          Command to run to check health
      --health-interval duration  Time between running the check (ns|us|ms|s|m|h) (default 0s)
      --health-retries int        Consecutive failures needed to report unhealthy
      --health-timeout duration    Maximum time to allow one check to run (ns|us|ms|s|m|h) (default 0s)
      --help                      Print usage
  -h, --hostname string            Container host name
      --init                      Run an init inside the container that forwards signals and reaps processes
      --init-path string          Path to the docker-init binary
  -i, --interactive                Keep STDIN open even if not attached
      --ip string                  IPv4 address (e.g., 172.30.100.104)
      --ip6 string                IPv6 address (e.g., 2001:db8::33)
      --ipc string                IPC namespace to use
      --isolation string          Container isolation technology
      --kernel-memory bytes        Kernel memory limit
  -l, --label list                Set meta data on a container (default [])
      --label-file list            Read in a line delimited file of labels (default [])
      --link list                  Add link to another container (default [])
      --link-local-ip list        Container IPv4/IPv6 link-local addresses (default [])
      --log-driver string          Logging driver for the container
      --log-opt list              Log driver options (default [])
      --mac-address string        Container MAC address (e.g., 92:d0:c6:0a:29:33)
  -m, --memory bytes              Memory limit
      --memory-reservation bytes  Memory soft limit
      --memory-swap bytes          Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --memory-swappiness int      Tune container memory swappiness (0 to 100) (default -1)
      --name string                Assign a name to the container
      --network string            Connect a container to a network (default "default")
      --network-alias list        Add network-scoped alias for the container (default [])
      --no-healthcheck            Disable any container-specified HEALTHCHECK
      --oom-kill-disable          Disable OOM Killer
      --oom-score-adj int          Tune host's OOM preferences (-1000 to 1000)
      --pid string                PID namespace to use
      --pids-limit int            Tune container pids limit (set -1 for unlimited)
      --privileged                Give extended privileges to this container
  -p, --publish list              Publish a container's port(s) to the host (default [])
  -P, --publish-all                Publish all exposed ports to random ports
      --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 (default [])
      --shm-size bytes            Size of /dev/shm
      --sig-proxy                  Proxy received signals to the process (default true)
      --stop-signal string        Signal to stop a container (default "SIGTERM")
      --stop-timeout int          Timeout (in seconds) to stop a container
      --storage-opt list          Storage driver options for the container (default [])
      --sysctl map                Sysctl options (default map[])
      --tmpfs list                Mount a tmpfs directory (default [])
  -t, --tty                        Allocate a pseudo-TTY
      --ulimit ulimit              Ulimit options (default [])
  -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 (default [])
      --volume-driver string      Optional volume driver for the container
      --volumes-from list          Mount volumes from the specified container(s) (default [])
  -w, --workdir string            Working directory inside the container

这里基于mysql镜像新建容器mysql_test02并运行命令/bin/bash

$ sudo docker run --name mysql_test02 -t -i mysql /bin/bash
root@193d3d417fa5:/# exit
exit
$ sudo docker ps -a
CONTAINER ID        IMAGE              COMMAND                  CREATED            STATUS                      PORTS              NAMES
193d3d417fa5        mysql              "docker-entrypoint..."  19 seconds ago      Exited (0) 3 seconds ago                        mysql_test02
a3760719cd93        mysql              "docker-entrypoint..."  5 minutes ago      Created                                        mysql_test01
a6b43220a35e        mysql              "docker-entrypoint..."  6 minutes ago      Created                                        musing_lumiere
a54bb4bd4885        mysql              "docker-entrypoint..."  13 minutes ago      Exited (0) 11 minutes ago                      blissful_lalande
a96af7cad4c7        hello-world        "/hello"                About an hour ago  Created                                        thirsty_fermat
c1926fd00edf        hello-world        "/hello"                About an hour ago  Created                                        hardcore_cray

上面命令中使用了-i-t两个参数。其中,-i是保证容器STDIN是开启状态;-t是告诉Docker为创建的容器分配一个伪TTY终端。这样我们就创建了一个能在命令行下与之交互的容器。 docker run命令的执行过程下:

  1. 首先检查本地是否ubuntu镜像
  2. 如果没有,连接Docker Hub Registry查看是否有名为mysql:latest镜像的镜像
  3. 找到镜像,将镜像下载到本地
  4. Docker在文件系统内部使用这个镜像创建一个新容器,这个容器会有自已的网络、IP地址以及一个与本地宿主机通讯的桥接网络接口
  5. 容器创建完成后,执行所要执行的命令,这里是/bin/bash

5.启动已创建的容器

容器停止/退出后,可以通过docker startdocker restart重新启动容器。

$ sudo 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
      --help                Print usage
  -i, --interactive          Attach container's STDIN


$ sudo docker restart --help

Usage:    docker restart [OPTIONS] CONTAINER [CONTAINER...]

Restart one or more containers

Options:
      --help      Print usage
  -t, --time int  Seconds to wait for stop before killing the container (default 10)

如,启动容器mysql_test02

$ sudo docker start mysql_test02
mysql_test02
$ sudo docker ps
CONTAINER ID        IMAGE              COMMAND                  CREATED            STATUS              PORTS              NAMES
193d3d417fa5        mysql              "docker-entrypoint..."  17 minutes ago      Up 9 seconds        3306/tcp            mysql_test02

6.附着到容器

可以使用docker attach命令附着到指定容器

$ sudo docker attach --help

Usage:    docker attach [OPTIONS] CONTAINER

Attach to a running container

Options:
      --detach-keys string  Override the key sequence for detaching a container
      --help                Print usage
      --no-stdin            Do not attach STDIN
      --sig-proxy            Proxy all received signals to the process (default true)

只有处于运行状态的容器才会被附着成功

$ sudo docker attach mysql_test02
You cannot attach to a stopped container, start it first
$ sudo docker start mysql_test02
mysql_test02
$ sudo docker attach mysql_test02
root@193d3d417fa5:/# ls -l
total 68
drwxr-xr-x  2 root root 4096 Sep 13 08:26 bin
drwxr-xr-x  2 root root 4096 Jul 13 13:01 boot
drwxr-xr-x  5 root root  360 Sep 19 09:12 dev
drwxr-xr-x  2 root root 4096 Sep 13 08:25 docker-entrypoint-initdb.d
lrwxrwxrwx  1 root root  34 Sep 13 08:27 entrypoint.sh -> usr/local/bin/docker-entrypoint.sh
drwxr-xr-x  59 root root 4096 Sep 19 08:06 etc
drwxr-xr-x  2 root root 4096 Jul 13 13:01 home
drwxr-xr-x  11 root root 4096 Nov 27  2014 lib
drwxr-xr-x  2 root root 4096 Sep  7 00:00 lib64
drwxr-xr-x  2 root root 4096 Sep  7 00:00 media
drwxr-xr-x  2 root root 4096 Sep  7 00:00 mnt
drwxr-xr-x  2 root root 4096 Sep  7 00:00 opt
dr-xr-xr-x 298 root root    0 Sep 19 09:12 proc
drwx------  2 root root 4096 Sep 19 08:06 root
drwxr-xr-x  4 root root 4096 Sep 13 08:27 run
drwxr-xr-x  2 root root 4096 Sep  7 00:00 sbin
drwxr-xr-x  2 root root 4096 Sep  7 00:00 srv
dr-xr-xr-x  13 root root    0 Sep 19 08:55 sys
drwxrwxrwt  2 root root 4096 Sep 13 08:27 tmp
drwxr-xr-x  23 root root 4096 Sep  7 00:00 usr
drwxr-xr-x  21 root root 4096 Sep  7 00:00 var

注意:在附着成功的容器内执行 exit 命令退出,会导致容器的停止。

7.查看容器日志

可以使用docker logs命令查看指定容器的日志,执行docker logs --help命令查看用法

$ sudo 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
      --help          Print usage
      --since string  Show logs since timestamp (e.g. 2013-01-02T13:23:37) or relative (e.g. 42m for 42 minutes)
      --tail string    Number of lines to show from the end of the logs (default "all")
  -t, --timestamps    Show timestamps

-f参数类似于tail -f可以看到实时日志输出。--tail参数指定最后显示的日志行数。如,查看最后10行日志

$ sudo docker logs --tail 10 mysql_test02
drwxr-xr-x  2 root root 4096 Sep  7 00:00 opt
dr-xr-xr-x 298 root root    0 Sep 19 09:12 proc
drwx------  2 root root 4096 Sep 19 08:06 root
drwxr-xr-x  4 root root 4096 Sep 13 08:27 run
drwxr-xr-x  2 root root 4096 Sep  7 00:00 sbin
drwxr-xr-x  2 root root 4096 Sep  7 00:00 srv
dr-xr-xr-x  13 root root    0 Sep 19 08:55 sys
drwxrwxrwt  2 root root 4096 Sep 13 08:27 tmp
drwxr-xr-x  23 root root 4096 Sep  7 00:00 usr
drwxr-xr-x  21 root root 4096 Sep  7 00:00 var

查看mysql_test02容器的全部日志如下:

$ sudo docker logs mysql_test02
root@193d3d417fa5:/# exit
exit
root@193d3d417fa5:/# 
root@193d3d417fa5:/# ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root          1      0  0 08:23 ?        00:00:00 /bin/bash
root          6      1  0 08:50 ?        00:00:00 ps -ef
root@193d3d417fa5:/# netstat
bash: netstat: command not found
root@193d3d417fa5:/# netstat -an
bash: netstat: command not found
root@193d3d417fa5:/# mysql
ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)
root@193d3d417fa5:/# exit
exit
root@193d3d417fa5:/# 
root@193d3d417fa5:/# ll  
bash: ll: command not found
root@193d3d417fa5:/# ls
bin  boot  dev    docker-entrypoint-initdb.d  entrypoint.sh  etc    home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@193d3d417fa5:/# ls -l
total 68
drwxr-xr-x  2 root root 4096 Sep 13 08:26 bin
drwxr-xr-x  2 root root 4096 Jul 13 13:01 boot
drwxr-xr-x  5 root root  360 Sep 19 08:54 dev
drwxr-xr-x  2 root root 4096 Sep 13 08:25 docker-entrypoint-initdb.d
lrwxrwxrwx  1 root root  34 Sep 13 08:27 entrypoint.sh -> usr/local/bin/docker-entrypoint.sh
drwxr-xr-x  59 root root 4096 Sep 19 08:06 etc
drwxr-xr-x  2 root root 4096 Jul 13 13:01 home
drwxr-xr-x  11 root root 4096 Nov 27  2014 lib
drwxr-xr-x  2 root root 4096 Sep  7 00:00 lib64
drwxr-xr-x  2 root root 4096 Sep  7 00:00 media
drwxr-xr-x  2 root root 4096 Sep  7 00:00 mnt
drwxr-xr-x  2 root root 4096 Sep  7 00:00 opt
dr-xr-xr-x 297 root root    0 Sep 19 08:54 proc
drwx------  2 root root 4096 Sep 19 08:06 root
drwxr-xr-x  4 root root 4096 Sep 13 08:27 run
drwxr-xr-x  2 root root 4096 Sep  7 00:00 sbin
drwxr-xr-x  2 root root 4096 Sep  7 00:00 srv
dr-xr-xr-x  13 root root    0 Sep 19 08:54 sys
drwxrwxrwt  2 root root 4096 Sep 13 08:27 tmp
drwxr-xr-x  23 root root 4096 Sep  7 00:00 usr
drwxr-xr-x  21 root root 4096 Sep  7 00:00 var
root@193d3d417fa5:/# exit
exit
root@193d3d417fa5:/# exit
root@193d3d417fa5:/# exit
root@193d3d417fa5:/# exit
root@193d3d417fa5:/# 
root@193d3d417fa5:/# pwd
/
root@193d3d417fa5:/# ls -l
total 68
drwxr-xr-x  2 root root 4096 Sep 13 08:26 bin
drwxr-xr-x  2 root root 4096 Jul 13 13:01 boot
drwxr-xr-x  5 root root  360 Sep 19 09:12 dev
drwxr-xr-x  2 root root 4096 Sep 13 08:25 docker-entrypoint-initdb.d
lrwxrwxrwx  1 root root  34 Sep 13 08:27 entrypoint.sh -> usr/local/bin/docker-entrypoint.sh
drwxr-xr-x  59 root root 4096 Sep 19 08:06 etc
drwxr-xr-x  2 root root 4096 Jul 13 13:01 home
drwxr-xr-x  11 root root 4096 Nov 27  2014 lib
drwxr-xr-x  2 root root 4096 Sep  7 00:00 lib64
drwxr-xr-x  2 root root 4096 Sep  7 00:00 media
drwxr-xr-x  2 root root 4096 Sep  7 00:00 mnt
drwxr-xr-x  2 root root 4096 Sep  7 00:00 opt
dr-xr-xr-x 298 root root    0 Sep 19 09:12 proc
drwx------  2 root root 4096 Sep 19 08:06 root
drwxr-xr-x  4 root root 4096 Sep 13 08:27 run
drwxr-xr-x  2 root root 4096 Sep  7 00:00 sbin
drwxr-xr-x  2 root root 4096 Sep  7 00:00 srv
dr-xr-xr-x  13 root root    0 Sep 19 08:55 sys
drwxrwxrwt  2 root root 4096 Sep 13 08:27 tmp
drwxr-xr-x  23 root root 4096 Sep  7 00:00 usr
drwxr-xr-x  21 root root 4096 Sep  7 00:00 var

可以看到已经打印出来我之前在mysql_test02容器内执行的所有命令。

8.容器内进程查看

可以使用docker top命令查看容器内运行的进程

$ sudo docker top mysql_test02
UID                PID                PPID                C                  STIME              TTY                TIME                CMD
root                20666              20647              0                  17:12              pts/20              00:00:00            /bin/bash

9.容器内运行进程

可以使用docker exec命令在容器内运行进程

$ sudo 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 (default [])
      --help                Print usage
  -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>])

执行命令docker exec -i mysql_test02 /bin/bash查看输出结果

$ sudo docker exec -i mysql_test02 /bin/bash
Error response from daemon: Container 193d3d417fa5e71e6ff5f4c4b67f2d313132f5989895cb6bd720c6258784c47f is not running

由提示可知:在执行docker exec之前,该容器必须处于运行状态。 下面先启动mysql_test02容器,再执行docker exec命令

$ sudo docker exec -i mysql_test02 /bin/bash
date
Tue Sep 19 09:46:19 UTC 2017
pwd
/
whoami
root
ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root          1      0  0 09:46 ?        00:00:00 /bin/bash
root          6      0  0 09:46 ?        00:00:00 /bin/bash
root        13      6  0 09:46 ?        00:00:00 ps -ef

可以看出只用-i时,由于没有分配伪终端,结果看起来很混乱。但是执行结果、命令返回值都可以正确获取。 下面我们加上-t参数再试试

$ sudo docker exec -it mysql_test02 /bin/bash
root@193d3d417fa5:/# date
Tue Sep 19 09:51:04 UTC 2017
root@193d3d417fa5:/# pwd
/
root@193d3d417fa5:/# whoami
root
root@193d3d417fa5:/# exit
exit
eason@eason-virtual-machine:~$ sudo docker ps
CONTAINER ID        IMAGE              COMMAND                  CREATED            STATUS              PORTS              NAMES
193d3d417fa5        mysql              "docker-entrypoint..."  2 hours ago        Up 6 minutes        3306/tcp            mysql_test02

由输出可知,使用-it时,则和我们平常操作terminal界面类似。而且也不会像attach方式因为退出,导致整个容器退出。

10.查看容器状态

在查看容器内进程时,我们使用了docker top命令。除此之外,还可以使用docker stats来查看容器的详细使用统计信息,该命令可以同时查看一个或多个容器的统计信息。 查看docker stats的用法:

$ sudo docker stats --help

Usage:    docker 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
      --help            Print usage
      --no-stream      Disable streaming stats and only pull the first result

查看容器mysql_test02的状态:

$ sudo docker stats mysql_test02

CONTAINER          CPU %              MEM USAGE / LIMIT    MEM %              NET I/O            BLOCK I/O          PIDS
mysql_test02        0.00%              2.938MiB / 3.84GiB  0.07%              4.2kB / 0B          1.29MB / 0B        1

docker statsdocker top统计内容有所不同,统计内容包括:CPU、内存、网络I/O、存储I/O使用情况等。统计形式也有所不同,docker stats是实时统计。 docker stats可以同时统计多个容器的使用情况,指定多个需要统计的容器ID或名称即可,也可以通过-a参数对所有容器进行统计:

$ sudo docker stats mysql_test02 mysql_test01

CONTAINER          CPU %              MEM USAGE / LIMIT    MEM %              NET I/O            BLOCK I/O          PIDS
mysql_test02        0.00%              2.938MiB / 3.84GiB  0.07%              4.2kB / 0B          1.29MB / 0B        1
mysql_test01        0.00%              0B / 0B              0.00%              0B / 0B            0B / 0B            0

$ sudo docker stats -a

CONTAINER          CPU %              MEM USAGE / LIMIT    MEM %              NET I/O            BLOCK I/O          PIDS
193d3d417fa5        0.00%              2.938MiB / 3.84GiB  0.07%              4.2kB / 0B          1.29MB / 0B        1
a3760719cd93        0.00%              0B / 0B              0.00%              0B / 0B            0B / 0B            0
a6b43220a35e        0.00%              0B / 0B              0.00%              0B / 0B            0B / 0B            0
a54bb4bd4885        0.00%              0B / 0B              0.00%              0B / 0B            0B / 0B            0
a96af7cad4c7        0.00%              0B / 0B              0.00%              0B / 0B            0B / 0B            0
c1926fd00edf        0.00%              0B / 0B              0.00%              0B / 0B            0B / 0B            0

11.查看容器详细信息

通过docker ps命令,我们可以看到容器的一些基本信息。除此之外,docker还提供了一个docker inspect命令,该命令会返回容器的详细配置信息。包括:名称、命令、运行状态、网络配置等。 首先查看docker inspect的用法:

$ sudo 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
      --help            Print usage
  -s, --size            Display total file sizes if the type is container
      --type string    Return JSON for specified type

查看容器mysql_test02的详细信息:

$ sudo docker inspect mysql_test02
[
    {
        "Id": "193d3d417fa5e71e6ff5f4c4b67f2d313132f5989895cb6bd720c6258784c47f",
        "Created": "2017-09-19T08:06:38.394158224Z",
        "Path": "docker-entrypoint.sh",
        "Args": [
            "/bin/bash"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 21138,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2017-09-19T09:46:10.902435717Z",
            "FinishedAt": "2017-09-19T09:43:09.64724865Z"
        },
        "Image": "sha256:aeaed9976244af22dce072c4c34add85ecdc7d79bfcbe32d558eff3c420945ee",
        "ResolvConfPath": "/var/lib/docker/containers/193d3d417fa5e71e6ff5f4c4b67f2d313132f5989895cb6bd720c6258784c47f/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/193d3d417fa5e71e6ff5f4c4b67f2d313132f5989895cb6bd720c6258784c47f/hostname",
        "HostsPath": "/var/lib/docker/containers/193d3d417fa5e71e6ff5f4c4b67f2d313132f5989895cb6bd720c6258784c47f/hosts",
        "LogPath": "/var/lib/docker/containers/193d3d417fa5e71e6ff5f4c4b67f2d313132f5989895cb6bd720c6258784c47f/193d3d417fa5e71e6ff5f4c4b67f2d313132f5989895cb6bd720c6258784c47f-json.log",
        "Name": "/mysql_test02",
        "RestartCount": 0,
        "Driver": "aufs",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "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,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "",
            "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": null,
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": -1,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0
        },
        "GraphDriver": {
            "Data": null,
            "Name": "aufs"
        },
        "Mounts": [
            {
                "Type": "volume",
                "Name": "ff604484cdd08d13bde4829c434fad26632c47a839fda4547515e091b5f5ac53",
                "Source": "/var/lib/docker/volumes/ff604484cdd08d13bde4829c434fad26632c47a839fda4547515e091b5f5ac53/_data",
                "Destination": "/var/lib/mysql",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],
        "Config": {
            "Hostname": "193d3d417fa5",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "ExposedPorts": {
                "3306/tcp": {}
            },
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "GOSU_VERSION=1.7",
                "MYSQL_MAJOR=5.7",
                "MYSQL_VERSION=5.7.19-1debian8"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "Image": "mysql",
            "Volumes": {
                "/var/lib/mysql": {}
            },
            "WorkingDir": "",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "d70bd474e82addd0342b2c9ca90822c02e16ea583f1deae84bbc82ebf94177b5",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "3306/tcp": null
            },
            "SandboxKey": "/var/run/docker/netns/d70bd474e82a",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "1322f735d8322ea7d0d006ce104fd373e83378a7d8a1553ad17b20d291ebadd9",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "37b955da1b70fff7a9d414c1d32f02d6dcf85343194113ffc4c94821b89b5642",
                    "EndpointID": "1322f735d8322ea7d0d006ce104fd373e83378a7d8a1553ad17b20d291ebadd9",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02"
                }
            }
        }
    }
]

docker inspect命令有一个很有用的参数-f--format,这个参数支持完整的GO语言模板,可以对输出结果进行格式化、筛选等。 例如可以使用如下命令查看mysql_test02的ip地址:

$ sudo docker inspect -f '{{.NetworkSettings.IPAddress}}' mysql_test02
172.17.0.2

12.停止容器

停止容器可以使用docker stop或者docker kill命令来完成 查看docker stop使用方法

sudo docker stop --help

Usage:    docker stop [OPTIONS] CONTAINER [CONTAINER...]

Stop one or more running containers

Options:
      --help      Print usage
  -t, --time int  Seconds to wait for stop before killing it (default 10)

停止mysql_test02容器

$ sudo docker stop mysql_test02
mysql_test02
$ sudo docker ps
CONTAINER ID        IMAGE              COMMAND            CREATED            STATUS              PORTS              NAMES

停止容器时,docker stop命令会向容器进程发送SIGTERM信号,收到该信号进程完成处理后结束。如果想快速停止可以使用docker kill,该命令会向容器进程发送SIGKILL信号。加上-t参数表示等待x秒之后停止容器,默认是10秒。 查看docker kill使用方法

$ sudo docker kill --help

Usage:    docker kill [OPTIONS] CONTAINER [CONTAINER...]

Kill one or more running containers

Options:
      --help            Print usage
  -s, --signal string  Signal to send to the container (default "KILL")

13.删除容器

容器不再使用后,可以使用docker rm命令将其删除。 先查看用法:

$ sudo 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)
      --help      Print usage
  -l, --link      Remove the specified link
  -v, --volumes  Remove the volumes associated with the container

其中-f参数能强行删除运行中的容器;-v参数能移除容器所使用的卷,为什么要使用这个参数呢,因为如果你已经使用docker rm来删除你的容器,那可能还有很多的孤立的Volume仍在占用着空间。 下面删除本机上的所有容器

$ sudo docker ps -a
CONTAINER ID        IMAGE              COMMAND                  CREATED            STATUS                      PORTS              NAMES
193d3d417fa5        mysql              "docker-entrypoint..."  4 hours ago        Exited (0) 24 minutes ago                      mysql_test02
a3760719cd93        mysql              "docker-entrypoint..."  4 hours ago        Created                                        mysql_test01
a6b43220a35e        mysql              "docker-entrypoint..."  4 hours ago        Created                                        musing_lumiere
a54bb4bd4885        mysql              "docker-entrypoint..."  4 hours ago        Exited (0) 4 hours ago                          blissful_lalande
a96af7cad4c7        hello-world        "/hello"                5 hours ago        Created                                        thirsty_fermat
c1926fd00edf        hello-world        "/hello"                5 hours ago        Created                                        hardcore_cray
$ sudo docker rm hardcore_cray thirsty_fermat blissful_lalande musing_lumiere mysql_test01 mysql_test02
hardcore_cray
thirsty_fermat
blissful_lalande
musing_lumiere
mysql_test01
mysql_test02
$ sudo docker ps -a
CONTAINER ID        IMAGE              COMMAND            CREATED            STATUS              PORTS              NAMES

关于Volume的概念

想要了解Docker Volume,首先我们需要知道Docker的文件系统是如何工作的。Docker镜像是由多个文件系统(只读层)叠加而成。当我们启动一个容器的时候,Docker会加载只读镜像层并在其上添加一个读写层。如果运行中的容器修改了现有的一个已经存在的文件,那该文件将会从读写层下面的只读层复制到读写层,该文件的只读版本仍然存在,只是已经被读写层中该文件的副本所隐藏。当删除Docker容器,并通过该镜像重新启动时,之前的更改将会丢失。在Docker中,只读层及在顶部的读写层的组合被称为Union File System(联合文件系统)。 为了能够保存(持久化)数据以及共享容器间的数据,Docker提出了Volume的概念。简单来说,Volume就是目录或者文件,它可以绕过默认的联合文件系统,而以正常的文件或者目录的形式存在于宿主机上。


金笔头博客, 版权所有丨如未注明 , 均为原创, 转载请注明Docker笔记(4)-关于容器的一些基本操作
喜欢 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址