目录

Docker 相关命令备忘参考

Docker 相关命令备忘参考,主要关于 Docker CLICompose CLI

版权声明:本文为博主 xwi88 的原创文章,遵循 CC BY-NC 4.0 版权协议,禁止商用,转载请注明出处,欢迎关注 https://github.com/xwi88

  • Docker version: Docker version 20.10.12, build e91ed57
  • Compose version: Docker Compose version 2.2.2

Docker 相关参考资源

文件格式

File formatDescription
DockerfileDefines the contents and startup behavior of a single container
Compose fileDefines a multi-container application

命令行接口 (CLIs)

CLIDescription
Docker CLIThe main CLI for Docker, includes all docker commands
Compose CLIThe CLI, which allows you to build and run multi-container applications
dockerdPersistent process that manages containers

应用程序接口 (APIs)

APIDescription
Engine APIThe main API for Docker, provides programmatic access to a daemon
Registry APIFacilitates distribution of images to the engine
Docker Hub APIAPI to interact with Docker Hub

驱动与规范

DriverDescription
Image specificationDescribes the various components of a Docker image
Registry token authenticationOutlines the Docker registry authentication scheme
Registry storage driversEnables support for given cloud providers when storing images with Registry

Docker CLI 用法

示例
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/Users/wangxin/.docker")
  -c, --context string     Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default context set with "docker context use")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket(s) to connect to
  -l, --log-level string   Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
      --tls                Use TLS; implied by --tlsverify
      --tlscacert string   Trust certs signed only by this CA (default "/Users/wangxin/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/Users/wangxin/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/Users/wangxin/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit

Management Commands:
  builder     Manage builds
  buildx*     Docker Buildx (Docker Inc., v0.7.1)
  compose*    Docker Compose (Docker Inc., 2.2.2)
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  image       Manage images
  manifest    Manage Docker image manifests and manifest lists
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  scan*       Docker Scan (Docker Inc., v0.17.0)
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a Dockerfile
  commit      Create a new image from a container's changes
  cp          Copy files/folders between a container and the local filesystem
  create      Create a new container
  diff        Inspect changes to files or directories on a container's filesystem
  events      Get real time events from the server
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a Docker registry
  logs        Fetch the logs of a container
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  ps          List containers
  pull        Pull an image or a repository from a registry
  push        Push an image or a repository to a registry
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default)
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  tag         Create a tag TARGET_IMAGE that refers to SOURCE_IMAGE
  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
  version     Show the Docker version information
  wait        Block until one or more containers stop, then print their exit codes

Run 'docker COMMAND --help' for more information on a command.

To get more help with docker, check out our guides at https://docs.docker.com/go/guides/

Docker Compose CLI 用法

示例
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
Usage:  docker compose [OPTIONS] COMMAND

Docker Compose

Options:
      --ansi string                Control when to print ANSI control characters ("never"|"always"|"auto") (default "auto")
      --compatibility              Run compose in backward compatibility mode
      --env-file string            Specify an alternate environment file.
  -f, --file stringArray           Compose configuration files
      --profile stringArray        Specify a profile to enable
      --project-directory string   Specify an alternate working directory
                                   (default: the path of the Compose file)
  -p, --project-name string        Project name

Commands:
  build       Build or rebuild services
  convert     Converts the compose file to platform's canonical format
  cp          Copy files/folders between a service container and the local filesystem
  create      Creates containers for a service.
  down        Stop and remove containers, networks
  events      Receive real time events from containers.
  exec        Execute a command in a running container.
  images      List images used by the created containers
  kill        Force stop service containers.
  logs        View output from containers
  ls          List running compose projects
  pause       Pause services
  port        Print the public port for a port binding.
  ps          List containers
  pull        Pull service images
  push        Push service images
  restart     Restart containers
  rm          Removes stopped service containers
  run         Run a one-off command on a service.
  start       Start services
  stop        Stop services
  top         Display the running processes
  unpause     Unpause services
  up          Create and start containers
  version     Show the Docker Compose version information

Run 'docker compose COMMAND --help' for more information on a command.

Docker 命令

Docker 常用管理命令

  • docker context [--help] 上下文管理
  • docker compose [--help] docker compose 命令 v2.2.2+
  • docker container [--help] docker 容器命令
  • docker image [--help] docker 镜像命令
    • docker image prune 删除所有未被 tag 标记和未被容器使用的镜像,标记为 <none>
  • docker volume [--help] 目录挂载命令
  • docker network [--help] docker 网络命令
  • docker system [--help] docker 系统命令
    • docker system df 磁盘使用查看
    • docker system info == docker info Display system-wide information
  • docker scan [--help] docker 镜像扫描分析
  • docker manifest [--help] docker 镜像清单查看,实验特性

Docker 常用命令

  • docker build [--help] 镜像构建
    • docker build [[-t tag] ...] -f [PATH/Dockerfile] .
    • docker build -t tag1 -t tag2 -f [PATH/Dockerfile] . 可同时生成多个 tag 镜像
  • docker commit [OPTIONS] <container> <REPOSITORY[:TAG]> 基于容器创建镜像
  • docker cp 容器与本地文件之间复制
    • docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
    • docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH
  • docker create [OPTIONS] IMAGE [COMMAND] [ARG...] 一般使用 docker run 直接创建并运行
  • docker history = docker image history 镜像历史查看
  • docker images 查看镜像列表
  • docker login
  • docker search
  • docker tag
  • docker pull
  • docker build
  • docker run
  • docker push
  • docker stop
  • docker logs

docker 镜像过滤查找

docker images -f [filter params]

  • dangling=(true|false) none tag images
  • label=<key> or label=<key>=<value> 通过 label 过滤
  • before=(<image-name>[:tag]|<image-id>|<image@digest>)
  • since=(<image-name>[:tag]|<image-id>|<image@digest>)
  • reference=(pattern of an image reference)
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
docker images -f dangling=true
docker images -f label=author
docker images -f label=author=xwi88
docker images -f reference="v8fg/*"
docker images -f reference="v8fg/alpine"
docker images -f reference="v8fg/alpine:*"
docker images -f reference="v8fg/golang:1.18*"
docker images -f reference="v8fg/golang:*1.18*"
docker images -f reference="[REPOSITORY:TAG]"
docker images -f reference="tes*"
docker images -f reference="test"
docker images -f reference="test*2"
警告
测试发现,如果 REPOSITORY 中含有 / 则通过 reference 正则查询时,必须包含 / 否则无法匹配出来,也即 / 无法被 filter 正则匹配

docker commit 基于容器创建镜像

docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

1
2
3
4
5
6
7
8
9
Usage:  docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container's changes

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

prune 镜像容器等一键删除

  • docker image prune -a 删除所有未被容器使用的镜像
  • docker container prune 删除所有停止运行容器
  • docker volume prune 删除所有未被挂载的卷
  • docker system prune 删除 docker 所有资源
  • docker network prune 删除所有网络

Simple Cheat Sheet

  • demo images: v8fg/demo
  • 演示镜像: v8fg/demo[:latest]
  • 演示容器名: v8fg-demo

Running Containers

commandnote
docker run -it v8fg/demo bashRun container and specify command
docker run -it v8fg/demoRun container
docker run -tid v8fg/demoRun container detatched, -tty
docker create -ti v8fg/demoCreate a container without starting it
docker run -tid --name v8fg-demo v8fg/demonamed container
docker psshow running containers
docker ps -ashow all containers
docker ps --filter name=v8fgshow matching containers
docker ps --filter name=demo -qshow matching container ID
docker inspect v8fg-demoinspect container
示例

经上面操作后,部分输出如下

1
2
3
4
5
6
CONTAINER ID   IMAGE       COMMAND     CREATED              STATUS                          PORTS     NAMES
01430cc7b2c0   v8fg/demo   "/bin/sh"   11 seconds ago       Up 11 seconds                             v8fg-demo
83ce7dee0346   v8fg/demo   "/bin/sh"   About a minute ago   Created                                   thirsty_bassi
1bd61cc802f1   v8fg/demo   "/bin/sh"   About a minute ago   Up About a minute                         relaxed_beaver
be104825d061   v8fg/demo   "/bin/sh"   About a minute ago   Exited (0) About a minute ago             flamboyant_beaver
8cfe1c19773f   v8fg/demo   "bash"      About a minute ago   Exited (0) About a minute ago             flamboyant_euclid

Container Lifecycle Stuff

commandnote
docker start v8fg-demostart
docker stop v8fg-demostop
docker stop v8fg-demo relaxed_beaverstop mutliple
docker restart v8fg-demorestart container
docker pause v8fg-demopauses a running container, freeze in place
docker unpause v8fg-demounpause a container
docker wait v8fg-demoblocks until running container stops
docker kill v8fg-demosends SIGKILL, faster than stop
docker rm v8fg-demoremove
docker rm v8fg-demo relaxed_beaverremove multiple
docker rm -f v8fg-demoforce remove
docker container rm -f $(docker ps -aq)Remove all containers, running or stopped

Resource Limits and Controls

commandnote
docker run -tid -c 512 v8fg/demo50% cpu
docker run -tid --cpu-shares 2 v8fg/demoCPU shares (relative weight)
docker run -tid --cpus 2 v8fg/demonumber of CPUs
docker run -tid --cpuset-cpus=0,4,6 v8fg/demouse these cpus
docker run -tid -m 300M v8fg/demolimit memory
docker create -ti --storage-opt size=5G v8fg/demolimit storage, not on aufs
docker run -tid -m 300M --cpus 1 --name v8fg-demo v8fg/demolimit memory

Stats, Logs, and Events

commandnote
docker statsresourse stats for all containers
docker stats v8fg-demoresource stats for one container
docker top v8fg-demoshows processes in a container
docker logs v8fg-democontainer logs
docker eventswatch events in real time
docker port v8fg-demoshows public facing port of container
docker diff v8fg-demoshow changes to a container’s file system

Docker Images

commandnote
docker imagesshow images
docker history v8fg/demoshow history of image
docker image rm v8fg/demoremove image
docker image remove ddd4b27c1c67remove by id
docker image remove v8fg/demoremove image
docker rmi v8fg/demoremove image
docker rmi $(docker images -q)remove all images
Commit container to an image:
docker commit v8fg-demono repo name
docker commit v8fg-demo test1repo name
docker commit v8fg-demo v8fg/test1repo name
docker commit v8fg-demo v8fg/test1:my-updatetagged
docker commit v8fg-demo v8fg/test1:v1.2.3tagged

Export/Import/Save/Load

  • export, import: 不保留层历史信息,较小 制作基础镜像,去除历史
  • save, load: 保留层历史信息,较大
commandnote
docker exportexport container to tarball archive stream
docker importcreate image from tarball, excludes history ( smaller image )
docker savesave image to tar archive stream ( includes parent layers )
docker loadload an image from tarball, includes history ( larger image )
Examples:
docker export v8fg-demo | gzip > v8fg-demo-container-export.tar.gz
cat v8fg-demo-container-export.tar.gz | docker import - v8fg-demo:latest-import
docker save v8fg/demo | gzip > v8fg-demo-image-save.tar.gz
docker load < v8fg-demo-image-save.tar.gz

Docker Hub/Registry

commandnote
docker loginLogin to Registry
docker logoutLogout of Registry
docker tag ddd4b27c1c67 v8fg/demo:local-v1Tag an image
docker push v8fg/demoPush to registry
docker search v8fg
docker search v8fg/golang
docker search golang
docker pull v8fg/demoPull it down, default latest
docker run v8fg/demo:alpineWill be downloaded if it isn`t here

Building Docker Images From A Dockerfile

commandnote
mkdir mydockerbuildCreate build dir
cd mydockerbuildcd into build dir
vi DockerfileEdit build instructions
docker build -t mydockerimage .
docker imagesShow images
docker run mydockerimageRun the new image

Simple Dockerfile Example

v8fg/demo:latest

1
2
3
4
5
ARG FROM_REPOSITORY=alpine FROM_TAG=3.15.1
FROM ${FROM_REPOSITORY}:${FROM_TAG}
LABEL author=xwi88 type=demo name=latest github="https://github.com/xwi88" group="https://github.com/v8fg"
RUN apk add --no-cache tzdata bash
ENV TZ=Asia/Shanghai

v8fg/demo:ubuntu

1
2
3
4
FROM ubuntu
LABEL author=xwi88 type=demo name=ubuntu github="https://github.com/xwi88" group="https://github.com/v8fg"
RUN apt-get update && apt-get install nginx -y && apt-get clean && apt-get autoclean && rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/*
CMD ["/usr/sbin/nginx"]

Big Dockerfile Example

commandnote
FROM ubuntubase image
RUN apt updaterun commands while building
RUN apt install nginx -yrun commands while building
WORKDIR ~/working dir that CMD is run from
ENTRYPOINT echodefault application
CMD “echo” “Hello docker!”main command / default application
CMD ["--port 27017"]params for ENTRYPOINT
CMD “Hello docker!”params for ENTRYPOINT
ENV SERVER_WORKS 4set env variable
EXPOSE 8080expose a port, not published to the host
MAINTAINER authors_namedeprecated
LABEL version=“1.0”add metadata
LABEL author=“User One”add metadata
USER 751UID (or username) to run as
VOLUME ["/my_files"]sets up a volume
COPY test relativeDir/copies “test” to WORKDIR/relativeDir/
COPY test /absoluteDir/copies “test” to /absoluteDir/
COPY ssh_config /etc/ssh/ssh_configcopy over a vile
COPY --chown=user1:group1 files* /data/also changes ownership
ADD /dir1 /dir2like copy but does more …

Volumes/Storage

commandnote
docker infogrep -i storage
docker inspect v8fg-demolook for “Mounts”
docker volume lsshow voluems
docker volume create testvol1create a volume
docker volume inspect testvol1inspect a volume
docker volume ls -f dangling=truefind dangling ( unused ) volumes
docker volume rm volume1remove volume
Running containers with volumes:
docker run -d --name test1 -v /data v8fg/demounamed volume mounted on /data
docker run -d --name test2 -v vol1:/data v8fg/demonamed volume
docker run -d --name test3 -v /src/data:/data v8fg/demobind mount
docker run -d --name test4 -v /src/data:/data:ro v8fg/demoRO
docker run -d --volumes-from test2 --name test5 v8fg/demostorage can be shared
docker rm -v test1remove container and unnamed volume
Access and sharing parameters:
:rofor read only
:zshared all containers can read/write
:Zprivate, unshared
-
`/var/lib/docker/overlay2`Defalt volume storage location on Ubuntu Linux

Expose Ports

commandnote
docker run -tid -p 1234:80 nginxexpose container port 80 on host port 1234
`docker run -tid -p 80:5000 ubuntu`bind port
docker run -tid -p 8000-9000:5000 ubuntubind port to range
`docker run -tid -p 80:5000/udp ubuntu`udp ports
`docker run -tid -p 127.0.0.1:80:5000 ubuntu`bind port on an interface
docker run -tid -p 127.0.0.1::5000 ubuntubind any port, specific interface
docker run -tid -P ubuntuexposed ports to random ports

Networks

commandnote
docker network lsshow networks, bridge is default
docker network inspect bridgeshow network details and connected containers
Create Bridge Network, Specify Subnet and Gateway:
docker network create -d bridge my-network
docker network create -d bridge --subnet 172.25.0.0/16 my-network
docker network create --subnet 203.0.113.0/24 --gateway 203.0.113.254 my-network
docker network rm my-networkremove network
Run container and specify network:
docker run -tid --net=my-network --name test1 ubuntu
Run container, specify network and IP:
docker run -tid --net=my-network --ip=172.25.3.3 --name=test1 ubuntu
Connect container to network:
docker network connect net1 test1
docker network connect net1 test2 --ip 172.25.0.102
Disconnect container from network:
`docker network disconnect net1 test1`Disconnect container from this network
docker network disconnect -f test1 test2Force disconnect
Find container’s IP address:
docker inspect -f '{{json .NetworkSettings.Networks}}' container1
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container1

参考