Docker常用命令

帮助命令

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

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

镜像命令

  1. docker images:查看所有本地的主机上的镜像
ubuntu@VM-0-13-ubuntu:/etc/docker$ sudo docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
hello-world   latest    bf756fb1ae65   12 months ago   13.3kB

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

# 可选项
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
  1. docker search:搜索镜像
ubuntu@VM-0-13-ubuntu:/etc/docker$ sudo docker search mysql
NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   10339     [OK]       
mariadb                           MariaDB is a community-developed fork of MyS…   3832      [OK]

## 解释
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


# 可选项,通过收藏来过滤
--filter=STARS=3000 搜索STARS > 3000 以上的
  1. docker pull :下载镜像

解释

ubuntu@VM-0-13-ubuntu:/etc/docker$ docker pull --help

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

例子

ubuntu@VM-0-13-ubuntu:/etc/docker$ docker pull mysql
Using default tag: latest # 默认下载最新的,可以指定版本
Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post http://%2Fvar%2Frun%2Fdocker.sock/v1.24/images/create?fromImage=mysql&tag=latest: dial unix /var/run/docker.sock: connect: permission denied
ubuntu@VM-0-13-ubuntu:/etc/docker$ sudo docker pull mysql
Using default tag: latest
latest: Pulling from library/mysql
6ec7b7d162b2: Pull complete  # 分层下载,docker image的和兴,联合文件系统,如果有共用的,就不会重新下载
fedd960d3481: Pull complete 
7ab947313861: Pull complete 
64f92f19e638: Pull complete 
3e80b17bff96: Pull complete 
014e976799f9: Pull complete 
59ae84fee1b3: Pull complete 
ffe10de703ea: Pull complete 
657af6d90c83: Pull complete 
98bfb480322c: Pull complete 
6aa3859c4789: Pull complete 
1ed875d851ef: Pull complete 
Digest: sha256:78800e6d3f1b230e35275145e657b82c3fb02a27b2d8e76aac2f5e90c1c30873 # 签名
Status: Downloaded newer image for mysql:latest # 真实地址
docker.io/library/mysql:latest


ubuntu@VM-0-13-ubuntu:/etc/docker$ sudo docker pull mysql:5.7 # 带版本号
5.7: Pulling from library/mysql
6ec7b7d162b2: Already exists # 已经下载过,就不会再下载了,联合文件系统
fedd960d3481: Already exists 
7ab947313861: Already exists 
64f92f19e638: Already exists 
3e80b17bff96: Already exists 
014e976799f9: Already exists 
59ae84fee1b3: Already exists 
7d1da2a18e2e: Pull complete 
301a28b700b9: Pull complete 
529dc8dbeaf3: Pull complete 
bc9d021dc13f: Pull complete 
Digest: sha256:c3a567d3e3ad8b05dfce401ed08f0f6bf3f3b64cc17694979d5f2e5d78e10173
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

  1. docker rmi:删除镜像
ubuntu@VM-0-13-ubuntu:/etc/docker$ docker rmi --help 

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

加选项:
docker rmi -f [IMAGE ID]:删除指定镜像
docker rmi -f $(docker images -aq):删除所有镜像(符合命令)

容器命令

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

sudo docker pull centos
  1. 新建容器并启动
docker run [可选参数] image

# 参数说明
--name = 'Name' 容器名字 tomcat01 tomcat02, 用来区分容器
-d              后台方式运行
-it             使用交互方式运行,进入容器查看内容
-p              指定容器的端口 -p 8080:8080 # 主机映射
    -p ip:主机端口:容器端口
    -p 主机端口:容器端口(常用)
    -p 容器端口
    容器端口
-P              随机指定端口


#测试
ubuntu@VM-0-13-ubuntu:~$ sudo docker run -it centos /bin/bash  # 启动centos容器,并进入容器
[root@18c49e246aae /]# 
[root@18c49e246aae /]# ls   # 查看容器内的centos,基础版本,很多命令都不全
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

[root@18c49e246aae /]# exit
exit
  1. 列出所有的运行的容器: docker ps
ubuntu@VM-0-13-ubuntu:~$ sudo docker ps --help

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) # 显示最近创建?个的容器 -n=?
  -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
  1. 退出容器
exit #直接容器体质并退出
Ctrl + P + Q # 容器不停止退出
  1. 删除容器
docker rm [容器id]                  #删除指定的容器,不能删除正在运行的容器,如果要强制删除 rm -f
docker rm -f $(docker ps -eq)       #删除所有容器
docker ps -a -q | xargs docker rm   # 删除所有容器
  1. 启动和停止容器的操作
docker start 容器id     # 启动容器
docker restart 容器id   # 重启容器
docker stop 容器id      # 停止当前正在运行的容器
dockerkill 容器id       # 强行杀掉容器

常用的其他命令

  1. 后台启动容器
# 通过镜像后台启动容器
docker run -d [镜像名]

## 但是docker ps,发现 centos停止了
## 常见的坑,docker 容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会自动停止
## 例如nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了
  1. 查看日志:docker logs

ubuntu@VM-0-13-ubuntu:~$ sudo docker logs --help

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)

测试

sudo docker run -d centos /bin/sh -c "while true; do echo kuangshen; sleep 1; done" # 启动容器,并写shell脚本
sudo docker logs -tf -n 10 ae92a16fcbd8 # 查看10条日志
  1. 查看容器中进程信息:docker top
sudo docker top ae92a16fcbd8
UID                 PID                 PPID                C                   STIME               TTY                 
root                8408                8375                0                   10:20               ?                   
root                9809                8408                0                   10:26               ?                   
  1. 查看镜像元数据
sudo docker inspect --help

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

测试

ubuntu@VM-0-13-ubuntu:~$ sudo docker inspect ae92a16fcbd8
[
    {
        "Id": "ae92a16fcbd849993c739b49eef7323551f84bea88f2edcbab1e1f76e0eaa907",
        "Created": "2021-01-07T02:20:04.460626428Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true; do echo kuangshen; sleep 1; done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 8408,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-01-07T02:20:04.852612913Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:300e315adb2f96afe5f0b2780b87f28ae95231fe3bdd1e16b9ba606307728f55",
        "ResolvConfPath": "/var/lib/docker/containers/ae92a16fcbd849993c739b49eef7323551f84bea88f2edcbab1e1f76e0eaa907/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/ae92a16fcbd849993c739b49eef7323551f84bea88f2edcbab1e1f76e0eaa907/hostname",
        "HostsPath": "/var/lib/docker/containers/ae92a16fcbd849993c739b49eef7323551f84bea88f2edcbab1e1f76e0eaa907/hosts",
        "LogPath": "/var/lib/docker/containers/ae92a16fcbd849993c739b49eef7323551f84bea88f2edcbab1e1f76e0eaa907/ae92a16fcbd849993c739b49eef7323551f84bea88f2edcbab1e1f76e0eaa907-json.log",
        "Name": "/charming_beaver",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "docker-default",
        "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/3faac96cb012a937e367442152d244219d96785315ff4d8b43a7dfd2492432a3-init/diff:/var/lib/docker/overlay2/995eef35515c769ade1ece476c7f0bb5de825b349dde13a1660cbcd003a1b256/diff",
                "MergedDir": "/var/lib/docker/overlay2/3faac96cb012a937e367442152d244219d96785315ff4d8b43a7dfd2492432a3/merged",
                "UpperDir": "/var/lib/docker/overlay2/3faac96cb012a937e367442152d244219d96785315ff4d8b43a7dfd2492432a3/diff",
                "WorkDir": "/var/lib/docker/overlay2/3faac96cb012a937e367442152d244219d96785315ff4d8b43a7dfd2492432a3/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "ae92a16fcbd8",
            "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 kuangshen; sleep 1; done"
            ],
            "Image": "centos",
            "Volumes": null,
            "WorkingDir": "",
            "Entrypoint": null,
            "OnBuild": null,
            "Labels": {
                "org.label-schema.build-date": "20201204",
                "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": "06569ae10ed8e3b4a39d9cadd11d8a1066df344b7a497d3b904ff7647fdd85f5",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/06569ae10ed8",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "c9567b07caa683741109eced165e4a96ebb53e949cfeaca590453564cd4cc66b",
            "Gateway": "172.18.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.18.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:12:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "135647e4cf2e19a323d9e38563f8e512f30519995d5dcbb616824c566fda2430",
                    "EndpointID": "c9567b07caa683741109eced165e4a96ebb53e949cfeaca590453564cd4cc66b",
                    "Gateway": "172.18.0.1",
                    "IPAddress": "172.18.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:12:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
]
  1. 进入当前正在运行的容器
#通常容器都是使用后台方式运行的,需要进入容器,修改一些配置

#命令一:
docker exec -it [容器di] bashshell

##测试:
ubuntu@VM-0-13-ubuntu:~$ clear
ubuntu@VM-0-13-ubuntu:~$ sudo docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
ae92a16fcbd8   centos    "/bin/sh -c 'while t…"   13 minutes ago   Up 13 minutes             charming_beaver
ubuntu@VM-0-13-ubuntu:~$ sudo docker exec -it ae92a16fcbd8 /bin/bash
[root@ae92a16fcbd8 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@ae92a16fcbd8 /]# ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 02:20 ?        00:00:00 /bin/sh -c while true; do echo kuangshen; sleep 1; done
root       858     0  0 02:34 pts/0    00:00:00 /bin/bash
root       877     1  0 02:34 ?        00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
root       878   858  0 02:34 pts/0    00:00:00 ps -ef


#命令二:
docker attach [容器id]

## 详情
sudo docker attach --help

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)


## 测试
sudo docker attach ae92a16fcbd8

# 两种命令的区别
## docker exec: 进入容器后,开启一个行的终端,可以在里面操作(常用)
## docker attach: 进入容器正在执行的终端,不会启动新的终端
  1. 从容器内拷贝文件到主机上
# 命令
docker cp 容器id:容器内路径 目的地主机路径

# 测试
ubuntu@VM-0-13-ubuntu:~$ sudo docker run -it  centos /bin/bash
[root@f63e106f76d2 /]# cd /home
[root@f63e106f76d2 home]# touch test.go
[root@f63e106f76d2 home]# ls
test.go
[root@f63e106f76d2 home]# exit
exit
ubuntu@VM-0-13-ubuntu:~$ sudo docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
ubuntu@VM-0-13-ubuntu:~$ sudo docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS                      PORTS     NAMES
f63e106f76d2   centos    "/bin/bash"   3 minutes ago   Exited (0) 13 seconds ago             competent_thompson
ubuntu@VM-0-13-ubuntu:~$ sudo docker cp f63e106f76d2:/home/test.go /home
ubuntu@VM-0-13-ubuntu:~$ cd /home/
ubuntu@VM-0-13-ubuntu:/home$ ls
test.go  ubuntu
ubuntu@VM-0-13-ubuntu:/home$ 

# 拷贝是一个手动过程,未来我们通过 -v 数据卷的形式,将主机和容器打通

常用命令小结

命令图片大全

attach      Attach to a running container # 当前 shell 下 attach 连接指定运行镜像
build       Build an image from a Dockerfile # 通过 Dockerfile 定制镜像
commit      Create a new image from a container changes # 提交当前容器为新的镜像
cp          Copy files/folders from the containers filesystem to the host path #从容器中拷贝指定文件或者目录到宿主机中
create      Create a new container # 创建一个新的容器,同 run,但不启动容器
diff        Inspect changes on a containers filesystem # 查看 docker 容器变化
events      Get real time events from the server # 从 docker 服务获取容器实时事件
exec        Run a command in an existing container # 在已存在的容器上运行命令
export      Stream the contents of a container as a tar archive # 导出容器的内容流作为一个 tar 归档文件[对应 import ]
history     Show the history of an image # 展示一个镜像形成历史
images      List images # 列出系统当前镜像
import      Create a new filesystem image from the contents of a tarball # 从tar包中的内容创建一个新的文件系统映像[对应export]
info        Display system-wide information # 显示系统相关信息
inspect     Return low-level information on a container # 查看容器详细信息
kill        Kill a running container # kill 指定 docker 容器
load        Load an image from a tar archive # 从一个 tar 包中加载一个镜像[对应 save]
login       Register or Login to the docker registry server # 注册或者登陆一个 docker 源服务器
logout      Log out from a Docker registry server # 从当前 Docker registry 退出
logs        Fetch the logs of a container # 输出当前容器日志信息
port        Lookup the public-facing port which is NAT-ed to PRIVATE_PORT # 查看映射端口对应的容器内部源端口
pause       Pause all processes within a container # 暂停容器
ps          List containers # 列出容器列表
pull        Pull an image or a repository from the docker registry server # 从docker镜像源服务器拉取指定镜像或者库镜像
push        Push an image or a repository to the docker registry server # 推送指定镜像或者库镜像至docker源服务器
restart     Restart a running container # 重启运行的容器
rm          Remove one or more containers # 移除一个或者多个容器
rmi         Remove one or more images # 移除一个或多个镜像[无容器使用该镜像才可删除,否则需删除相关容器才可继续或 -f 强制删除]
run         Run a command in a new container # 创建一个新的容器并运行一个命令
save        Save an image to a tar archive # 保存一个镜像为一个 tar 包[对应 load]
search      Search for an image on the Docker Hub # 在 docker hub 中搜索镜像
start       Start a stopped containers # 启动容器
stop        Stop a running containers # 停止容器
tag         Tag an image into a repository # 给源中镜像打标签
top         Lookup the running processes of a container # 查看容器中运行的进程信息
unpause     Unpause a paused container # 取消暂停容器
version     Show the docker version information # 查看 docker 版本号
posted @ 2021-01-16 16:32  林林星  阅读(136)  评论(0编辑  收藏  举报