一帮助命令

帮助文档地址:https://docs.docker.com/engine/reference/commandline/docker/

1. docker version 显示docker的版本信息

[root@wangstudy ~]# docker version
Client: Docker Engine - Community
 Version:           19.03.10
 API version:       1.40
 Go version:        go1.13.10
 Git commit:        9424aeaee9
 Built:             Thu May 28 22:18:06 2020
 OS/Arch:           linux/amd64
 Experimental:      false

Server: Docker Engine - Community
 Engine:
  Version:          19.03.10
  API version:      1.40 (minimum version 1.12)
  Go version:       go1.13.10
  Git commit:       9424aeaee9
  Built:            Thu May 28 22:16:43 2020
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.2.13
  GitCommit:        7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc:
  Version:          1.0.0-rc10
  GitCommit:        dc9208a3303feef5b3839f4323d9beb36df0a9dd
 docker-init:
  Version:          0.18.0
  GitCommit:        fec3683

2. docker info 显示docker的系统信息,包括镜像和容器的数量

[root@wangstudy ~]# docker info
Client:
 Debug Mode: false

Server:
 Containers: 1
  Running: 0
  Paused: 0
  Stopped: 1
 Images: 1
 Server Version: 19.03.10
 Storage Driver: overlay2
  Backing Filesystem: extfs
  Supports d_type: true
  Native Overlay Diff: true
 Logging Driver: json-file
 Cgroup Driver: cgroupfs
 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
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: 7ad184331fa3e55e52b890ea95e65ba581ae3429
 runc version: dc9208a3303feef5b3839f4323d9beb36df0a9dd
 init version: fec3683
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 3.10.0-1062.18.1.el7.x86_64
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 2
 Total Memory: 3.7GiB
 Name: wangstudy
 ID: V6LP:LYBG:5CHG:FUKM:J2AJ:VJHR:ADWS:UWUP:EAKM:T2RZ:CC5N:BYRO
 Docker Root Dir: /var/lib/docker
 Debug Mode: false
 Registry: https://index.docker.io/v1/
 Labels:
 Experimental: false
 Insecure Registries:
  127.0.0.0/8
 Registry Mirrors:
  https://01k21qno.mirror.aliyuncs.com/
 Live Restore Enabled: false

 3. docker --help  显示所有命令

[root@wangstudy ~]# 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
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  engine      Manage the docker engine
  image       Manage images
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  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.

二 镜像命令

(1)docker images 查看主机的所有镜像

格式: docker images [选项] [仓库]

显示我们之前下载的hello-world镜像

docker 默认进入home目录 docker-init_docker 默认进入home目录

respository:仓库名

tag:仓库版本

image ID:镜像id

created:创建时间

size:镜像大小 

选项说明:

  • -a 或--all:列出本地所有的镜像(默认情况下,过滤掉中间映像层);
  • --digests :显示镜像的摘要信息;
  • -f或--filter :过滤满足条件的镜像;
     
  • --format :指定返回值的模板文件;
     
  • --no-trunc :显示完整的镜像信息;
     
  • -q 或--quiet:只显示镜像ID。

  

docker 默认进入home目录 docker-init_docker 默认进入home目录_02

 (2)docker search 搜索镜像

格式: docker search [选项] 搜索字

docker 默认进入home目录 docker-init_mysql_03

 选项:

  • --filter,-f 过滤满足条件的镜像,如搜索mysql关键字中stars数量超过3000的镜像

docker 默认进入home目录 docker-init_linux_04

  • --format 指定返回值的模板文件;
  • --limit 指定搜索结果的数量
  • --no-trunc 完整输出

 docker pull 下载镜像

格式: docker pull 镜像名 [版本]

默认版本是最新,dokcer pull mysql等价于docker.io/library/mysql:latest

[root@wangstudy ~]# docker pull mysql
Using default tag: latest
latest: Pulling from library/mysql
afb6ec6fdc1c: Pull complete # 分层下载 docker镜像核心,联合文件系统
0bdc5971ba40: Pull complete 
97ae94a2c729: Pull complete 
f777521d340e: Pull complete 
1393ff7fc871: Pull complete 
a499b89994d9: Pull complete 
7ebe8eefbafe: Pull complete 
597069368ef1: Pull complete 
ce39a5501878: Pull complete 
7d545bca14bf: Pull complete 
211e5bb2ae7b: Pull complete 
5914e537c077: Pull complete 
Digest: sha256:a31a277d8d39450220c722c1302a345c84206e7fd4cdb619e7face046e89031d
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest #真实地址

指定版本,前面下过的可以共用

docker 默认进入home目录 docker-init_docker_05

docker rmi -f [镜像ID]

[root@wangstudy ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mysql               5.7                 a4fdfd462add        11 days ago         448MB
mysql               latest              30f937e841c8        11 days ago         541MB
hello-world         latest              bf756fb1ae65        5 months ago        13.3kB
[root@wangstudy ~]# docker rmi -f 30f937e841c8
Untagged: mysql:latest
Untagged: mysql@sha256:a31a277d8d39450220c722c1302a345c84206e7fd4cdb619e7face046e89031d
Deleted: sha256:30f937e841c82981a9a6363f7f6f35ed6b9d5e3f16df50a72207e4a2a389983f
Deleted: sha256:8a5e032615340d8936e0e3707a39ce3da51dc952368176818f879e2f868b535b
Deleted: sha256:c74673a735ca31b9b5162808ab451a8b20876a15e16a7899f2101f3c9b82df60
Deleted: sha256:430365c8e22a9207dca4638c523dc82163bca3ab8a335a71147af41d1551561f
Deleted: sha256:1ede41b1dbec1a5e4385200b62283ffb25c425275530ea9e9cc36b921186cd08
Deleted: sha256:2f6badb9fd9965261d3463591f8af4afddf5f141456de83dc994690ae64b34eb
[root@wangstudy ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
mysql               5.7                 a4fdfd462add        11 days ago         448MB
hello-world         latest              bf756fb1ae65        5 months ago        13.3kB

删除多个镜像  docker rmi -f ID1 ID2 ID3 ID4

删除所有镜像,因为docker rmi -f $(docker images -aq)命令显示了所有的镜像id。

[root@wangstudy ~]# docker images -aq
a4fdfd462add
bf756fb1ae65
[root@wangstudy ~]# docker rmi -f $(docker images -aq)
Untagged: mysql:5.7
Untagged: mysql@sha256:d16d9ef7a4ecb29efcd1ba46d5a82bda3c28bd18c0f1e3b86ba54816211e1ac4
Deleted: sha256:a4fdfd462add8e63749aa08ff0044b13d342a042965f1ec6744586cda10dfce9
Deleted: sha256:637f0ff7e591e53fe997c634cf10e63ab810dd1d6cb587ce46a57f753c36bdbf
Deleted: sha256:65ba4d5ac7eb5218cfb4be1e7807584425c19f47606bc1e6d53e050d480d9581
Deleted: sha256:7d0236d50948d993a686c69889c6f016a8da89b8557c5e0eaf6af145ea5877cb
Deleted: sha256:a6219b1270405f43892a7a12895ae1e0ccff307d162cf0025df3ed87f511754b
Deleted: sha256:37803884320881cd931c77dea2ee4d8a7231dfed5a02dc595e6046ffacfa6e1b
Deleted: sha256:cefc9066dc1aa84f6cddead1bb5a8c590e8368d56fb65694e8783d70791bec20
Deleted: sha256:3bfbd2dd4507386ce56fd731b3c97d10bc058e6aa478f901466da69108db50e1
Deleted: sha256:9652363dd4c1146b3f9a519800a9f379adf0b6c4f9aece1ffe965dce5f52a8ca
Deleted: sha256:0ed190016efa0f19bcc5f1d66ffffc7b09716f3c57bcc5de74a4ce217af92278
Deleted: sha256:8399fb13d72603fdc8781075672ee25fedf8384f6721639a70dd3533250ed9e4
Deleted: sha256:ffc9b21953f4cd7956cdf532a5db04ff0a2daa7475ad796f1bad58cfbaf77a07
Untagged: hello-world:latest
Untagged: hello-world@sha256:6a65f928fb91fcfbc963f7aa6d57c8eeb426ad9a20c7ee045538ef34847f44f1
Deleted: sha256:bf756fb1ae65adf866bd8c456593cd24beb6a0a061dedf42b26a993176745f6b
[root@wangstudy ~]# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

三 容器命令

先下载centos镜像(docker pull centos),然后新建容器

[root@wangstudy ~]# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
8a29a15cefae: Pull complete 
Digest: sha256:fe8d824220415eed5477b63addf40fb06c3b049404242b31982106ac204f6700
Status: Downloaded newer image for centos:latest
docker.io/library/centos:latest

(1)docker run[选项] 运行容器

  •  --name 取个名字
  • -d  后台运行
  • -it 使用交互方式运行,进入容器查看内容

docker 默认进入home目录 docker-init_mysql_06

  • -p 指定容器端口
  • -P 随机指定端口

 (2) docker ps[选项] 列出所有正在运行的容器

       -a 当前运行和历史运行的容器

       -n=?  显示最近创建的容器

       -q  只显示容器的编号

(3)exit 直接容器停止退出

 Ctrl+P+Q 容器不停止退出

(4)docker rm 容器id 删除容器 ,无法删除正在运行的容器

docker rm -f ${docker ps -aq} 删除所有容器 

docker ps -a -q|xargs docker rm 删除所有的容器

(5)启动和停止容器

docker start 容器id 启动容器

docker restart 容器id 重启容器

docker stop 容器id  停止当前正在运行的容器

docker kill 容器id 强制停止

[root@wangstudy ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
[root@wangstudy ~]# docker ps -a
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS                        PORTS               NAMES
951d75278471        centos              "/bin/bash"         10 minutes ago      Exited (127) 22 seconds ago                       focused_hopper
bedf3815107c        centos              "/bin/bash"         20 minutes ago      Exited (0) 18 minutes ago                         infallible_brattain
b9347895766f        bf756fb1ae65        "/hello"            23 hours ago        Exited (0) 23 hours ago                           nice_murdock
[root@wangstudy ~]# docker start bedf3815107c
bedf3815107c
[root@wangstudy ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
bedf3815107c        centos              "/bin/bash"         20 minutes ago      Up 3 seconds                            infallible_brattain
[root@wangstudy ~]# docker stop bedf3815107c
bedf3815107c
[root@wangstudy ~]# docker pas
docker: 'pas' is not a docker command.
See 'docker --help'
[root@wangstudy ~]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES

四 日志、元数据、进程的查看
1. docker logs  查看日志

    格式: docker logs [选项] 容器Id

  • -f : 跟踪日志输出
  • --since :显示某个开始时间的所有日志
  • -t : 显示时间戳
  • --tail :仅列出最新N条容器日志

  默认我们是没有日志 

docker 默认进入home目录 docker-init_shell_07

 我们自己编写一个shell脚本,如下:

while true;do echo wang;sleep 1;done

运行如下:

docker 默认进入home目录 docker-init_shell_08

日志显示:

docker 默认进入home目录 docker-init_shell_09

  

2.  docker top 查看进行信息

docker 默认进入home目录 docker-init_mysql_10

3. docker inspect 查看容器元数据 

[root@wangstudy ~]# docker inspect 089d44c214ac
[
    {
        "Id": "089d44c214acec91a18f261fd669c55edb31f88533df3a3420b8ac0171ed73c6",
        "Created": "2020-06-01T08:13:49.627625137Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true;do echo wang;sleep 1;done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 17899,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-06-01T08:13:50.078697611Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:470671670cac686c7cf0081e0b37da2e9f4f768ddc5f6a26102ccd1c6954c1ee",
        "ResolvConfPath": "/var/lib/docker/containers/089d44c214acec91a18f261fd669c55edb31f88533df3a3420b8ac0171ed73c6/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/089d44c214acec91a18f261fd669c55edb31f88533df3a3420b8ac0171ed73c6/hostname",
        "HostsPath": "/var/lib/docker/containers/089d44c214acec91a18f261fd669c55edb31f88533df3a3420b8ac0171ed73c6/hosts",
        "LogPath": "/var/lib/docker/containers/089d44c214acec91a18f261fd669c55edb31f88533df3a3420b8ac0171ed73c6/089d44c214acec91a18f261fd669c55edb31f88533df3a3420b8ac0171ed73c6-json.log",
        "Name": "/blissful_agnesi",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "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,
            "Capabilities": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "private",
            "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": [],
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DeviceCgroupRules": null,
            "DeviceRequests": null,
            "KernelMemory": 0,
            "KernelMemoryTCP": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": null,
            "OomKillDisable": false,
            "PidsLimit": null,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0,
            "MaskedPaths": [
                "/proc/asound",
                "/proc/acpi",
                "/proc/kcore",
                "/proc/keys",
                "/proc/latency_stats",
                "/proc/timer_list",
                "/proc/timer_stats",
                "/proc/sched_debug",
                "/proc/scsi",
                "/sys/firmware"
            ],
            "ReadonlyPaths": [
                "/proc/bus",
                "/proc/fs",
                "/proc/irq",
                "/proc/sys",
                "/proc/sysrq-trigger"
            ]
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/9df12c3cbfb53d37af6ea926efdf49a136ee9ccf0c5b35ce4ab7c36513d7b547-init/diff:/var/lib/docker/overlay2/f7c5eda32706d08bc2ac06d975f6acf14dc9f2a2cf4fbfe24b9f27110637b423/diff",
                "MergedDir": "/var/lib/docker/overlay2/9df12c3cbfb53d37af6ea926efdf49a136ee9ccf0c5b35ce4ab7c36513d7b547/merged",
                "UpperDir": "/var/lib/docker/overlay2/9df12c3cbfb53d37af6ea926efdf49a136ee9ccf0c5b35ce4ab7c36513d7b547/diff",
                "WorkDir": "/var/lib/docker/overlay2/9df12c3cbfb53d37af6ea926efdf49a136ee9ccf0c5b35ce4ab7c36513d7b547/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "089d44c214ac",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/sh",
                "-c",
                "while true;do echo wang;sleep 1;done"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20200114",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS",
                "org.opencontainers.image.created": "2020-01-14 00:00:00-08:00",
                "org.opencontainers.image.licenses": "GPL-2.0-only",
                "org.opencontainers.image.title": "CentOS Base Image",
                "org.opencontainers.image.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "eb1d3207aba39468dc75c6913fa9e5c9793d750946cbe7bd4dc73fb15277e04b",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/eb1d3207aba3",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "152c5d0be49b0525295ad4466930696ec248fe28459b9c244c479c24f240bab3",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.3",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:03",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "a2986200147eec90464d8cb789679ad33c2a8b651626fa52fad452d53d3235af",
                    "EndpointID": "152c5d0be49b0525295ad4466930696ec248fe28459b9c244c479c24f240bab3",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.3",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:03",
                    "DriverOpts": null
                }
            }
        }
    }
]

4. 进入容器

1.docker exec -it 容器id /bin/bash 以交互模式运行容器,进入后开启一个新终端

docker 默认进入home目录 docker-init_mysql_11

 

 2. docker attach 容器id 正在执行当前代码,不会开新终端

docker 默认进入home目录 docker-init_shell_12

5. 从容器内拷贝

 docker cp 容器id:容器内路径 目的路径

docker 默认进入home目录 docker-init_docker_13