Docker的常用命令

Docker的常用命令

帮助命令

docker version # 显示 docker 的版本信息
docker info # 显示 docker 的系统信息,包括镜像和容器数量
docker 命令 --help

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

镜像命令

docker images 查看所有本地的主机上的镜像

Usage: docker images [OPTIONS] [REPOSITORY[:TAG]]

List images

Options:
  -a, --all             # Show all images (default hides intermediate images)
      --digests         # Show digests
  -f, --filter filter   # Filter output based on conditions provided
      --format string   # Pretty-print images using a Go template
      --no-trunc        # Don't truncate output
  -q, --quiet           # Only show image IDs


[lixun@aliecs ~]$ sudo docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    feb5d9fea6a5   4 months ago   13.3kB

# 解释
REPOSITORY      # 镜像的仓库源
TAG             # 镜像的标签
IMAGE ID        # 镜像的ID
CREATED         # 镜像的创建时间
SIZE            # 镜像的大小

docker search 搜索镜像

Usage:  docker search [OPTIONS] TERM

Search the Docker Hub for images

Options:
  -f, --filter filter   # Filter output based on conditions provided
      --format string   # Pretty-print search using a Go template
      --limit int       # Max number of search results (default 25)
      --no-trunc        # Don't truncate output

[lixun@aliecs ~]$ sudo docker search mysql
NAME             DESCRIPTION                             STARS   OFFICIAL  AUTOMATED
mysql    MySQL is a widely used, open-source relation…   12013     [OK]       
mariadb  MariaDB Server is a high performing open sou…   4603      [OK] 

docker pull 下载镜像

Usage:  docker pull [OPTIONS] NAME[:TAG|@DIGEST]

Pull an image or a repository from a registry

Options:
  -a, --all-tags                # Download all tagged images in the repository
      --disable-content-trust   # Skip image verification (default true)
      --platform string         # Set platform if server is multi-platform capable
  -q, --quiet                   # Suppress verbose output


[lixun@aliecs ~]$ sudo docker pull mysql
Using default tag: latest # 不指定 tag,默认 latest
latest: Pulling from library/mysql
72a69066d2fe: Pull complete # 分层下载,docker images 的核心 联合文件系统
93619dbc5b36: Pull complete 
99da31dd6142: Pull complete 
e5c707858ec0: Pull complete 
fc41578cbf60: Pull complete 
4785d896ef10: Pull complete 
7d250cdc93be: Pull complete 
309700f41983: Pull complete 
45fd33301836: Pull complete 
92f970c68b71: Pull complete 
bb3544339a9e: Pull complete 
f66ddf4c43fa: Pull complete 
Digest: sha256:d0507b008897c39f6cbc76285af1171d4551988475e00e91344060023cd9c553 # 签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest # 真实地址

# 
docker pull mysql ↔ docker pull docker.io/library/mysql:latest

# 指定 tag
[lixun@aliecs ~]$ sudo docker pull mysql:5.7
5.7: Pulling from library/mysql
72a69066d2fe: Already exists 
93619dbc5b36: Already exists 
99da31dd6142: Already exists 
e5c707858ec0: Already exists 
fc41578cbf60: Already exists 
4785d896ef10: Already exists 
7d250cdc93be: Already exists 
2efe6ef3579a: Pull complete 
40dc4a5ca43a: Pull complete 
cd6f90222f59: Pull complete 
031e631e9021: Pull complete 
Digest: sha256:66480693e01295d85954bb5dbe2f41f29ebceb57d3d8098ea0c9d201473f2d8b
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

docker rmi 删除镜像

Usage:  docker rmi [OPTIONS] IMAGE [IMAGE...]

Remove one or more images

Options:
  -f, --force      # Force removal of the image
      --no-prune   # Do not delete untagged parents

[lixun@aliecs ~]$ docker rmi -f 42f82e150ec2 # 删除指定
[lixun@aliecs ~]$ docker rmi -f 42f82e150ec2 feb5d9fea6a5 # 删除多个
[lixun@aliecs ~]$ docker rmi -f $(dcoker images -aq) # 删除所有容器

容器命令

说明: 我们有了镜像才可以创建容器,linux,下载一个 centos 镜像来测试学习。

docker pull centos

新建容器并启动

Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]

Run a command in a new container

Options:
  -d               # Run container in background and print container ID
  -i               # Keep STDIN open even if not attached
  -t               # Allocate a pseudo-TTY
  -p               # Publish a container's port(s) to the host
	  -p ip:主机端口:容器端口
	  -p 主机端口:容器端口(常用)
	  -p 容器端口
	  容器端口
  -P               # Publish all exposed ports to random ports

# 测试,启动并进入容器
[lixun@aliecs ~]$ docker run -it centos /bin/bash
[root@24b0ac2ec11e /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

# 从容器中退出
[root@50ef0c49f5f7 /]# exit
exit
[lixun@aliecs ~]$ 

docker ps 列出运行的容器

Usage:  docker ps [OPTIONS]

List containers

Options:
  -a, --all             # Show all containers (default shows just running)
  -f, --filter filter   # Filter output based on conditions provided
      --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 container IDs
  -s, --size            # Display total file sizes


[lixun@aliecs ~]$ docker ps -a
CONTAINER ID   IMAGE         COMMAND       CREATED              STATUS                      PORTS     NAMES
50ef0c49f5f7   centos        "/bin/bash"   39 seconds ago       Exited (0) 35 seconds ago             sad_goldstine
24b0ac2ec11e   centos        "/bin/bash"   About a minute ago   Exited (0) 51 seconds ago             unruffled_haslett
65b86207336f   hello-world   "/hello"      2 hours ago          Exited (0) 2 hours ago                beautiful_shannon

退出容器

exit # 停止并退出容器
Ctrl + p + q # 不停止退出容器

docker rm 删除容器

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

Remove one or more containers

Options:
  -f, --force     Force the removal of a running container (uses SIGKILL)
  -l, --link      Remove the specified link
  -v, --volumes   Remove anonymous volumes associated with the container

[lixun@aliecs ~]$ docker rm 65b86207336f
65b86207336f
[lixun@aliecs ~]$ docker rm -f $(docker ps -aq)
[lixun@aliecs ~]$ docker ps -a -q|xargs docker rm

docker start/restart/stop/kill 启动和停止容器

# docker start
Usage:  docker start [OPTIONS] CONTAINER [CONTAINER...]

Start one or more stopped containers

Options:
  -a, --attach               # Attach STDOUT/STDERR and forward signals
      --detach-keys string   # Override the key sequence for detaching a container
  -i, --interactive          # Attach container's STDIN

# docker restart
Usage:  docker restart [OPTIONS] CONTAINER [CONTAINER...]

Restart one or more containers

Options:
  -t, --time int   # Seconds to wait for stop before killing the container (default 10)

# docker stop
Usage:  docker stop [OPTIONS] CONTAINER [CONTAINER...]

Stop one or more running containers

Options:
  -t, --time int   

# docker kill
Usage:  docker kill [OPTIONS] CONTAINER [CONTAINER...]

Kill one or more running containers

Options:
  -s, --signal string   Signal to send to the container (default "KILL")

常用其他命令

docker run -d 后台启动

[lixun@aliecs ~]$ docker run -d centos
9a708d24af2008a43362f63b7442d987cda0da670457940b78c6e0c9a4048875
[lixun@aliecs ~]$ docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

# docker 容器使用后台运行,就必须要有一个前台进程,否则,docker 发现没有应用,就会自动停止

docker logs 查看日志

Usage:  docker logs [OPTIONS] CONTAINER

Fetch the logs of a container

Options:
      --details        # Show extra details provided to logs
  -f, --follow         # Follow log output
      --since string   # Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)
  -n, --tail string    # Number of lines to show from the end of the logs (default "all")
  -t, --timestamps     # Show timestamps
      --until string   # Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)

# 显示日志
[lixun@aliecs ~]$ docker logs -tf --tail 10 f8ccaa7fc83e

docker top 查看容器中进程信息

Usage:  docker top CONTAINER [ps OPTIONS]

Display the running processes of a container

[lixun@aliecs ~]$ docker top f8ccaa7fc83e
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                500045              500027              0                   17:22               ?                   00:00:01            /bin/sh -c while true;do echo Jun;sleep 1;done
root                758783              500045              0                   18:22               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1

docker inspect 查看镜像的元数据

Usage:  docker inspect [OPTIONS] NAME|ID [NAME|ID...]

Return low-level information on Docker objects

Options:
  -f, --format string   # Format the output using the given Go template
  -s, --size            # Display total file sizes if the type is container
      --type string     # Return JSON for specified type


[lixun@aliecs ~]$ docker inspect f8ccaa7fc83e
[
    {
        "Id": "f8ccaa7fc83e8a48b31e524caeef650422d8290c2520e871f73c54a0691d2bb7",
        "Created": "2022-01-25T09:22:24.781056836Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true;do echo Jun;sleep 1;done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 500045,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2022-01-25T09:22:25.096385211Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
        "ResolvConfPath": "/var/lib/docker/containers/f8ccaa7fc83e8a48b31e524caeef650422d8290c2520e871f73c54a0691d2bb7/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/f8ccaa7fc83e8a48b31e524caeef650422d8290c2520e871f73c54a0691d2bb7/hostname",
        "HostsPath": "/var/lib/docker/containers/f8ccaa7fc83e8a48b31e524caeef650422d8290c2520e871f73c54a0691d2bb7/hosts",
        "LogPath": "/var/lib/docker/containers/f8ccaa7fc83e8a48b31e524caeef650422d8290c2520e871f73c54a0691d2bb7/f8ccaa7fc83e8a48b31e524caeef650422d8290c2520e871f73c54a0691d2bb7-json.log",
        "Name": "/nostalgic_torvalds",
        "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,
            "CgroupnsMode": "host",
            "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/a15cc0b70321bf767fe8adb6be2b880fa5cd69b69281d44485fd9fda2bb61d54-init/diff:/var/lib/docker/overlay2/54dbc41ae4bb400857b4c12aa5eafd8e0a5eda05f4df63de082c0cfd34893d89/diff",
                "MergedDir": "/var/lib/docker/overlay2/a15cc0b70321bf767fe8adb6be2b880fa5cd69b69281d44485fd9fda2bb61d54/merged",
                "UpperDir": "/var/lib/docker/overlay2/a15cc0b70321bf767fe8adb6be2b880fa5cd69b69281d44485fd9fda2bb61d54/diff",
                "WorkDir": "/var/lib/docker/overlay2/a15cc0b70321bf767fe8adb6be2b880fa5cd69b69281d44485fd9fda2bb61d54/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "f8ccaa7fc83e",
            "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 Jun;sleep 1;done"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20210915",
                "org.label-schema.license": "GPLv2",
                "org.label-schema.name": "CentOS Base Image",
                "org.label-schema.schema-version": "1.0",
                "org.label-schema.vendor": "CentOS"
            }
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "aaf7aa6b37c9a6778f7e5b64d03dccdfc58d42ba99f30897497f1567fb1c8dc8",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/aaf7aa6b37c9",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "28c9c439cedd1e8248fc50470cbcfdfcb26418793ea9efb193cae82405593950",
            "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": "043a32cc1ae4d903bf1f54d1ab41d85e32cf1fb483167eff2754290443e33c7f",
                    "EndpointID": "28c9c439cedd1e8248fc50470cbcfdfcb26418793ea9efb193cae82405593950",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]

docker exec/attach

docker exec 进入当前正在运行的容器

Usage:  docker exec [OPTIONS] CONTAINER COMMAND [ARG...]

Run a command in a running container

Options:
  -d, --detach               # Detached mode: run command in the background
      --detach-keys string   # Override the key sequence for detaching a container
  -e, --env list             # Set environment variables
      --env-file list        # Read in a file of environment variables
  -i, --interactive          # Keep STDIN open even if not attached
      --privileged           # Give extended privileges to the command
  -t, --tty                  # Allocate a pseudo-TTY
  -u, --user string          # Username or UID (format: <name|uid>[:<group|gid>])
  -w, --workdir string       # Working directory inside the container

# 
[lixun@aliecs ~]$ docker exec -it f8ccaa7fc83e /bin/bash
[root@f8ccaa7fc83e /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

docker attach 进入当前正在运行的容器

Usage:  docker attach [OPTIONS] CONTAINER

Attach local standard input, output, and error streams to a running container

Options:
      --detach-keys string   # Override the key sequence for detaching a container
      --no-stdin             # Do not attach STDIN
      --sig-proxy            # Proxy all received signals to the process (default true)

[lixun@aliecs ~]$ docker attach f8ccaa7fc83e
Jun
Jun
Jun

区别:

  • docker exec:进入容器后开启一个新的终端,可以在里面操作(常用)
  • docker attach:进入容器正在执行的终端,不会启动新的进程!

docker cp 从容器拷贝文件到主机上

[lixun@aliecs ~]$ docker cp --help

Usage:  docker cp [OPTIONS] CONTAINER:SRC_PATH DEST_PATH|-
        docker cp [OPTIONS] SRC_PATH|- CONTAINER:DEST_PATH

Copy files/folders between a container and the local filesystem

Use '-' as the source to read a tar archive from stdin
and extract it to a directory destination in a container.
Use '-' as the destination to stream a tar archive of a
container source to stdout.

Options:
  -a, --archive       Archive mode (copy all uid/gid information)
  -L, --follow-link   Always follow symbol link in SRC_PATH

[lixun@aliecs ~]$ docker attach e4d622db3323
[root@e4d622db3323 /]# ls 
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@e4d622db3323 /]# cd home
[root@e4d622db3323 home]# touch cp.java
[root@e4d622db3323 home]# exit
exit
[lixun@aliecs ~]$ docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[lixun@aliecs ~]$ docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                         PORTS     NAMES
e4d622db3323   centos    "/bin/bash"   2 minutes ago   Exited (0) 5 seconds ago                 magical_lalande
[lixun@aliecs ~]$ docker cp e4d622db3323:/home/cp.java /home/lixun/
[lixun@aliecs ~]$ ls
cp.java

# 拷贝是一个手动过程,未来我们使用 -v 卷的技术,可以实现同步

小结

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