Docker的常用命令

2021/5/21 18:56:36

本文主要是介绍Docker的常用命令,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!


title: Docker的常用命令
categories:
- Docker
tags:
- Docker
- java后端

帮助命令

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

帮助文档地址:

https://docs.docker.com/reference/

image-20210521091351213

镜像命令

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

[root@ajie ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    d1165f221234   2 months ago   13.3kB

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

# 可选项
  -a, --all             # 显示所有的镜像
  -q, --quiet           # 只显示镜像id

docker search 搜索镜像

[root@ajie ~]# docker search mysql
NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   10899     [OK]       
mariadb                           MariaDB Server is a high performing open sou…   4113      [OK]       
mysql/mysql-server                Optimized MySQL Server Docker images. Create…   809                  [OK]

# 可选项 通过收藏进行过滤
--filter=STARS=3000 # 搜索收藏数大于3000的镜像

[root@ajie ~]# docker search mysql --filter=STARS=3000
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   10899     [OK]       
mariadb   MariaDB Server is a high performing open sou…   4113      [OK]   

[root@ajie ~]# docker search mysql --filter=STARS=5000
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   10899     [OK] 

docker pull 下载镜像

# 下载镜像 docker pull 镜像名[:tag]
[root@ajie ~]# docker pull mysql
Using default tag: latest				# 如果不写tag,默认下载最新版本
latest: Pulling from library/mysql
69692152171a: Pull complete 			# 分层下载,docker image的核心,联合文件系统
1651b0be3df3: Pull complete 
951da7386bc8: Pull complete 
0f86c95aa242: Pull complete 
37ba2d8bd4fe: Pull complete 
6d278bb05e94: Pull complete 
497efbd93a3e: Pull complete 
f7fddf10c2c2: Pull complete 
16415d159dfb: Pull complete 
0e530ffc6b73: Pull complete 
b0a4a1a77178: Pull complete 
cd90f92aa9ef: Pull complete 
Digest: sha256:d50098d7fcb25b1fcb24e2d3247cae3fc55815d64fec640dc395840f8fa80969	# 签名
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest			# 真实地址

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

# 指定版本下载
[root@ajie ~]# docker pull mysql:5.7
5.7: Pulling from library/mysql
69692152171a: Already exists 
1651b0be3df3: Already exists 
951da7386bc8: Already exists 
0f86c95aa242: Already exists 
37ba2d8bd4fe: Already exists 
6d278bb05e94: Already exists 
497efbd93a3e: Already exists 
a023ae82eef5: Pull complete 
e76c35f20ee7: Pull complete 
e887524d2ef9: Pull complete 
ccb65627e1c3: Pull complete 
Digest: sha256:a682e3c78fc5bd941e9db080b4796c75f69a28a8cad65677c23f7a9f18ba21fa
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

image-20210521160116025

docker rmi 删除镜像

[root@ajie ~]# docker rmi -f 镜像id # 删除指定镜像
[root@ajie ~]# docker rmi -f 镜像id 镜像id 镜像id # 删除多个镜像
[root@ajie ~]# docker rmi -f $(docker images -aq) # 删除所有镜像

容器命令

说明:我们有了镜像才可以创建容器。这里我们用centos进行测试学习

[root@ajie ~]# docker pull centos

新建容器并启动

docker run [可选命令] image

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

# 测试,启动并进入容器。
[root@ajie ~]# docker run -it centos /bin/bash
[root@388006971c36 /]# ls #此centos系统只是基础版本,命令并不齐全
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
# 退出容器
[root@388006971c36 /]# exit
exit
[root@ajie ~]# 

列出所有运行的容器

# docker ps [可选项]
		# 列出正在运行的容器
-a 		# 列出所有的容器(正在运行的以及历史运行过的)
-q		# 只列出容器id
-n=?	# 列出容器的数量

[root@ajie ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@ajie ~]# docker ps -a
CONTAINER ID   IMAGE          COMMAND       CREATED          STATUS                     PORTS     NAMES
388006971c36   centos         "/bin/bash"   10 minutes ago   Exited (0) 7 minutes ago             crazy_williams
3e52986bee16   d1165f221234   "/hello"      31 hours ago     Exited (0) 31 hours ago              lucid_elbakyan
[root@ajie ~]# docker ps -aq
388006971c36
3e52986bee16
[root@ajie ~]# docker ps -a -n=1
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
388006971c36   centos    "/bin/bash"   10 minutes ago   Exited (0) 7 minutes ago             crazy_williams
[root@ajie ~]# 

退出容器

exit	# 关闭容器并退出
Ctrl+P+Q # 容器不停止退出

删除容器

docker rm 容器id   # 删除指定容器,但是不能删除正在运行的容器,如果想要强制删除,可以使用 rm -f
docker rm -f $(docker ps -aq) # 删除所有容器(包括正在运行的和历史运行的)
docker ps -a -q|xargs docker rm # 删除所有容器(包括正在运行的和历史运行的)

启动和停止容器的操作

docker start 容器id		# 启动容器
docker restart 容器id		# 重启容器
docker stop 容器id		# 停止容器
docker kill 容器id		# 杀掉容器

其它常用命令

后台启动容器

# docker run -d 镜像名
[root@ajie ~]# docker run -d centos
e8ff8594570e2a526d00d7b41aaeffe9c40f3d9dfe5acd67e0282b42aab19151
[root@ajie ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

# 注意:docker ps 发现centos停止了

# 常见的坑:docker容器使用后台运行,就必需要有一个前台进程,docker发现没有应用,就会停止。

查看日志

docker logs [可选项] 容器id
-tf  # 显示所有日志消息
--tail number # 显示指定数量的日志

查看容器中进程信息

# docker top 容器id
[root@ajie ~]# docker top ca466d96f4b8
UID                 PID                 PPID                C                   STIME       
14942               14902               0                   17:34               pts/0     

查看容器的元数据

# docker inspect 容器id
[root@ajie ~]# docker inspect ca466d96f4b8
[
    {
        "Id": "ca466d96f4b8123fa40f6986a09be4aef595ed9c22a09e947c487889cbe324c8",
        "Created": "2021-05-21T09:17:28.414401291Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 14942,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-05-21T09:34:06.409496884Z",
            "FinishedAt": "2021-05-21T09:18:58.885488586Z"
        },
        "Image": "sha256:300e315adb2f96afe5f0b2780b87f28ae95231fe3bdd1e16b9ba606307728f55",
        "ResolvConfPath": "/var/lib/docker/containers/ca466d96f4b8123fa40f6986a09be4aef595ed9c22a09e947c487889cbe324c8/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/ca466d96f4b8123fa40f6986a09be4aef595ed9c22a09e947c487889cbe324c8/hostname",
        "HostsPath": "/var/lib/docker/containers/ca466d96f4b8123fa40f6986a09be4aef595ed9c22a09e947c487889cbe324c8/hosts",
        "LogPath": "/var/lib/docker/containers/ca466d96f4b8123fa40f6986a09be4aef595ed9c22a09e947c487889cbe324c8/ca466d96f4b8123fa40f6986a09be4aef595ed9c22a09e947c487889cbe324c8-json.log",
        "Name": "/loving_lichterman",
        "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/b773a1f931de4e32278f7feeb4517c4f54ef0ea3aa3404d1356d114ebd7b6f7b-init/diff:/var/lib/docker/overlay2/a2a92e74d6dc1cce01a2fa500af1341d791784b70c5f1cb9a35f4ed518b6bb3c/diff",
                "MergedDir": "/var/lib/docker/overlay2/b773a1f931de4e32278f7feeb4517c4f54ef0ea3aa3404d1356d114ebd7b6f7b/merged",
                "UpperDir": "/var/lib/docker/overlay2/b773a1f931de4e32278f7feeb4517c4f54ef0ea3aa3404d1356d114ebd7b6f7b/diff",
                "WorkDir": "/var/lib/docker/overlay2/b773a1f931de4e32278f7feeb4517c4f54ef0ea3aa3404d1356d114ebd7b6f7b/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "ca466d96f4b8",
            "Domainname": "",
            "User": "",
            "AttachStdin": true,
            "AttachStdout": true,
            "AttachStderr": true,
            "Tty": true,
            "OpenStdin": true,
            "StdinOnce": true,
            "Env": [
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": [
                "/bin/bash"
            ],
            "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": "c16694e13fcc769d7f495a2a2ae87aa1b6e7c18ead74258775d622bfad2636bd",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/c16694e13fcc",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "2cd25fd033a7eb383ccfebee7b89ff218afef9bd0ae50ecf6417cec8973e3d86",
            "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": "53f0fc57d3a5f93a19c25a379c0ad76cdf24c047ef7c14118321660d67c9a9cb",
                    "EndpointID": "2cd25fd033a7eb383ccfebee7b89ff218afef9bd0ae50ecf6417cec8973e3d86",
                    "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 -it 容器id /bin/bash
# 测试
[root@ajie ~]# docker exec -it ca466d96f4b8 /bin/bash
[root@ca466d96f4b8 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@ca466d96f4b8 /]# 

# 方式二
docker attach 容器id
# 测试
[root@ajie ~]# docker attach ca466d96f4b8
正在运行的代码...

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

从容器内拷贝文件到主机上

# docker cp 容器id:.../.../文件名称 /.../.../目录名称

# 启动并进入容器
[root@ajie ~]# docker run -it centos /bin/bash
[root@4d7c236c7637 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@4d7c236c7637 /]# cd home
# 查看家目录下的文件
[root@4d7c236c7637 home]# ls
# 在家目录下创建一个新文件
[root@4d7c236c7637 home]# touch test.java
[root@4d7c236c7637 home]# ls
test.java
[root@4d7c236c7637 home]# exit
exit
[root@ajie ~]# docker ps -a
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS                     PORTS     NAMES
4d7c236c7637   centos    "/bin/bash"   30 seconds ago   Exited (0) 5 seconds ago             kind_kapitsa
# 进入主机中的家目录
[root@ajie ~]# cd /home
# 查看主机中家目录下的文件
[root@ajie home]# ls
git  hilde  www
# 把刚才创建的问价复制到主机中
[root@ajie home]# docker cp 4d7c236c7637:home/test.java /home
[root@ajie home]# ls
git  hilde  test.java  www

# 注意:文件拷贝和容器运不运行没有关系,只要容器存在,资源就一直存在着

xit
[root@ajie ~]# docker ps -a
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
4d7c236c7637 centos “/bin/bash” 30 seconds ago Exited (0) 5 seconds ago kind_kapitsa

进入主机中的家目录

[root@ajie ~]# cd /home

查看主机中家目录下的文件

[root@ajie home]# ls
git hilde www

把刚才创建的问价复制到主机中

[root@ajie home]# docker cp 4d7c236c7637:home/test.java /home
[root@ajie home]# ls
git hilde test.java www

注意:文件拷贝和容器运不运行没有关系,只要容器存在,资源就一直存在着


                   

这篇关于Docker的常用命令的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程