一、常用命令

其中 <> 阔起来的参数为必选,[] 阔起来为可选

  1. docker version:查看 docker 的版本号,包括客户端、服务端、依赖的 Go 等
  2. docker info:查看系统(docker)层面信息,包括管理的 images, containers 数等
  3. docker search <image>:在 docker index 中搜索 image
  4. docker pull <image>:从docker registry server 中下拉image
  5. docker push <image|repository>:推送一个 image 或 repository 到 registry
  6. docker push <image|repository>:TAG:同上,指定tag
  7. docker inspect <image|container>:查看 image 或 container 的底层信息
  8. docker images:查看本机 images
  9. docker images –a:列出所有的 images
  10. docker ps:默认显示正在运行中的 container
  11. docker ps –l:显示最后一次创建的 container,包括未运行的
  12. docker ps –a:显示所有的 container,包括未运行的
  13. docker logs <container>:查看 container 的日志,也就是执行命令的一些输出
  14. docker rm <container...>:删除一个或多个 container
  15. docker rm ‘ d o c k e r p s − a − q ‘ docker ps -a -q‘*dockerps−_a_−_q_‘:删除所有的 container
  16. docker ps -a -q | xargs docker rm:同上, 删除所有的 container
  17. docker rmi <image...>:删除一个或多个 image
  18. docker start/stop/restart <container>:开启/停止/重启 container
  19. docker start -i <container>:启动一个 container 并进入交互模式
  20. docker attach <container>:attach一个运行中的 container
  21. docker run <image> <command>:使用 image 创建 container 并执行相应命令,然后停止
  22. docker run -i -t <image> /bin/bash:使用 image 创建container 并进入交互模式, login shell 是 /bin/bash
  23. docker run -i -t -p <host_port:contain_port>:将 container 的端口映射到宿主机的端口
  24. docker commit <container> [repo:tag]:将一个 container 固化为一个新的 image,后面的 repo:tag 可选
  25. docker build <path>:寻找path路径下名为的 Dockerfile 的配置文件,使用此配置生成新的 image
  26. docker build -t repo[:tag]:同上,可以指定 repo 和可选的 tag
  27. docker build - <dockerfile>:使用指定的 dockerfile 配置文件,docker 以 stdin 方式获取内容,使用此配置生成新的 image
  28. docker port <container> <container port>:查看本地哪个端口映射到 container 的指定端口,其实用 docker ps 也可以看到
  29. 更改主机名:docker run -it --hostname web jim/custom1 /bin/bash

二、docker [OPTIONS] command

Usage: docker [OPTIONS] COMMAND [arg...]     
       docker daemon [ --help | ... ]     
       docker [ -h | --help | -v | --version ]     

A self-sufficient runtime for containers.     
Options:     
--config=~/.docker              Location of client config files     
-D, --debug=false               Enable debug mode     
-H, --host=[]                   Daemon socket(s) to connect to     
-h, --help=false                Print usage     
-l, --log-level=info            Set the logging level     
--tls=false                     Use TLS; implied by --tlsverify     
--tlscacert=~/.docker/ca.pem    Trust certs signed only by this CA     
--tlscert=~/.docker/cert.pem    Path to TLS certificate file     
--tlskey=~/.docker/key.pem      Path to TLS key file     
--tlsverify=false               Use TLS and verify the remote     
-v, --version=false             Print version information and quit
1234567891011121314151617

1、attach

Attach to a running container

将终端依附到容器上

Usage:  docker attach [OPTIONS] CONTAINER     
Attach to a running container     
  --help=false        Print usage     
  --no-stdin=false    Do not attach STDIN     
  --sig-proxy=true    Proxy all received signals to the process
12345

为后端运行的交互式的容器启用一个终端与之交互。

1.后台有一个可以交互的容器

2.启动该容器

3.通过 attach 启动终端与之交互

2、build

Usage:  docker build [OPTIONS] PATH | URL | -     
Build an image from a Dockerfile     
   --build-arg=[]                  Set build-time variables     
   --cpu-shares=0                  CPU shares (relative weight)     
   --cgroup-parent=                Optional parent cgroup for the container     
   --cpu-period=0                  Limit the CPU CFS (Completely Fair Scheduler) period     
   --cpu-quota=0                   Limit the CPU CFS (Completely Fair Scheduler) quota     
   --cpuset-cpus=                  CPUs in which to allow execution (0-3, 0,1)     
   --cpuset-mems=                  MEMs in which to allow execution (0-3, 0,1)     
   --disable-content-trust=true    Skip image verification     
   -f, --file=                     Name of the Dockerfile (Default is 'PATH/Dockerfile')     
   --force-rm=false                Always remove intermediate containers     
   --help=false                    Print usage     
   -m, --memory=                   Memory limit     
   --memory-swap=                  Total memory (memory + swap), '-1' to disable swap     
   --no-cache=false                Do not use cache when building the image     
   --pull=false                    Always attempt to pull a newer version of the image     
   -q, --quiet=false               Suppress the verbose output generated by the containers     
   --rm=true                       Remove intermediate containers after a successful build     
   -t, --tag=                      Repository name (and optionally a tag) for the image     
   --ulimit=[]                     Ulimit options
123456789101112131415161718192021

通过 Dockerfile 创建镜像。具体见以后的使用中。

3、commit

Usage:  docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]     
Create a new image from a container's changes    
   -a, --author=       Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")     
   -c, --change=[]     Apply Dockerfile instruction to the created image     
   --help=false        Print usage     
   -m, --message=      Commit message     
   -p, --pause=true    Pause container during commit
1234567

通过容器创建本地镜像.可自定义 tag,如 docker commit dc806ee0bf86 web:v1不指定 tag 的情况下默认 tag 为 latest

root@ubuntu:~# docker commit dc806ee0bf86 test     
1e488386876e14ef3e930a98ec0bb49de1890963e2e979069f9f4d87f89f4959   
12

4、cp

Usage:  docker cp [OPTIONS] CONTAINER:PATH LOCALPATH|-     
        docker cp [OPTIONS] LOCALPATH|- CONTAINER:PATH     
Copy files/folders between a container and the local filesystem     
Use '-' as the source to read a tar archive from stdin and extract it to a directory destination in a container.     
Use '-' as the destination to stream a tar archive of a container source to stdout.
12345

容器和宿主机之间相互 copy 文件

  1. 将容器:/data/a.txt复制到本地当前目录
docker cp 87cb69be18bb:/data/a.txt ./     
1
  1. 将本地文件复制到容器 :/data/backup 目录下
docker cp helpdocker.tgz 87cb69be18bb:/data/backup/     
1
  1. 将本地目录复制到容器 :/data/backup 目录下
docker cp data 87cb69be18bb:/data/backup
1

5、create

Usage:  docker create [OPTIONS] IMAGE [COMMAND] [ARG...]     
Create a new container     
  -a, --attach=[]                 Attach to STDIN, STDOUT or STDERR     
  --add-host=[]                   Add a custom host-to-IP mapping (host:ip)     
  --blkio-weight=0                Block IO (relative weight), between 10 and 1000     
  --cpu-shares=0                  CPU shares (relative weight)     
  --cap-add=[]                    Add Linux capabilities     
  --cap-drop=[]                   Drop Linux capabilities     
  --cgroup-parent=                Optional parent cgroup for the container     
  --cidfile=                      Write the container ID to the file     
  --cpu-period=0                  Limit CPU CFS (Completely Fair Scheduler) period     
  --cpu-quota=0                   Limit CPU CFS (Completely Fair Scheduler) quota     
  --cpuset-cpus=                  CPUs in which to allow execution (0-3, 0,1)     
  --cpuset-mems=                  MEMs in which to allow execution (0-3, 0,1)     
  --device=[]                     Add a host device to the container     
  --disable-content-trust=true    Skip image verification     
  --dns=[]                        Set custom DNS servers     
  --dns-opt=[]                    Set DNS options     
  --dns-search=[]                 Set custom DNS search domains     
  -e, --env=[]                    Set environment variables     
  --entrypoint=                   Overwrite the default ENTRYPOINT of the image     
  --env-file=[]                   Read in a file of environment variables     
  --expose=[]                     Expose a port or a range of ports     
  --group-add=[]                  Add additional groups to join     
  -h, --hostname=                 Container host name     
  --help=false                    Print usage     
  -i, --interactive=false         Keep STDIN open even if not attached     
  --ipc=                          IPC namespace to use     
  --kernel-memory=                Kernel memory limit     
  -l, --label=[]                  Set meta data on a container     
  --label-file=[]                 Read in a line delimited file of labels     
  --link=[]                       Add link to another container     
  --log-driver=                   Logging driver for container     
  --log-opt=[]                    Log driver options     
  --lxc-conf=[]                   Add custom lxc options     
  -m, --memory=                   Memory limit     
  --mac-address=                  Container MAC address (e.g. 92:d0:c6:0a:29:33)     
  --memory-reservation=           Memory soft limit     
  --memory-swap=                  Total memory (memory + swap), '-1' to disable swap     
  --memory-swappiness=-1          Tuning container memory swappiness (0 to 100)     
  --name=                         Assign a name to the container     
  --net=default                   Set the Network for the container     
  --oom-kill-disable=false        Disable OOM Killer     
  -P, --publish-all=false         Publish all exposed ports to random ports     
  -p, --publish=[]                Publish a container's port(s) to the host     
  --pid=                          PID namespace to use     
  --privileged=false              Give extended privileges to this container     
  --read-only=false               Mount the container's root filesystem as read only     
  --restart=no                    Restart policy to apply when a container exits     
  --security-opt=[]               Security Options     
  --stop-signal=SIGTERM           Signal to stop a container, SIGTERM by default     
  -t, --tty=false                 Allocate a pseudo-TTY     
  -u, --user=                     Username or UID (format: <name|uid>[:<group|gid>])     
  --ulimit=[]                     Ulimit options     
  --uts=                          UTS namespace to use     
  -v, --volume=[]                 Bind mount a volume     
  --volume-driver=                Optional volume driver for the container     
  --volumes-from=[]               Mount volumes from the specified container(s)     
  -w, --workdir=                  Working directory inside the container
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859

创建但不启动一个容器.具体参数同 docker run.

6、diff

Usage:  docker diff [OPTIONS] CONTAINER     
Inspect changes on a container's filesystem     
  --help=false       Print usage
123

查看容器内发生变化的文件。

$ docker diff 87cb69be18bb
A /data     
A /data/a.txt     
A /data/b     
A /data/backup     
A /data/backup/data     
A /data/backup/helpdocker.tgz     
C /root     
A /root/.bash_history
123456789

7、events

Usage:  docker events [OPTIONS]     
Get real time events from the server     
    -f, --filter=[]    Filter output based on conditions provided     
    --help=false       Print usage     
    --since=           Show all events created since timestamp     
    --until=           Stream events until this timestamp   
123456

实时输出 docker 服务器端的事件,包括容器的创建、启动、关闭等。

$ docker events
2016-08-26T10:42:08.001137030+08:00 87cb69be18bbe74ea9e14b16228ccc3347dcffb3e074fa303ca32deb46417105: (from ubuntu:14.04) die
12

8、exec

Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]     
Run a command in a running container     
  -d, --detach=false         Detached mode: run command in the background     
  --help=false               Print usage     
  -i, --interactive=false    Keep STDIN open even if not attached     
  --privileged=false         Give extended privileges to the command     
  -t, --tty=false            Allocate a pseudo-TTY     
  -u, --user=                Username or UID (format: <name|uid>[:<group|gid>])
12345678

通过宿主机在正在运行的容器上执行命令。通过宿主机在容器上创建文件

$ docker exec 87cb69be18bb touch /root/abc.txt  
1

可通过 exec 命令申请一个终端,执行 shell:

$ docker exec -it 87cb69be18bb /bin/bash
root@87cb69be18bb:/# ls     
abc  bin  boot  data  dev  etc  home  ifconfig  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
123

9、export

Usage:  docker export [OPTIONS] CONTAINER     
Export a container's filesystem as a tar archive     
    --help=false       Print usage     
    -o, --output=      Write to a file, instead of STDOUT
1234

将容器的文件系统打包成 tar 文件。

两种方式:

$ docker export 87cb69be18bb > web.tar     
$ docker export -o web.tar 87cb69be18bb   
12

10、history

Usage:  docker history [OPTIONS] IMAGE     
Show the history of an image     
    -H, --human=true     Print sizes and dates in human readable format     
    --help=false         Print usage     
    --no-trunc=false     Don't truncate output     
    -q, --quiet=false    Only show numeric IDs       
123456

显示一个镜像的历史

$ docker history ubuntu:14.04     
IMAGE          CREATED                           CREATED BY         SIZE    COMMENT     
d9560c05d6bd   2 weeks ago         /bin/sh -c #(nop) CMD ["/bin/bash"]             0 B                      
001bed837092   2 weeks ago         /bin/sh -c sed -i 's/^#\s*\(deb.*universe\)$/   1.895 kB                 
92b3f03280cc   2 weeks ago         /bin/sh -c rm -rf /var/lib/apt/lists/*          0 B                      
24e6f8fb4abf   2 weeks ago         /bin/sh -c set -xe   && echo '#!/bin/sh' > /u   194.6 kB                 
50ed19911a3e   2 weeks ago         /bin/sh -c #(nop) ADD file:4f5a660d3f5141588d   187.8 MB       
1234567

11、images

Usage:  docker images [OPTIONS] [REPOSITORY[:TAG]]     
List images     
    -a, --all=false      Show all images (default hides intermediate images)     
    --digests=false      Show digests     
    -f, --filter=[]      Filter output based on conditions provided     
    --help=false         Print usage     
    --no-trunc=false     Don't truncate output     
    -q, --quiet=false    Only show numeric IDs   
12345678

显示所有的镜像。

12、import

Usage:  docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]     
Import the contents from a tarball to create a filesystem image     
    -c, --change=[]    Apply Dockerfile instruction to the created image     
    --help=false       Print usage     
    -m, --message=     Set commit message for imported image
12345

根据 export 出的 tar 文件创建一个镜像,和 export 相结合使用,这种方式容器的层结构将会丢失。

# docker import web.tar web
1

13、info

Usage:  docker info [OPTIONS]     
Display system-wide information     
    --help=false       Print usage    
123

查看 docker 的全局信息

# docker info
Containers: 1     
Images: 25     
Server Version: 1.9.1     
Storage Driver: aufs     
    Root Dir: /var/lib/docker/aufs     
    Backing Filesystem: extfs     
    Dirs: 27     
    Dirperm1 Supported: false     
Execution Driver: native-0.2     
Logging Driver: json-file     
Kernel Version: 3.13.0-32-generic     
Operating System: Ubuntu 14.04.1 LTS     
CPUs: 1     
Total Memory: 986.8 MiB     
Name: ubuntu     
ID: ALLP:KE4W:ITY7:WUL6:QKUG:4CGB:R6IA:2UXG:227D:K6BF:EDLL:27TX     
WARNING: No swap limit support
123456789101112131415161718

14、inspect

Usage:  docker inspect [OPTIONS] CONTAINER|IMAGE [CONTAINER|IMAGE...]     
Return low-level information on a container or image     
    -f, --format=       Format the output using the given go template     
    --help=false        Print usage     
    -s, --size=false    Display total file sizes if the type is container     
    --type=             Return JSON for specified type, (e.g image or container)
123456

用于查看容器的所有配置信息,包含容器名、环境变量、运行命令、主机配置、网络配置和数据卷配置等。

$ docker inspect nextcloud
[
    {
        "Id": "4f798fc8f1b5bcde38aa3702a02e06d996ae4608e8c369237754ae50e950f7ca",
        "Created": "2018-08-10T03:28:36.570570242Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 19066,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2018-08-15T01:51:36.80771433Z",
            "FinishedAt": "2018-08-15T01:51:36.267209678Z"
        },
        "Image": "sha256:c3342f6abac82e375ec5c5e64be74afee47af31e39ba480a55fd912aa45a722b",
        "ResolvConfPath": "/var/lib/docker/containers/4f798fc8f1b5bcde38aa3702a02e06d996ae4608e8c369237754ae50e950f7ca/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/4f798fc8f1b5bcde38aa3702a02e06d996ae4608e8c369237754ae50e950f7ca/hostname",
        "HostsPath": "/var/lib/docker/containers/4f798fc8f1b5bcde38aa3702a02e06d996ae4608e8c369237754ae50e950f7ca/hosts",
        "LogPath": "/var/lib/docker/containers/4f798fc8f1b5bcde38aa3702a02e06d996ae4608e8c369237754ae50e950f7ca/4f798fc8f1b5bcde38aa3702a02e06d996ae4608e8c369237754ae50e950f7ca-json.log",
        "Name": "/nextcloud",
        "RestartCount": 2,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "ExecIDs": null,    
123456789101112131415161718192021222324252627282930313233

15、kill

Usage:  docker kill [OPTIONS] CONTAINER [CONTAINER...]     
Kill a running container     
  --help=false         Print usage     
  -s, --signal=KILL    Signal to send to the container    
1234

强制终止容器.关于 stop 和 kill 的区别:docker stop 命令给容器中的进程发送 SIGTERM 信号,默认行为是会导致容器退出,当然,容器内程序可以捕获该信号并自行处理,例如可以选择忽略。而 dockerkill 则是给容器的进程发送 SIGKILL 信号,该信号将会使容器必然退出。

16、load

Usage:  docker load [OPTIONS]     
Load an image from a tar archive or STDIN     
  --help=false       Print usage     
  -i, --input=       Read from a tar archive file, instead of STDIN   
1234

与下面的 save 命令相对应,将下面 sava 命令打包的镜像通过 load 命令导入。

17、login

Usage:  docker login [OPTIONS] [SERVER]     
Register or log in to a Docker registry.     
If no server is specified "https://index.docker.io/v1/" is the default.     
    -e, --email=       Email     
    --help=false       Print usage     
    -p, --password=    Password     
    -u, --username=    Username   
1234567

登录到自己的 Docker register,需有 Docker Hub 的注册账号,或者自行搭建的私有仓库。

18、logout

Usage:  docker logout [OPTIONS] [SERVER]     
Log out from a Docker registry.     
If no server is specified "https://index.docker.io/v1/" is the default.     
    --help=false       Print usage   
1234

从 Docker register 退出登录。

19、logs

Fetch the logs of a container     
  -f, --follow=false        Follow log output     
  --help=false              Print usage     
  --since=                  Show logs since timestamp     
  -t, --timestamps=false    Show timestamps     
  --tail=all                Number of lines to show from the end of the logs
123456

用于查看容器的日志,它将输入(出)到容器标准输入(出)的数据,作为日志输出到 docker logs 命令的终端上。常用于后台型容器。87cb69be18bb 是一个数据流为输入、输出和错误和容器,如下命令则会打印该容器的所有交互日志。

# docker logs 87cb69be18bb    
1

来个综合点的,查询容器最新的 3 条日志并打上时间戳:

# docker logs -f -t --tail=3 nextcloud   
2018-08-15T01:51:23.500951699Z root@nextcloud:/# 
2018-08-15T01:51:36.154541783Z root@nextcloud:/# exit
2018-08-15T01:51:36.154917668Z exit
1234

20、network

  Usage:  docker network [OPTIONS] COMMAND [OPTIONS]     
    Commands:     
      create                   Create a network     
      connect                  Connect container to a network     
      disconnect               Disconnect container from a network     
      inspect                  Display detailed network information     
      ls                       List all networks     
      rm                       Remove a network     
12345678

20.1、创建网络

Usage:  docker network create [OPTIONS] NETWORK-NAME     
Creates a new network with a name specified by the user     
  --aux-address=map[]      auxiliary ipv4 or ipv6 addresses used by Network driver     
  -d, --driver=bridge      Driver to manage the Network     
  --gateway=[]             ipv4 or ipv6 Gateway for the master subnet     
  --help=false             Print usage     
  --ip-range=[]            allocate container ip from a sub-range     
  --ipam-driver=default    IP Address Management Driver     
  -o, --opt=map[]          set driver specific options     
  --subnet=[]              subnet in CIDR format that represents a network segment  
12345678910

自定义网络,可指定网段、网关等参数。创建一个 my_network 的网络,–ip-range:指定子网段,–subnet:指定一个网段

$ docker network create -d bridge --ip-range=192.168.1.0/24 --subnet=192.168.1.0/24 my_network
1

20.2、查看网络

  Usage:  docker network inspect [OPTIONS] NETWORK [NETWORK...]     
  Displays detailed information on a network     
  
  $ docker network inspect my_network
    [     
        {     
            "Name": "my_network",     
            "Id": "414e1dd5d71ea709be885be5c283ed8080c8ca22e9baad0dc242865dd39164fd",     
            "Scope": "local",     
            "Driver": "bridge",     
            "IPAM": {     
                "Driver": "default",     
                "Config": [     
                    {     
                        "Subnet": "192.168.1.0/24",     
                        "IPRange": "192.168.1.0/24"     
                    }     
                ]     
            },     
            "Containers": {},     
            "Options": {}     
        }     
    ]
1234567891011121314151617181920212223

20.3、列出网络

Usage:  docker network ls [OPTIONS]     
Lists networks     
  --no-trunc=false     Do not truncate the output     
  -q, --quiet=false    Only display numeric IDs    
1234
$ docker network ls
NETWORK ID          NAME                DRIVER     
90b8ebd11e4f        bridge              bridge                   
77dd4f913ba1        none                null                     
65dfd6ebddab        host                host                     
414e1dd5d71e        my_network          bridge
123456

bridge 为默认的网络,172.17.0.0/16 网段my_network 为自定义的网格

20.4、删除网络

Usage:  docker network rm [OPTIONS] NETWORK    
Deletes a network   

$ docker network rm my_network1     
1234

20.5、连接网络

Usage:  docker network connect [OPTIONS] NETWORK CONTAINER     
Connects a container to a network   
12

将容器连接到指定的网络。

1.创建一个容器,不指定网络,默认会用 bridge 网络。

$ #docker run -it --name=web ubuntu:14.04 /bin/bash     
1

会看到默认有 eth0:172.17.0.0/16 段

root@d35ef0bda3fb:/# ifconfig
eth0      Link encap:Ethernet  HWaddr 02:42:ac:11:00:02  
          inet addr:172.17.0.2  Bcast:0.0.0.0  Mask:255.255.0.0
          inet6 addr: fe80::42:acff:fe11:2/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:5 errors:0 dropped:0 overruns:0 frame:0
          TX packets:6 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:418 (418.0 B)  TX bytes:508 (508.0 B)
lo        Link encap:Local Loopback  
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0 
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B) 
1234567891011121314151617

2.将该容器连接到 my_network 网络连接到的容器必须是 running 状态。

$ docker network connect my_network web     
1

3.查看容器网络状态会看到多出一个 eth1:192.168.1.0/24 网段

root@d35ef0bda3fb:/# ifconfig     
eth0      Link encap:Ethernet  HWaddr 02:42:ac:11:00:02       
          inet addr:172.17.0.2  Bcast:0.0.0.0  Mask:255.255.0.0     
          inet6 addr: fe80::42:acff:fe11:2/64 Scope:Link     
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1     
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0     
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0     
          collisions:0 txqueuelen:0      
          RX bytes:648 (648.0 B)  TX bytes:648 (648.0 B)     

eth1      Link encap:Ethernet  HWaddr 02:42:c0:a8:01:02       
          inet addr:192.168.1.2  Bcast:0.0.0.0  Mask:255.255.255.0     
          inet6 addr: fe80::42:c0ff:fea8:102/64 Scope:Link     
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1     
          RX packets:8 errors:0 dropped:0 overruns:0 frame:0     
          TX packets:8 errors:0 dropped:0 overruns:0 carrier:0     
          collisions:0 txqueuelen:0      
          RX bytes:648 (648.0 B)  TX bytes:648 (648.0 B)  
123456789101112131415161718

20.6、断开网络

Usage:  docker network disconnect [OPTIONS] NETWORK CONTAINER     
Disconnects container from a network     
12

将容器与一个网络断开

# docker network disconnect my_network web     
1

断开后该容器不在拥有该网络的地址。

21、pause

Usage:  docker pause [OPTIONS] CONTAINER [CONTAINER...]     
Pause all processes within a container     
  --help=false       Print usage    
123

暂停容器内的所有进程。此时,通过 docker stats 可以观察到此时的资源使用情况是固定不变的,通过 docker logs -f 也观察不到日志的进一步输出。

$ docker pause 87cb69be18bb     
1

容器的状态变为:Up About an hour (Paused) docker unpause 重新启动一个容器。

22、port

Usage:  docker port [OPTIONS] CONTAINER [PRIVATE_PORT[/PROTO]]     
List port mappings or a specific mapping for the CONTAINER    
12

输出容器端口与宿主机端口的映射情况

# docker port blog     
80/tcp -> 0.0.0.0:80     
12

容器 blog 的内部端口 80 映射到宿主机的 80 端口,这样可通过宿主机的 80 端口查看容器 blog 提供的服务

23、ps

 Usage:  docker ps [OPTIONS]     
    List containers     
      -a, --all=false       Show all containers (default shows just running)     
      --before=             Show only container created before Id or Name     
      -f, --filter=[]       Filter output based on conditions provided     
      --format=             Pretty-print containers using a Go template     
      --help=false          Print usage     
      -l, --latest=false    Show the latest created container, include non-running     
      -n=-1                 Show n last created containers, include non-running     
      --no-trunc=false      Don't truncate output     
      -q, --quiet=false     Only display numeric IDs     
      -s, --size=false      Display total file sizes     
      --since=              Show created since Id or Name, include non-running      
12345678910111213

列出所有容器,其中 docker ps 用于查看正在运行的容器,ps -a 则用于查看所有容器。

24、pull

   Usage:  docker pull [OPTIONS] NAME[:TAG|@DIGEST]     
    Pull an image or a repository from a registry     
      -a, --all-tags=false            Download all tagged images in the repository     
      --disable-content-trust=true    Skip image verification     
      --help=false                    Print usage
12345

从 registry 中拉取镜像。

25、push

Usage:  docker push [OPTIONS] NAME[:TAG]     
Push an image or a repository to a registry     
  --disable-content-trust=true    Skip image signing     
  --help=false                    Print usage    
1234

本地的镜像上传到 registry 中

26、rename

Usage:  docker rename [OPTIONS] OLD_NAME NEW_NAME     
Rename a container     
  --help=false       Print usage    
123

更改容器的名字将容器 tender_lichterman 更名为 web1

# docker rename tender_lichterman web1     
1

27、restart

Usage:  docker restart [OPTIONS] CONTAINER [CONTAINER...]     
Restart a container     
  --help=false       Print usage     
  -t, --time=10      Seconds to wait for stop before killing the container
1234

重启一个容器。

28、rm

Usage:  docker rm [OPTIONS] CONTAINER [CONTAINER...]     
Remove one or more containers     
  -f, --force=false      Force the removal of a running container (uses SIGKILL)     
  --help=false           Print usage     
  -l, --link=false       Remove the specified link     
  -v, --volumes=false    Remove the volumes associated with the container
123456

删除容器。不可以删除一个运行中的容器,必须先用 docker stop 或 docker kill 使其停止。当然可以强制删除,必须加 -f 参数。如果要一次性删除所有容器,可使用 docker rm -f $(docker ps -a -q),其中,-q 指的是只列出容器的 ID。

29、rmi

Usage:  docker rmi [OPTIONS] IMAGE [IMAGE...]     
Remove one or more images     
  -f, --force=false    Force removal of the image     
  --help=false         Print usage     
  --no-prune=false     Do not delete untagged parents
12345

删除一个或多个镜像。

30、save

Usage:  docker save [OPTIONS] IMAGE [IMAGE...]     
Save an image(s) to a tar archive (streamed to STDOUT by default)     
  --help=false       Print usage     
  -o, --output=      Write to a file, instead of STDOUT
1234

将镜像打包,与上面的 load 命令相对应.两种方式:

# docker save webserver >webserver.tar     
# docker save -o webserver.tar webserver:v1
12

31、search

   Usage:  docker search [OPTIONS] TERM     
    Search the Docker Hub for images     
      --automated=false    Only show automated builds     
      --help=false         Print usage     
      --no-trunc=false     Don't truncate output     
      -s, --stars=0        Only displays with at least x stars    
123456

查找镜像。

32、start

Usage:  docker start [OPTIONS] CONTAINER [CONTAINER...]     
Start one or more stopped containers     
  -a, --attach=false         Attach STDOUT/STDERR and forward signals     
  --help=false               Print usage     
  -i, --interactive=false    Attach container's STDIN   
12345

启动一个或多个停止的镜像。启动一个镜像并启动一个交互试的终端。

$ docker start -ia 87cb69be18bb     

root@87cb69be18bb:/# ls
123

33、stats

Usage:  docker stats [OPTIONS] CONTAINER [CONTAINER...]     
Display a live stream of container(s) resource usage statistics     
  --help=false         Print usage     
  --no-stream=false    Disable streaming stats and only pull the first result    
1234

动态显示容器的资源消耗情况,包括:CPU、内存、网络I/O

34、stop

Usage:  docker stop [OPTIONS] CONTAINER [CONTAINER...]     
Stop a running container.     
Sending SIGTERM and then SIGKILL after a grace period     
  --help=false       Print usage     
  -t, --time=10      Seconds to wait for stop before killing it    
12345

停止一个正在运行的容器。

35、tag

 Usage:  docker tag [OPTIONS] IMAGE[:TAG] [REGISTRYHOST/][USERNAME/]NAME[:TAG]     
    Tag an image into a repository     
      -f, --force=false    Force     
      --help=false         Print usage    
1234

对 repository 中的镜像进行重命名。tag 后的镜像和原镜像拥有相同的I D。

36、top

   Usage:  docker top [OPTIONS] CONTAINER [ps OPTIONS]     
    Display the running processes of a container       
12

查看容器中正在运行的进程。

$ docker top 87cb69be18bb     
UID      PID    PPID      C        STIME     TTY     TIME            CMD     
root     512    679       0        12:59      pts/3   00:00:00        /bin/bash
123

37、unpause

Usage:  docker unpause [OPTIONS] CONTAINER [CONTAINER...]     
Unpause all processes within a container     
  --help=false       Print usage    
123

恢复容器内暂停的进程,与 pause 参数相对应。

38、version

Usage:  docker version [OPTIONS]     
Show the Docker version information     
  -f, --format=      Format the output using the given go template     
  --help=false       Print usage   
1234

查看 docker 版本信息

   $ docker version     
    Client:     
     Version:      1.9.1     
     API version:  1.21     
     Go version:   go1.4.3     
     Git commit:   a34a1d5     
     Built:        Fri Nov 20 17:56:04 UTC 2015     
     OS/Arch:      linux/amd64     

    Server:     
     Version:      1.9.1     
     API version:  1.21     
     Go version:   go1.4.3     
     Git commit:   a34a1d5     
     Built:        Fri Nov 20 17:56:04 UTC 2015     
     OS/Arch:      linux/amd64
12345678910111213141516

39、volume

Usage:  docker volume [OPTIONS] [COMMAND]     
Manage Docker volumes     
Commands:     
  create                   Create a volume     
  inspect                  Return low-level information on a volume     
  ls                       List volumes     
  rm                       Remove a volume
1234567

管理 docker 数据卷

39.1、创建数据卷

Usage:  docker volume create [OPTIONS]     
Create a volume     
  -d, --driver=local    Specify volume driver name     
  --name=           Specify volume name     
  -o, --opt=map[]       Set driver specific options
12345

1.创建一个名为 data_v 的数据卷

$ docker volume create --name='data_v'     
1

2.创建完数据卷后,其他容器即可挂载该容器。可用于数据共享。3.创建一个容器,把名为 data_v 的数据卷挂载到容器的 /data 目录

$ docker run -it -v data_v:/data ubuntu:14.04 /bin/bash    
1

39.2、查看数据卷

Usage:  docker volume inspect [OPTIONS] VOLUME [VOLUME...]     
Return low-level information on a volume     
  -f, --format=      Format the output using the given go template   
123

查看刚刚创建的数据卷

$ docker volume inspect data_v
[     
    {     
        "Name": "data_v",     
        "Driver": "local",     
        "Mountpoint": "/var/lib/docker/volumes/data_v/_data"     
    }     
]
12345678

39.3、列出数据卷

Usage:  docker volume ls [OPTIONS]     
List volumes     
  -f, --filter=[]      Provide filter values (i.e. 'dangling=true')     
  -q, --quiet=false    Only display volume names   

$ docker volume ls  
DRIVER              VOLUME NAME
local               04ad14c9c5dbeecd08fe37927024b73efc809da9698eb7000c63e214e929ec15
local               067591aee8ac7ab721de3cba6896c9574703d434604e74f97ff489eecda42777
local               127dcc895206f024f9ece5d88da97db7ea0a9b689f2cf662a38f9baaba441755
local               19fc4d60583be9cda8b0d3f408e64c69efcad90dcab617655b22983588cc8a7c
local               1a1020d07eddf1d796dcef60e89f4a65cfd440c4817ea5d2d9cc608af8b3c139
123456789101112

39.4、删除数据卷

Usage:  docker volume rm [OPTIONS] VOLUME [VOLUME...]

$ docker volume rm data_v     
123

40、wait

   Usage:  docker wait [OPTIONS] CONTAINER [CONTAINER...]     
    Block until a container stops, then print its exit code     
      --help=false       Print usage   
123

捉容器停止时的退出码。执行此命令后,该命令会“hang”在当前终端,直到容器停止,此时,会打印出容器的退出码。