Docker命令行介绍

Docker命令行结构
docker + 管理的对象(比如容器,镜像) + 具体操作(比如创建,启动,停止,删除)

示例:

  • docker image pull nginx 拉取一个叫nginx的docker image镜像。

  • docker container stop web 停止一个叫web的docker container容器。

基础命令:

  • docker version 查看版本信息和client/server信息。

    ~# docker version
    Client: Docker Engine - Community
     Cloud integration: v1.0.23
     Version:           20.10.14
     API version:       1.41
     Go version:        go1.16.15
     Git commit:        a224086
     Built:             Thu Mar 24 01:48:21 2022
     OS/Arch:           linux/amd64
     Context:           default
     Experimental:      true
    
    Server: Docker Desktop
     Engine:
      Version:          20.10.14
      API version:      1.41 (minimum version 1.12)
      Go version:       go1.16.15
      Git commit:       87a90dc
      Built:            Thu Mar 24 01:46:14 2022
      OS/Arch:          linux/amd64
      Experimental:     false
     containerd:
      Version:          1.5.11
      GitCommit:        3df54a852345ae127d1fa3092b95168e4a88e2f8
     runc:
      Version:          1.0.3
      GitCommit:        v1.0.3-0-gf46b6ba
     docker-init:
      Version:          0.19.0
      GitCommit:        de40ad0
  • docker info 查看本机容器和镜像相关的信息,比如有多少容器和镜像,正在运行的有多少,停止的有多少等。

    ~# docker info
    Client:
     Context:    default
     Debug Mode: false
     Plugins:
      buildx: Docker Buildx (Docker Inc., v0.8.2)
      compose: Docker Compose (Docker Inc., v2.4.1)
      sbom: View the packaged-based Software Bill Of Materials (SBOM) for an image (Anchore Inc., 0.6.0)
      scan: Docker Scan (Docker Inc., v0.17.0)
    
    Server:
     Containers: 5
      Running: 0
      Paused: 0
      Stopped: 5
     Images: 2
     Server Version: 20.10.14
     Storage Driver: overlay2
      Backing Filesystem: extfs
      Supports d_type: true
      Native Overlay Diff: true
      userxattr: false
     Logging Driver: json-file
     Cgroup Driver: cgroupfs
     Cgroup Version: 1
     Plugins:
      Volume: local
      Network: bridge host ipvlan macvlan null overlay
      Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog
     Swarm: inactive
     Runtimes: runc io.containerd.runc.v2 io.containerd.runtime.v1.linux
     Default Runtime: runc
     Init Binary: docker-init
     containerd version: 3df54a852345ae127d1fa3092b95168e4a88e2f8
     runc version: v1.0.3-0-gf46b6ba
     init version: de40ad0
     Security Options:
      seccomp
       Profile: default
     Kernel Version: 4.19.128-microsoft-standard
     Operating System: Docker Desktop
     OSType: linux
     Architecture: x86_64
     CPUs: 8
     Total Memory: 12.4GiB
     Name: docker-desktop
     ID: 4JD3:ZGZ6:AQSF:6QEF:PYNP:D7I5:RIW7:IO5G:HUGE:ZLRU:6SXH:QSX6
     Docker Root Dir: /var/lib/docker
     Debug Mode: false
     HTTP Proxy: http.docker.internal:3128
     HTTPS Proxy: http.docker.internal:3128
     No Proxy: hubproxy.docker.internal
     Registry: https://index.docker.io/v1/
     Labels:
     Experimental: false
     Insecure Registries:
      hubproxy.docker.internal:5000
      127.0.0.0/8
     Live Restore Enabled: false
    
    WARNING: No blkio throttle.read_bps_device support
    WARNING: No blkio throttle.write_bps_device support
    WARNING: No blkio throttle.read_iops_device support
    WARNING: No blkio throttle.write_iops_device support
    WARNING: bridge-nf-call-iptables is disabled
    WARNING: bridge-nf-call-ip6tables is disabled

镜像 vs 容器

image镜像

  • Docker image是一个 read-only 文件。
  • 这个文件包含文件系统,源码,库文件,依赖,工具等一些运行application所需要的文件。
  • 可以理解成一个模板。
  • Docker image具有分层的概念。

container容器

  • 一个运行中的Docker image。
  • 实质是复制image并在image最上层加上一层 read-write 的层 (称之为 container layer , 容器层)。
  • 基于同一个image可以创建多个container。

Docker image的获取

容器的基本操作

常用命令

操作命令(全)命令(简)
容器的创建docker container run <image name>docker run <image name>
容器的列出(up)docker container lsdocker ps
容器的列出(up和exit)docker container ls -adocker ps -a
容器的停止docker container stop <name or ID>docker stop <container name or ID>
容器的删除docker container rm <name or ID>docker rm <container name or ID>

示例:

$ docker container run nginx
$ docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
343fd4031609   nginx     "/docker-entrypoint.…"   6 seconds ago   Up 5 seconds   80/tcp    xenodochial_clarke
$ docker container ls
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
343fd4031609   nginx     "/docker-entrypoint.…"   14 seconds ago   Up 13 seconds   80/tcp    xenodochial_clarke
$ docker container stop 34
34
$ docker container ls -a
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS     NAMES
343fd4031609   nginx     "/docker-entrypoint.…"   29 seconds ago   Exited (0) 5 seconds ago              xenodochial_clarke
d9095daa8bcf   nginx     "/docker-entrypoint.…"   28 minutes ago   Exited (0) 28 minutes ago             suspicious_shamir
$ docker container rm 34
34
$ docker container ls -a
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                      PORTS     NAMES
d9095daa8bcf   nginx     "/docker-entrypoint.…"   28 minutes ago   Exited (0) 28 minutes ago             suspicious_shamir
$

命令小技巧

批量停止

$ docker container ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
cd3a825fedeb   nginx     "/docker-entrypoint.…"   7 seconds ago    Up 6 seconds    80/tcp    mystifying_leakey
269494fe89fa   nginx     "/docker-entrypoint.…"   9 seconds ago    Up 8 seconds    80/tcp    funny_gauss
34b68af9deef   nginx     "/docker-entrypoint.…"   12 seconds ago   Up 10 seconds   80/tcp    interesting_mahavira
7513949674fc   nginx     "/docker-entrypoint.…"   13 seconds ago   Up 12 seconds   80/tcp    kind_nobel

方法1

$ docker container rm cd3 269 34b 751

方法2

$ docker container stop $(docker container ps -q)
cd3a825fedeb
269494fe89fa
34b68af9deef
7513949674fc
$ docker container ps -a
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS                     PORTS     NAMES
cd3a825fedeb   nginx     "/docker-entrypoint.…"   30 seconds ago   Exited (0) 2 seconds ago             mystifying_leakey
269494fe89fa   nginx     "/docker-entrypoint.…"   32 seconds ago   Exited (0) 2 seconds ago             funny_gauss
34b68af9deef   nginx     "/docker-entrypoint.…"   35 seconds ago   Exited (0) 2 seconds ago             interesting_mahavira
7513949674fc   nginx     "/docker-entrypoint.…"   36 seconds ago   Exited (0) 2 seconds ago             kind_nobel
$

也可以使用docker container ps -q | xargs docker container stop,和上面的操作本质是等效的。

批量删除

和批量停止类似,可以使用 docker container rm $(docker container ps -aq)

docker system prune -a -f 可以快速对系统进行清理,删除停止的容器,不用的image,等等。

docker命令帮助文档

首先是docker --help,用于查看全部的帮忙选项,输出如下:

~# docker --help

Usage:  docker [OPTIONS] COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/root/.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 "/root/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/root/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/root/.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.8.2)
  compose*    Docker Compose (Docker Inc., v2.4.1)
  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
  sbom*       View the packaged-based Software Bill Of Materials (SBOM) for an image (Anchore Inc., 0.6.0)
  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 container --help,如下:

~# docker container --help

Usage:  docker container COMMAND

Manage containers

Commands:
  attach      Attach local standard input, output, and error streams to a running container
  commit      Create a new image from a 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
  exec        Run a command in a running container
  export      Export a container's filesystem as a tar archive
  inspect     Display detailed information on one or more containers
  kill        Kill one or more running containers
  logs        Fetch the logs of a container
  ls          List containers
  pause       Pause all processes within one or more containers
  port        List port mappings or a specific mapping for the container
  prune       Remove all stopped containers
  rename      Rename a container
  restart     Restart one or more containers
  rm          Remove one or more containers
  run         Run a command in a new container
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  stop        Stop one or more running containers
  top         Display the running processes of a container
  unpause     Unpause all processes within one or more containers
  update      Update configuration of one or more containers
  wait        Block until one or more containers stop, then print their exit codes

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

还可以继续查看下一级命令的帮助文档,比如使用docker container run --help查看运行容器的相关选项,如下:

~# docker container run --help

Usage:  docker container 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)
  -a, --attach list                    Attach to STDIN, STDOUT or STDERR
      --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
      --cap-drop list                  Drop Linux capabilities
      --cgroup-parent string           Optional parent cgroup for the container
      --cgroupns string                Cgroup namespace to use (host|private)
                                       'host':    Run the container in the Docker host's cgroup namespace
                                       'private': Run the container in its own private cgroup namespace
                                       '':        Use the cgroup namespace as configured by the
                                                  default-cgroupns-mode option on the daemon (default)
      --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
      --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
      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list
      --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
      --dns-option list                Set DNS options
      --dns-search list                Set custom DNS search domains
      --domainname string              Container NIS domain name
      --entrypoint string              Overwrite the default ENTRYPOINT of the image
  -e, --env list                       Set environment variables
      --env-file list                  Read in a file of environment variables
      --expose list                    Expose a port or a range of ports
      --gpus gpu-request               GPU devices to add to the container ('all' to pass all GPUs)
      --group-add list                 Add additional groups to join
      --health-cmd string              Command to run to check health
      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)
      --health-retries int             Consecutive failures needed to report unhealthy
      --health-start-period duration   Start period for the container to initialize before starting health-retries countdown (ms|s|m|h) (default 0s)
      --health-timeout duration        Maximum time to allow one check to run (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
  -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 mode to use
      --isolation string               Container isolation technology
      --kernel-memory bytes            Kernel memory limit
  -l, --label list                     Set meta data on a container
      --label-file list                Read in a line delimited file of labels
      --link list                      Add link to another container
      --link-local-ip list             Container IPv4/IPv6 link-local addresses
      --log-driver string              Logging driver for the container
      --log-opt list                   Log driver options
      --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)
      --mount mount                    Attach a filesystem mount to the container
      --name string                    Assign a name to the container
      --network network                Connect a container to a network
      --network-alias list             Add network-scoped alias for the container
      --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)
      --platform string                Set platform if server is multi-platform capable
      --privileged                     Give extended privileges to this container
  -p, --publish list                   Publish a container's port(s) to the host
  -P, --publish-all                    Publish all exposed ports to random ports
      --pull string                    Pull image before running ("always"|"missing"|"never") (default "missing")
      --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
      --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
      --sysctl map                     Sysctl options (default map[])
      --tmpfs list                     Mount a tmpfs directory
  -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
      --volume-driver string           Optional volume driver for the container
      --volumes-from list              Mount volumes from the specified container(s)
  -w, --workdir string                 Working directory inside the container

容器运行模式

//TODO attach模式和detach模式。

连接容器的 shell

docker container run -it 创建一个容器并进入交互式模式。

➜  ~ docker container run -it busybox sh
/ #
/ #
/ # ls
bin   dev   etc   home  proc  root  sys   tmp   usr   var
/ # ps
PID   USER     TIME  COMMAND
    1 root      0:00 sh
    8 root      0:00 ps
/ # exit

docker container exec -it 在一个已经运行的容器里执行一个额外的command。

➜  ~ docker container run -d nginx
33d2ee50cfc46b5ee0b290f6ad75d724551be50217f691e68d15722328f11ef6
➜  ~
➜  ~ docker container exec -it 33d sh
#
#
# ls
bin  boot  dev  docker-entrypoint.d  docker-entrypoint.sh  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
#
# exit
➜  ~

容器 vs 虚拟机

容器不是Mini虚拟机

  • 容器其实是进程(Containers are just processes)。
  • 容器中的进程被限制了对CPU内存等资源的访问。
  • 当进程停止后,容器就退出了。

容器的进程process

以下是在Ubuntu20.04中演示,因Windows环境下的Docker和Linux具有一些差异。pstree 命令需要额外安装,可以使用 yum install psmisc 或者 sudo apt-get install psmisc 安装

➜  ~ docker container run -d nginx
57fe4033dd7e1e620a0b6a7b83b85d4f8f98772f0ce585624c384de254826fd0
➜  ~ docker container ls
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
57fe4033dd7e   nginx     "/docker-entrypoint.…"   4 seconds ago   Up 3 seconds   80/tcp    festive_proskuriakova
➜  ~ docker container top 57f
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                7646                7625                0                   12:14               ?                   00:00:00            nginx: master process nginx -g daemon off;
systemd+            7718                7646                0                   12:14               ?                   00:00:00            nginx: worker process
➜  ~
➜  ~
➜  ~  ps -aef --forest
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 May14 ?        00:00:00 /init
root       157     1  0 May14 ?        00:00:00 /init
root       523   157  0 May14 ?        00:02:32  \_ /usr/bin/dockerd -p /var/run/docker.pid
root       545   523  0 May14 ?        00:25:55  |   \_ containerd --config /var/run/docker/containerd/containerd.toml --log-level info
root      7625   157  0 12:14 ?        00:00:00  \_ /usr/bin/containerd-shim-runc-v2 -namespace moby -id 57fe4033dd7e1e620a0b6a7b83b85d4f8f98772f0ce585624c384de254826fd0 -address /var/run/d
root      7646  7625  0 12:14 ?        00:00:00      \_ nginx: master process nginx -g daemon off;
systemd+  7718  7646  0 12:14 ?        00:00:00          \_ nginx: worker process
root      6442     1  0 May18 ?        00:00:00 /init
root      6443  6442  0 May18 ?        00:00:00  \_ /init
penxiao   6444  6443  0 May18 pts/2    00:00:01      \_ -zsh
penxiao   7770  6444  0 12:15 pts/2    00:00:00          \_ ps -aef --forest
➜  ~
➜  ~ pstree -halps 7718
init,1
└─init,157
    └─containerd-shim,7625 -namespace moby -id 57fe4033dd7e1e620a0b6a7b83b85d4f8f98772f0ce585624c384de254826fd0 -address /var/run/docker/containerd/containerd.sock
        └─nginx,7646
            └─nginx,7718

Gain Access to the MobyLinux VM on Windows or MacOS

https://nickjanetakis.com/blog/docker-tip-70-gain-access-to-the-mobylinux-vm-on-windows-or-macos

docker container run 背后发生了什么?

$ docker container run -d --publish 80:80 --name webhost nginx

  1. 在本地查找是否有nginx这个image镜像,但是没有发现
  2. 去远程的image registry查找nginx镜像(默认的registry是Docker Hub)
  3. 下载最新版本的nginx镜像 (nginx:latest 默认)
  4. 基于nginx镜像来创建一个新的容器,并且准备运行
  5. docker engine分配给这个容器一个虚拟IP地址
  6. 在宿主机上打开80端口并把容器的80端口转发到宿主机上
  7. 启动容器,运行指定的命令(这里是一个shell脚本去启动nginx)












  • 无标签