一篇文章让你搞清楚docker常用命令

众所周知,docker 排查问题相较而言是困难的。因此,熟知一些常用命令对我们快速的排查定位问题是非常有帮助的。下面让我们一起来学习一下吧👇

1、显示docker的系统信息

docker info

[[email protected] docker]# docker info
Client:
 Context:    default
 Debug Mode: false
 Plugins:
  app: Docker App (Docker Inc., v0.9.1-beta3)
  buildx: Build with BuildKit (Docker Inc., v0.6.1-docker)
  scan: Docker Scan (Docker Inc.)

Server:
 Containers: 8
  Running: 5
  Paused: 0
  Stopped: 3
 Images: 16
 Server Version: 20.10.8
 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: io.containerd.runc.v2 io.containerd.runtime.v1.linux runc
 Default Runtime: runc
 Init Binary: docker-init
 containerd version: e25210fe30a0a703442421b0f60afac609f950a3
 runc version: v1.0.1-0-g4144b63
 init version: de40ad0
 Security Options:
  seccomp
   Profile: default
 Kernel Version: 3.10.0-1062.1.2.el7.x86_64
 Operating System: CentOS Linux 7 (Core)
 OSType: linux
 Architecture: x86_64
 CPUs: 1
 Total Memory: 1.795GiB
 Name: xiao
 ID: SR3Y:RSZT:2ZAE:M33P:O2LT:55KN:A3XY:WE7V:QXJY:7Z32:M34L:NX7N
 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://4h8ex9ed.mirror.aliyuncs.com/
 Live Restore Enabled: false

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

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

port  	  # 查看映射端口对应的容器内部源端口
pause	    # 暂停容器
ps        # 容器列表
pull      # 从docker镜像源服务器拉取指定镜像或者库镜像
push      # 推送指定镜像或者库镜像至docker源服务器
restart   # 重启运行的容器
rm        # 移除一个或多个容器
rmi       # 移除一个或多个镜像 (无容器使用该镜像才可删除,否则需要删除相关容器才可继续或 -f 强制删除)
run       # 创建一个新的容器并运行一个命令
save      # 保存一个镜像为一个 tar 包【对应 load】
search    # 在 docker hub 中搜索镜像
start     # 启动容器
stop      # 停止容器
tag       # 给源中镜像打标签
top       # 查看容器中运行的进程信息
unpause   # 取消暂停容器
version   # 查看 docker版本号
wait      # 截取容器停止时的退出状态值
attach    # Attach to a running container  #当前shell下attach连接指定运行镜像
build     # Build an image from a Dockerfile  #通过Dockerfile定制镜像
commit    # Create a new image from a containers changes  #提交当前容器为新的镜像
cp        # Copy files/folders from a container to a HOSTDIR or to STDOUT  #从容器中拷贝指定文件或者目录到宿主机中
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 a running container#在已存在的容器上运行命令
export    # Export a containers filesystem as a tar archive  #导出容器的内容流作为一个tar归档文件(对应import)
history   # Show the history of an image  #展示一个镜像形成历史
inspect   # 查看容器详细信息
kill      # kill 指定的容器

2、镜像命令

docker images

docker images
REPOSITORY            TAG       IMAGE ID       CREATED        SIZE
jenkins/jenkins       latest    ba8a0e5dc5cb   4 months ago   570MB
nginx                 latest    d1a364dc548d   4 months ago   133MB
portainer/portainer   latest    580c0e4e98b0   6 months ago   79.1MB
hello-world           latest    d1165f221234   6 months ago   13.3kB

# 解释
REPOSITORY: 镜像仓库源
TAG: 镜像版本信息
IMAGE ID: 镜像的ID
CREATED: 镜像的创建实际爱你
SIZE: 镜像的大小

可选参数
docker images
	-a : (--all) 列出所有镜像
	-q : (--quiet) 只显示镜像ID

2.1、搜索镜像

docker search [xxx]

docker search mysql

NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   11470     [OK]       
mariadb                           MariaDB Server is a high performing open sou…   4354      [OK]       
mysql/mysql-server                Optimized MySQL Server Docker images. Create…   848                  [OK]
percona                           Percona Server is a fork of the MySQL relati…   555       [OK]       
phpmyadmin                        phpMyAdmin - A web interface for MySQL and M…   332       [OK]       
centos/mysql-57-centos7           MySQL 5.7 SQL database server                   91                    [OK]


docker search mysql --filter=STARS=3000 # 搜索start数大于3000的
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   11470     [OK]       
mariadb   MariaDB Server is a high performing open sou…   4354      [OK]

2.2、拉取镜像

hub 搜索

一篇文章让你搞清楚docker常用命令

docker pull 镜像名[:tag]

# eg
docker pull mysql
Using default tag: latest               # 如果不写tag, 默认就是latest
latest: Pulling from library/mysql
a330b6cecb98: Pull complete 		# 分层下载,docker image 的核心 联合文件系统
9c8f656c32b8: Pull complete 
88e473c3f553: Pull complete 
062463ea5d2f: Pull complete 
daf7e3bdf4b6: Pull complete 
1839c0b7aac9: Pull complete 
cf0a0cfee6d0: Pull complete 
1b42041bb11e: Pull complete 
10459d86c7e6: Pull complete 
b7199599d5f9: Pull complete 
1d6f51e17d45: Pull complete 
50e0789bacad: Pull complete 
Digest: sha256:99e0989e7e3797cfbdb8d51a19d32c8d286dd8862794d01a547651a896bcf00c  # 签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest				# 真实地址

----

docker pull mysql
等价于
docker pull docker.io/library/mysql:latest

---
# 指定tag
docker pull mysql:5.7
5.7: Pulling from library/mysql
a330b6cecb98: Already exists 			# 联合文件系统,已存在的不再重复下载
9c8f656c32b8: Already exists 
88e473c3f553: Already exists 
062463ea5d2f: Already exists 
daf7e3bdf4b6: Already exists 
1839c0b7aac9: Already exists 
cf0a0cfee6d0: Already exists 
fae7a809788c: Pull complete 			# 下载不存在的
dae5a82a61f0: Pull complete 
7063da9569eb: Pull complete 
51a9a9b4ef36: Pull complete 
Digest: sha256:d9b934cdf6826629f8d02ea01f28b2c4ddb1ae27c32664b14867324b3e5e1291
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

---
#查看
docker images
REPOSITORY            TAG       IMAGE ID       CREATED        SIZE
mysql                 5.7       1d7aba917169   3 weeks ago    448MB
mysql                 latest    0716d6ebcc1a   3 weeks ago    514MB
jenkins/jenkins       latest    ba8a0e5dc5cb   4 months ago   570MB
nginx                 latest    d1a364dc548d   4 months ago   133MB
portainer/portainer   latest    580c0e4e98b0   6 months ago   79.1MB
hello-world           latest    d1165f221234   6 months ago   13.3kB

2.3、删除镜像

docker rmi -f [镜像名、镜像ID]

docker rmi -f [镜像名、镜像ID]

docker rmi -f 1d7aba917169
Untagged: mysql:5.7
Untagged: [email protected]:d9b934cdf6826629f8d02ea01f28b2c4ddb1ae27c32664b14867324b3e5e1291
Deleted: sha256:1d7aba9171693947d53f474014821972bf25d72b7d143ce4af4c8d8484623417
Deleted: sha256:94ebbead5c58282fef91cc7d0fb56e4006a72434b4a6ae2cd5be98f369cb8c21
Deleted: sha256:989da5efad29ec59bd536cd393d277bc777f8b9b34b8e3ad9593a4b0a83b40f4
Deleted: sha256:7457ee6817c678da3cb383d27a3d79d5f3f25fbcb92958d5e8d5709e7631e23c
Deleted: sha256:fe7dac53adebe33519b4e4fc577bfcddd7372cc313c35fae681fc82fb325fdc0

3、容器命令

有了镜像才可以创建容器,下载centos镜像进行学习

docker pull centos

3.1、新建容器并启动

docker run [可选参数] imageName/imageId
# 参数说明
--name "NAME"  容器名字,tomcat01, tomcat02, 用来区分容器
-d  后台方式运行
-i  , -t   #使用交互模式运行,可以进入容器查看内容
-p         #指定容器端口 -p 8080   
	   -p ip:主机端口:容器端口  -p 3344:80
	   -p 主机端口:容器端口   (常用)
           -p 容器端口
           容器端口
-P  	   #随机指定端口

3.2、启动容器,并进入容器

[[email protected] ~]# docker run -it centos /bin/bash
[[email protected] /]# ls  #查看容器内的centos
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[[email protected] /]# exit # 退出容器
exit
[[email protected] ~]# 

一篇文章让你搞清楚docker常用命令

CONTAINER ID c4a1504a9cf9

3.3、查看所有运行的容器

docker ps     # 查看运行的容器  exit之后就停止了容器
docker ps -a  # 查看所有运行过的以及在运行的容器

docker ps -a
CONTAINER ID   IMAGE                 COMMAND                  CREATED         STATUS                      PORTS     NAMES
c4a1504a9cf9   centos                "/bin/bash"              7 minutes ago   Exited (0) 3 minutes ago              hungry_euler
dc0c5076048e   hello-world           "/hello"                 2 months ago    Exited (0) 2 months ago               busy_cori


docker ps -a -n=[数字]  # 最近创建的容器
docker ps -a -n=1
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
c4a1504a9cf9   centos    "/bin/bash"   11 minutes ago   Exited (0) 7 minutes ago             hungry_euler

3.4、退出容器

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

3.5、删除容器

docker rm 容器ID                  # 删除指定容器  不能删除正在运行的容器
docker rm -f $(docker ps -aq)     # 递归删除所有容器
docker ps -a -q|xargs docker rm   # 删除所有容器

3.6、启动和停止容器

docker start 容器ID	# 启动容器
docker restart 容器ID 	# 重启容器
docker stop 容器ID      # 停止当前正在运行的容器
docker kill 容器ID      # 强制停止当前容器

4、常用其它命令

4.1、后台运行容器

docker run -d centos
463f1dc43e444ff6b6d0efd3f0c5047e118ddf64deed3aea2a8b5a6c89df61bb
[[email protected] ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[[email protected] ~]#

发现后台运行的容器,停止了

❗ docker使用后台运行,就必须要有一个前台进程。否则,docker发现没有服务,就会自动停止👀

4.2、查看日志

docker logs --help

#shell脚本造日志
docker run -d centos /bin/sh -c "while true;do echo xiao;sleep 1;done"
d5033adf13b49f537430fc19df9fe00b477301dfd3a2d9c287060c65c1a59d7b
[[email protected] ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
d5033adf13b4   centos    "/bin/sh -c 'while t…"   5 seconds ago   Up 4 seconds             competent_jang
[[email protected] ~]# 

#显示日志
docker logs -f -t --tail 10 d5033adf13b4
2021-09-27T07:05:08.800676670Z xiao
2021-09-27T07:05:09.803226803Z xiao
2021-09-27T07:05:10.806019019Z xiao
2021-09-27T07:05:11.809012200Z xiao
2021-09-27T07:05:12.811505073Z xiao
2021-09-27T07:05:13.817109532Z xiao
2021-09-27T07:05:14.819543508Z xiao
2021-09-27T07:05:15.822718210Z xiao
...

-tf                 #显示日志
--tail [数字]	    # 显示日志的条数

4.3、查看容器中的进程信息 (ps - linux)

docker top命令

docker top 容器ID

docker top d5033adf13b4
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                29087               29069               0                   15:01               ?                   00:00:00            /bin/sh -c while true;do echo xiao;sleep 1;done
root                29908               29087               0                   15:08               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
[[email protected] ~]# 

4.4、查看镜像的源数据

dockers inspect 命令

一篇文章让你搞清楚docker常用命令

docker inspect d5033adf13b4
[
    {
        "Id": "d5033adf13b49f537430fc19df9fe00b477301dfd3a2d9c287060c65c1a59d7b",
        "Created": "2021-09-27T07:01:42.833109605Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true;do echo xiao;sleep 1;done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 29087,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-09-27T07:01:43.288158158Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
        "ResolvConfPath": "/var/lib/docker/containers/d5033adf13b49f537430fc19df9fe00b477301dfd3a2d9c287060c65c1a59d7b/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/d5033adf13b49f537430fc19df9fe00b477301dfd3a2d9c287060c65c1a59d7b/hostname",
        "HostsPath": "/var/lib/docker/containers/d5033adf13b49f537430fc19df9fe00b477301dfd3a2d9c287060c65c1a59d7b/hosts",
        "LogPath": "/var/lib/docker/containers/d5033adf13b49f537430fc19df9fe00b477301dfd3a2d9c287060c65c1a59d7b/d5033adf13b49f537430fc19df9fe00b477301dfd3a2d9c287060c65c1a59d7b-json.log",
        "Name": "/competent_jang",
        "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/9aec4e083e254075a863c62c5c54f7ad2d7321750b4384ff1e092e25c5dc257e-init/diff:/var/lib/docker/overlay2/d6e4be0166eac21b08ff7e34bb088bd7488086c5fd04603879424af35f8e6190/diff",
                "MergedDir": "/var/lib/docker/overlay2/9aec4e083e254075a863c62c5c54f7ad2d7321750b4384ff1e092e25c5dc257e/merged",
                "UpperDir": "/var/lib/docker/overlay2/9aec4e083e254075a863c62c5c54f7ad2d7321750b4384ff1e092e25c5dc257e/diff",
                "WorkDir": "/var/lib/docker/overlay2/9aec4e083e254075a863c62c5c54f7ad2d7321750b4384ff1e092e25c5dc257e/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "d5033adf13b4",
            "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 xiao;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": "182c5e5a4f65a8c8ae6fffc733ef2ff02b9c7ea0e374331017cb651077fb77c6",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/182c5e5a4f65",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "7dd5c90916bf7c472a88dc308498f198b59c9606c144c6d413b77ecc03e05cc1",
            "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": "feafa30d4051f24353508959bd420fd163ad0c98d6b30ec8ff13b59a59552bb1",
                    "EndpointID": "7dd5c90916bf7c472a88dc308498f198b59c9606c144c6d413b77ecc03e05cc1",
                    "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
                }
            }
        }
    }
]
[[email protected] ~]#

4.5、进入当前正在运行的容器

4.5.1、docker exec -it 容器ID bashShell (常用)

docker exec -it d5033adf13b4 /bin/bash
[[email protected] /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[[email protected] /]# ps -ef
UID        PID  PPID  C STIME TTY          TIME CMD
root         1     0  0 07:01 ?        00:00:00 /bin/sh -c while true;do echo xiao;sleep 1;done
root      1895     0  0 07:33 pts/0    00:00:00 /bin/bash
root      1937     1  0 07:33 ?        00:00:00 /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1
root      1938  1895  0 07:33 pts/0    00:00:00 ps -ef
[[email protected] /]# 

4.5.2、docker attach 容器ID

docker attach d5033adf13b4
xiao
xiao
xiao
xiao
xiao
...

4.5.3、二者区别

docker exec # 进入容器后,开启一个新的终端,可以在里面操作

docker attach # 进入容器正在执行的终端,不会开启新的进程。

4.6、拷贝容器内文件到主机上

手动同步

docker cp 命令

docker cp 容器ID:容器内路径 目的主机路径

docker cp 2b7529b86ad0:/home/index.txt /home
[[email protected] ~]# ls
life  mysql-community-release-el7-5.noarch.rpm  study  testSH  work
[[email protected] ~]# cd /home/
[[email protected] home]# ls
index.txt  jenkins  test
[[email protected] home]# 

一篇文章让你搞清楚docker常用命令

4.6.1、问题探索

👀如何实现自动同步,打通容器和主机

这个问题下篇讲解😊

4.7、查看cpu内存使用情况

docker stats

每秒刷新

一篇文章让你搞清楚docker常用命令

 

原文地址:https://www.cnblogs.com/all-smile/p/16874416.html