Docker深入浅出3-容器管理

时间:2021-08-12 07:29:21

docker客户端非常简单,我们可以直接输入docker命令来查看Docker客户端所有的命令项

[root@admin-fxr ~]# docker

Usage:    docker COMMAND

A self-sufficient runtime for containers

Options:
      --config string      Location of client config files (default "/root/.docker")
  -D, --debug              Enable debug mode
      --help               Print usage
  -H, --host list          Daemon socket(s) to connect to (default [])
  -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:
  container   Manage containers
  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
  volume      Manage volumes

Commands:
  attach      Attach 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 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.

可以通过命令docker command --help 更深入的了解指定的Docker命令使用方法。例如我们要查看docker status 指令的具体的使用方法

[root@admin-fxr ~]# docker stats --help

Usage:    docker stats [OPTIONS] [CONTAINER...]

Display a live stream of container(s) resource usage statistics

Options:
  -a, --all             Show all containers (default shows just running)
      --format string   Pretty-print images using a Go template
      --help            Print usage
      --no-stream       Disable streaming stats and only pull the first result
[root@admin-fxr ~]# 

运行WEB容器:

前面我们运行的容器并没有一些什么特殊的用处

接下来我们尝试使用docker构建一个web应用程序。

我们将在docker容器中运行一个java小程序

docker run -d -P training/webapp python app.py

参数说明:

-d:让容器在后台运行

-P:  将容器内部使用的网络端口映射到我们使用的主机上

我们写的java程序打包成一个docker镜像,然后实例化一个容器,就直接可以访问。

查看WEB应用容器的进程

[root@admin-fxr ~]# docker top mysql02
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
polkitd             1965                1951                0                   10:02               ?                   00:01:47            mysqld
root                2142                2128                0                   10:02               pts/1               00:00:00            /bin/bash
root                2189                2142                0                   10:02               pts/1               00:00:00            mysql -uroot -px xxxx
root                2260                2251                0                   10:16               ?                   00:00:00            /bin/bash
root                2308                2298                0                   10:16               pts/0               00:00:00            /bin/bash
[root@admin-fxr ~]# 

查看web应用程序:使用docker inspect 来查看Docker的底层信息,它会返回一个JSON文件记录着Docker容器的配置和状态信息:

[root@admin-fxr ~]# docker inspect mysql02
[
    {
        "Id": "bb8c5376040e126df96ceb7d9ffb254804a5e031366b0601ff820f2374eaba74",
        "Created": "2018-06-11T02:02:01.869077886Z",
        "Path": "docker-entrypoint.sh",
        "Args": [
            "mysqld"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 1965,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2018-06-11T02:02:02.177041787Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:a8a59477268d92f434d86a73b5ea6de9bf7b05d536359413e79da1feb31f87aa",
        "ResolvConfPath": "/var/lib/docker/containers/bb8c5376040e126df96ceb7d9ffb254804a5e031366b0601ff820f2374eaba74/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/bb8c5376040e126df96ceb7d9ffb254804a5e031366b0601ff820f2374eaba74/hostname",
        "HostsPath": "/var/lib/docker/containers/bb8c5376040e126df96ceb7d9ffb254804a5e031366b0601ff820f2374eaba74/hosts",
        "LogPath": "",
        "Name": "/mysql02",
        "RestartCount": 0,
        "Driver": "overlay2",
        "MountLabel": "system_u:object_r:svirt_sandbox_file_t:s0:c129,c382",
        "ProcessLabel": "system_u:system_r:svirt_lxc_net_t:s0:c129,c382",
        "AppArmorProfile": "",
        "ExecIDs": [
            "7e4eec98867d3b1f0fda4936b82c7e0ea7294f31146bf538516e44718e2caa14",
            "336a9b700f39b4186804d46ff020684ecfdb8effa59aa051c99d63e7606c403e",
            "05343506cbf1971a8d1c34d3d749a13830260633ceb9a7202aec4960dc038601"
        ],
        "HostConfig": {
            "Binds": null,
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "journald",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {
                "3306/tcp": [
                    {
                        "HostIp": "",
                        "HostPort": "3306"
                    }
                ]
            },
            "RestartPolicy": {
                "Name": "no",
                "MaximumRetryCount": 0
            },
            "AutoRemove": false,
            "VolumeDriver": "",
            "VolumesFrom": null,
            "CapAdd": null,
            "CapDrop": null,
            "Dns": [],
            "DnsOptions": [],
            "DnsSearch": [],
            "ExtraHosts": null,
            "GroupAdd": null,
            "IpcMode": "",
            "Cgroup": "",
            "Links": null,
            "OomScoreAdj": 0,
            "PidMode": "",
            "Privileged": false,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": null,
            "UTSMode": "",
            "UsernsMode": "",
            "ShmSize": 67108864,
            "Runtime": "docker-runc",
            "ConsoleSize": [
                0,
                0
            ],
            "Isolation": "",
            "CpuShares": 0,
            "Memory": 0,
            "NanoCpus": 0,
            "CgroupParent": "",
            "BlkioWeight": 0,
            "BlkioWeightDevice": null,
            "BlkioDeviceReadBps": null,
            "BlkioDeviceWriteBps": null,
            "BlkioDeviceReadIOps": null,
            "BlkioDeviceWriteIOps": null,
            "CpuPeriod": 0,
            "CpuQuota": 0,
            "CpuRealtimePeriod": 0,
            "CpuRealtimeRuntime": 0,
            "CpusetCpus": "",
            "CpusetMems": "",
            "Devices": [],
            "DiskQuota": 0,
            "KernelMemory": 0,
            "MemoryReservation": 0,
            "MemorySwap": 0,
            "MemorySwappiness": -1,
            "OomKillDisable": false,
            "PidsLimit": 0,
            "Ulimits": null,
            "CpuCount": 0,
            "CpuPercent": 0,
            "IOMaximumIOps": 0,
            "IOMaximumBandwidth": 0
        },
        "GraphDriver": {
            "Name": "overlay2",
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/7a82ad0c45a2abd460e6037ef7bb1c6424bc3bbdd3300ab0653144b3bf32607c-init/diff:/var/lib/docker/overlay2/812c628ee6a3d73b2e5625304e0cf1f5a65082870baaba31f6524ec456feb490/diff:/var/lib/docker/overlay2/91a5fbeb0c686ad843bf7730b1f773f9bd5e4f196f1f502502e082dd510ead27/diff:/var/lib/docker/overlay2/830daa3feafa22688bfb52dd81119d805ebab837ad3cedd7ac5f9d5f793783a1/diff:/var/lib/docker/overlay2/f56a48e5f09e646698d3dbdb689f08eba8dea2f49147934f67b143561918fea9/diff:/var/lib/docker/overlay2/c70b1ea7834fe8157049e8b3f3bf104b57a5c4ead0eb2dbc60149f72438e3ce9/diff:/var/lib/docker/overlay2/82a315246590c8462d5eb47edb56b6849e3c6cdc67b5c9082e0be3bfa34d1bd4/diff:/var/lib/docker/overlay2/74dfa5eaa2c884b217443ba87d7173a53bc287de3ea02e12b2944fd4676c282a/diff:/var/lib/docker/overlay2/707035914ce0c667e4aec7ddbd3e2dba3325d8c8f73344ae6736ee7c9a03c31d/diff:/var/lib/docker/overlay2/ce1b273f2ead7c2f091ad1de6f5401c3c989075c9d5368714bd02f5122e518f6/diff:/var/lib/docker/overlay2/dc78b220d2479289e41af7cf28ec60bc60030cfc5e3d38be5343bdc57828207b/diff:/var/lib/docker/overlay2/423cd24bcc5d2c4025abf3358196394bd36ef1be6943e86c80a4ffda44ac2067/diff:/var/lib/docker/overlay2/25ba916284f3a30bad8a723a0f06428fb7aa49332d2213736c79a2e9afedccdc/diff",
                "MergedDir": "/var/lib/docker/overlay2/7a82ad0c45a2abd460e6037ef7bb1c6424bc3bbdd3300ab0653144b3bf32607c/merged",
                "UpperDir": "/var/lib/docker/overlay2/7a82ad0c45a2abd460e6037ef7bb1c6424bc3bbdd3300ab0653144b3bf32607c/diff",
                "WorkDir": "/var/lib/docker/overlay2/7a82ad0c45a2abd460e6037ef7bb1c6424bc3bbdd3300ab0653144b3bf32607c/work"
            }
        },
        "Mounts": [
            {
                "Type": "volume",
                "Name": "f6c63f01eb4065563842de03418bfe2d10a3645b9674d64d2f19b5bb053d6461",
                "Source": "/var/lib/docker/volumes/f6c63f01eb4065563842de03418bfe2d10a3645b9674d64d2f19b5bb053d6461/_data",
                "Destination": "/var/lib/mysql",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],
        "Config": {
            "Hostname": "bb8c5376040e",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "ExposedPorts": {
                "3306/tcp": {}
            },
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "MYSQL_ROOT_PASSWORD=123456",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin",
                "GOSU_VERSION=1.7",
                "MYSQL_MAJOR=8.0",
                "MYSQL_VERSION=8.0.11-1debian9"
            ],
            "Cmd": [
                "mysqld"
            ],
            "ArgsEscaped": true,
            "Image": "mysql",
            "Volumes": {
                "/var/lib/mysql": {}
            },
            "WorkingDir": "",
            "Entrypoint": [
                "docker-entrypoint.sh"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "08f01088ef9a536008fe9550a44df8e172ce5d86015416d69f207cb41bb51e62",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {
                "3306/tcp": [
                    {
                        "HostIp": "0.0.0.0",
                        "HostPort": "3306"
                    }
                ]
            },
            "SandboxKey": "/var/run/docker/netns/08f01088ef9a",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "c2f5548748c4c88696205230c47b9e4d4cbe466157cf3ded96d0147f6ebd87a8",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "b387fe177a81bb2eb51d29e88da05b122bf8cc5d3d4f877f819208a29d41a0c8",
                    "EndpointID": "c2f5548748c4c88696205230c47b9e4d4cbe466157cf3ded96d0147f6ebd87a8",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02"
                }
            }
        }
    }
]
[root@admin-fxr ~]# 

重启web应用程序:docker restart 容器名称

查询全部的容器:docker ps -a

查询最后一次创建的容器:docker ps -l

移除web应用程序:可以批量移除

docker rm 容器id1 容器id2 容器id3 容器id4 注意:删除容器的时候,容器必须是停止的状态,否则会报错。