全局信息

info|help|version

docker info
docker help
docker version

docker help可以查看到docker支持的所有命令,基础功能包括三个方面:容器生命周期管理、容器管理、镜像管理。

容器本身可以和一个进程进行类比,管理方式上也相似,只不过docker提供了一组简明的接口来专门管理。

镜像可以类比为可执行文件,相比于普通应用程序,它涵盖了几乎所有的配置,在不同平台上启动不需要配置环境。镜像管理方式上也和普通程序有所不同,由于它可以保留提交历史记录,所以用起来会更加方便。

生命周期

create|run|update

docker run实际上包括两步:第一步调用docker create,第二步运行容器。二者参数几乎一样。 docker update则用于更改容器配置。

docker run [OPTIONS] IMG [CMD] [ARGS...]
-i                      interactive mode
-a                      attach stdio
-d                      detach stdio, backgroud
-c                      cpu share, defaut using max 1024
-m                      memory limit, unit: b,k,m,g
-t                      allocate a tty
-v H:C                  mount container dir to host: -v /host:/container
-w                      working directory inside the container
-p PORT                 expose container port
--name                  assign a name
--entrypoint            overwrite default ENTRYPOINT
--expose                expose a port
--link                  link to another container
--rm                    auto remove container when stopped
--mac-address           set mac address
--ipc=host              using host shm, semaphore, mq
--ipc=container:CID     using container shm, semaphore, mq
--cap-add|--cap-drop    add or drop cap
--net                   bridge: create network stack on the docker bridge
                        none: no networking
                        container: reuse another container network stack
                        host: use the host network stack
--volumes-from VALUE    Mount volumes from the specified container
--privileged            给容器特权

docker update CONTAINER [CONTAINER...]
  --blkio-weight        Block IO (relative weight), between 10 and 1000
  -c, --cpu-shares      CPU shares (relative weight)
  --cpu-period          Limit CPU CFS (Completely Fair Scheduler) period
  --cpu-quota           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)
  --help                Print usage
  --kernel-memory       Kernel memory limit
  -m, --memory          Memory limit
  --memory-reservation  Memory soft limit
  --memory-swap         Swap limit equal to memory plus swap: '-1' to enable unlimited swap
  --restart             Restart policy to apply when a container exits

运行容器会返回容器ID(记为CID),很多对容器操作的命令都是用CID来指定容器。使用时只需要使用CID前面几位就可以了。

volume(-v)有两种形式:-v host:container-v container,前者称为绑定模式。执行docker rm -v CID时,绑定模式的volume不会被删除。

docker run -it --entrypoint /bin/bash IMG # overwrite entrypoint
docker run -d ubuntu /bin/sh -c "while true; do date >> /var/hello.log; sleep 1; done"

# backup dbdata:/var/lib/postgresql/data
docker run --rm --volumes-from dbdata -v $(pwd):/backup debian \
       tar -czf /backup/backup.tar.gz /var/lib/postgresql/data

给容器特权--priviliged需要谨慎,特权可以让容器起容器,也可以让容器访问主机上的设备。标准容器可以用df查看文件系统和设备映射,但是不能看到/dev/sdx设备,特权容器则不同,能够看到硬盘设备,也能够挂载设备。所以这个权限是否开启需要十分谨慎,开启就意味着主机在容器中完全暴露了。相关论述可参考:Privileged Docker Containers

和特权相关的还有--cap-add--cap-drop选项,默认选项包括:

权限 含义
SETPCAP 修改进程CAP
MKNOD 创建特殊文件:mknod
AUDIT_WRITE 写内核日志
CHOWN 修改UIDs和GIDs
NET_RAW 使用RAW/PACKET套接字
DAC_OVERRIDE 绕过文件RWX检查
FOWNER 绕过文件UID检查
FSETID 文件修改时不清除SUID和SGID权限位
KILL 绕过发送信号权限检查
SETGID 更改GID
SETUID 更改UID
NET_BIND_SERVICE 绑定套接字到特权端口(<1024)
SYS_CHROOT 修改root目录:chroot
SETFCAP 设置文件权限

默认未添加的权限包括:

权限 含义
SYS_MODULE 内核模块载入和卸载
SYS_RAWIO IO端口操作:iopl, ioperm
SYS_PACCT 进程记账开关:acct
SYS_ADMIN 系统管理操作
SYS_NICE 修改进程优先级:nice, setpriority
SYS_RESOURCE 修改资源限制
SYS_TIME 设置系统和硬件时钟:settimeofday, stime, adjtimex
SYS_TTY_CONFIG 用于对TTY的各种特权ioctl操作
AUDIT_CONTROL 开启/关闭内核审计日志,查看状态和过滤规则
MAC_OVERRIDE 配置MAC和修改状态,用于LSM
MAC_ADMIN 覆盖MAC,用于LSM
NET_ADMIN 网络相关操作
SYSLOG 特权syslog操作
DAC_READ_SEARCH 绕过文件执行权限和目录访问权限检查
LINUX_IMMUTABLE 设置inode标志位:FS_APPEND_FL, FS_IMMUTABLE_FL
NET_BROADCAST 发送广播,监听多播
IPC_LOCK 内存锁:mlock, mlockall, mmap, shmctl
IPC_OWNER 绕过对System V IPC对象的权限检查
SYS_PTRACE 跟踪进程:ptrace
SYS_BOOT 重启和载入新的内核:reboot, kexec_load
LEASE 创建租期:fcntl
WAKE_ALARM 通过触发某些条件唤醒系统
BLOCK_SUSPEND 阻塞系统挂起

entrypoint|cmd

这两个参数在Dockerfile中对应两个指令。

Dockerfile中的CMD有三种用途:

  1. 以shell形式执行命令(shell form)
  2. 运行可执行文件并提供参数(exec form)
  3. 给ENTRYPOINT提供参数(args form)

运行docker run命令时指定CMD会覆盖Dockerfile的CMD指令。

Dockerfile中的ENTRYPOINT用于指定容器入口,所有容器都有ENTRYPOINT,无论哪种形式的CMD本质上都是ENTRYPOINT的参数。只不过像/bin/bash这样的ENTRYPOINT让CMD看起来有三种形式而已。

wait|stop|start|restart|kill|rm

这一组命令都是相同的格式,如:docker stop [OPTIONS] CID [CID...]

docker wait用于等待容器结束并打印退出码。 docker stop首先发送SIGTERM,然后发送SIGKILLdocker kill直接发送SIGKILL或指定的信号。 docker rm用于清理数据,该命令不能删除运行中的容器。

docker wait

docker stop
  -t, --time int        Seconds to wait for stop before killing it (default 10)

docker start
  -a, --attach          Attach STDOUT/STDERR and forward signals
  -i, --interactive     Attach container's STDIN

docker restart
  -t, --time int        Seconds to wait for stop before killing the container (default 10)

docker kill
  -s, --signal string   Signal to send to the container (default "KILL")

docker rm
  -f, --force           Force the removal of a running container (uses SIGKILL)
  -l, --link            Remove the specified link
  -v, --volumes         Remove the volumes associated with the container
# stop and remove all container
docker stop $(docker ps -q)
docker rm $(docker ps -qa)

容器管理

ps|top|logs|stats|diff

docker stats用于查看资源使用统计信息,默认只显示运行容器的统计信息。

docker ps [OPTIONS]
  -a, --all             Show all containers (default shows just running)
  -f, --filter value    Filter output based on conditions provided (default [])
      --format string   Pretty-print containers using a Go template
  -n, --last int        Show n last created containers (includes all states) (default -1)
  -l, --latest          Show the latest created container (includes all states)
      --no-trunc        Don't truncate output
  -q, --quiet           Only display numeric IDs
  -s, --size            Display total file sizes

docker top CONTAINER [ps OPTIONS]

docker logs [OPTIONS] CONTAINER
      --details         Show extra details provided to logs
  -f, --follow          Follow log output
      --since string    Show logs since timestamp
      --tail string     Number of lines to show from the end of the logs (default "all")
  -t, --timestamps      Show timestamps

docker stats [OPTIONS] [CONTAINER...]
  -a, --all             Show all containers (default shows just running)
      --no-stream       Disable streaming stats and only pull the first result

docker diff CONTAINER

port|events|inspect

docker port用于显示端口映射。

docker port CONTAINER [PRIVATE_PORT[/PROTO]]

docker events [OPTIONS]
  -f, --filter value   Filter output based on conditions provided (default [])
      --since string   Show all events created since timestamp
      --until string   Stream events until this timestamp

docker inspect [OPTIONS] CONTAINER|IMAGE|TASK [CONTAINER|IMAGE|TASK...]
  -f, --format       Format the output using the given go template
  -s, --size         Display total file sizes if the type is container
  --type             Return JSON for specified type, (e.g image, container or task)

rename|attach|pause|unpause

docker rename由于修改容器名字。 docker pause用于暂停容器中的所有进程。

docker rename OLD_NAME NEW_NAME
docker attach [OPTIONS] CONTAINER
      --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)

docker pause CONTAINER [CONTAINER...]
docker unpause CONTAINER [CONTAINER...]

cp|exec

docker exec基本上就是一个后门程序,使用该命令可以随意的窥探并修改容器。

docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
  -L, --follow-link   Always follow symbol link in SRC_PATH

docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
  -d, --detach         Detached mode: run command in the background
  --detach-keys        Override the key sequence for detaching a container
  --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           Username or UID (format: <name|uid>[:<group|gid>])

镜像管理

images|commit|tag|rmi|history

commit用于将容器保存为镜像,tag用于修改镜像名, rmi删除镜像需要确保没有容器和镜像依赖目标镜像。

docker images [OPTIONS] [REPOSITORY[:TAG]]
  -a, --all             Show all images (default hides intermediate images)
      --digests         Show digests
  -f, --filter value    Filter output based on conditions provided (default [])
      --format string   Pretty-print images using a Go template
      --no-trunc        Don't truncate output
  -q, --quiet           Only show numeric IDs

docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]
  -a, --author string   Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
  -c, --change value    Apply Dockerfile instruction to the created image (default [])
  -m, --message string  Commit message
  -p, --pause           Pause container during commit (default true)

docker tag IMAGE[:TAG] IMAGE[:TAG]

docker rmi [OPTIONS] IMAGE [IMAGE...]
  -f, --force           Force removal of the image
      --no-prune        Do not delete untagged parents

docker history [OPTIONS] IMAGE
  -H, --human      Print sizes and dates in human readable format (default true)
      --no-trunc   Don't truncate output
  -q, --quiet      Only show numeric IDs

build|export|import|save|load

export|import的对象是容器,save|load的对象是镜像,后者包括完整的提交历史。

docker build [OPTIONS] PATH | URL | -
      --build-arg value         Set build-time variables (default [])
      --cgroup-parent string    Optional parent cgroup for the container
      --cpu-period int          Limit the CPU CFS (Completely Fair Scheduler) period
      --cpu-quota int           Limit the CPU CFS (Completely Fair Scheduler) quota
  -c, --cpu-shares int          CPU shares (relative weight)
      --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)
      --disable-content-trust   Skip image verification (default true)
  -f, --file string             Name of the Dockerfile (Default is 'PATH/Dockerfile')
      --force-rm                Always remove intermediate containers
      --help                    Print usage
      --isolation string        Container isolation technology
      --label value             Set metadata for an image (default [])
  -m, --memory string           Memory limit
      --memory-swap string      Swap limit equal to memory plus swap: '-1' to enable unlimited swap
      --no-cache                Do not use cache when building the image
      --pull                    Always attempt to pull a newer version of the image
  -q, --quiet                   Suppress the build output and print image ID on success
      --rm                      Remove intermediate containers after a successful build (default true)
      --shm-size string         Size of /dev/shm, default value is 64MB
  -t, --tag value               Name and optionally a tag in the 'name:tag' format (default [])
      --ulimit value            Ulimit options (default [])

docker export [OPTIONS] CONTAINER
  -o, --output string   Write to a file, instead of STDOUT

docker import [OPTIONS] file|URL|- [REPOSITORY[:TAG]]
  -c, --change value    Apply Dockerfile instruction to the created image (default [])
  -m, --message string  Set commit message for imported image

docker save [OPTIONS] IMAGE [IMAGE...]
  -o, --output string   Write to a file, instead of STDOUT

docker load [OPTIONS]
  -i, --input string    Read from tar archive file, instead of STDIN
  -q, --quiet           Suppress the load output
docker save -o images.tar ubuntu centos
docker load -i images.tar

login|logout|pull|push|search

docker login [OPTIONS] [SERVER]
  -p, --password string   Password
  -u, --username string   Username

docker logout [SERVER]

docker pull [OPTIONS] NAME[:TAG|@DIGEST]
  -a, --all-tags                Download all tagged images in the repository
      --disable-content-trust   Skip image verification (default true)

docker push [OPTIONS] NAME[:TAG]
      --disable-content-trust   Skip image verification (default true)

docker search [OPTIONS] TERM
  -f, --filter value   Filter output based on conditions provided (default [])
      --limit int      Max number of search results (default 25)
      --no-trunc       Don't truncate output

volume

docker volume COMMAND
  create      Create a volume
  inspect     Display detailed information on one or more volumes
  ls          List volumes
  rm          Remove one or more volumes

network

docker network COMMAND
  connect     Connect a container to a network
  create      Create a network
  disconnect  Disconnect a container from a network
  inspect     Display detailed information on one or more networks
  ls          List networks
  rm          Remove one or more networks

service

docker service COMMAND
  create      Create a new service
  inspect     Display detailed information on one or more services
  ps          List the tasks of a service
  ls          List services
  rm          Remove one or more services
  scale       Scale one or multiple services
  update      Update a service

node

docker node COMMAND
  demote      Demote one or more nodes from manager in the swarm
  inspect     Display detailed information on one or more nodes
  ls          List nodes in the swarm
  promote     Promote one or more nodes to manager in the swarm
  rm          Remove one or more nodes from the swarm
  ps          List tasks running on a node
  update      Update a node

swarm

docker swarm COMMAND
  init        Initialize a swarm
  join        Join a swarm as a node and/or manager
  join-token  Manage join tokens
  update      Update the swarm
  leave       Leave a swarm