零基础学Docker【2】 | 一文带你快速学习Docker常用命令

2021-01-27 16:41:18 浏览数 (1)

前言

本篇是零基础学Docker系列的第二篇文章,在上一篇文章中?一文带你快速了解并上手Docker已经为大家讲解了一些什么是Docker,如何安装使用Docker的内容,以及对Docker与虚拟机技术的一个简单对比做了一些说明。本篇我们将趁热打铁,需要完成的任务如下:

  • 掌握Docker的常用命令,包含但不限于镜像命令,容器命令,以及一些常用的其他命令
  • 学会使用官方文档查找对应的命令说明
  • 学会使用帮助命令来查找对应的命令说明

申明

部分内容来源于网上资源,如若侵犯到您的权益,请联系作者第一时间删除

Docker常用命令

Docker的官方文档非常的详细,关于所有的命令行使用说明/规范,可以参考 https://docs.docker.com/reference/

我们以docker images命令为例,可以发现在官方文档上有非常详细的说明,对于每种命令的介绍说明用法拓展使用参数选项例子…都非常的齐全。

另外我们也可以通过帮助命令在命令行中让我们了解到不同的命令使用。

1、帮助命令

代码语言:javascript复制
docker version    #显示docker的版本信息。
docker info       #显示docker的系统信息,包括镜像和容器的数量
docker 命令 --help #帮助命令

2、镜像命令

代码语言:javascript复制
docker images #查看所有本地主机上的镜像 可以使用docker image ls代替

docker search #搜索镜像

docker pull #下载镜像 docker image pull

docker rmi #删除镜像 docker image rm

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

代码语言:javascript复制
[root@localhost ~]# docker images
REPOSITORY            TAG                 IMAGE ID            CREATED             SIZE
portainer/portainer   latest              62771b0b9b09        3 months ago        79.1MB
hello-world           latest              bf756fb1ae65        10 months ago       13.3kB

# 解释
#REPOSITORY			# 镜像的仓库源
#TAG				# 镜像的标签(版本)		---lastest 表示最新版本
#IMAGE ID			# 镜像的id
#CREATED			# 镜像的创建时间
#SIZE				# 镜像的大小

# 可选项
Options:
  -a, --all         Show all images (default hides intermediate images) #列出所有镜像
  -q, --quiet       Only show numeric IDs # 只显示镜像的id

[root@localhost ~]# docker images -a  #列出所有镜像详细信息
REPOSITORY            TAG                 IMAGE ID            CREATED             SIZE
portainer/portainer   latest              62771b0b9b09        3 months ago        79.1MB
hello-world           latest              bf756fb1ae65        10 months ago       13.3kB

[root@localhost ~]# docker images -aq  #列出所有镜像的id
62771b0b9b09
bf756fb1ae65

docker search 搜索镜像

代码语言:javascript复制
[root@localhost ~]# docker search mysql
NAME                              DESCRIPTION                                     STARS               OFFICIAL            AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   10136               [OK]
mariadb                           MariaDB is a community-developed fork of MyS…   3733                [OK]
mysql/mysql-server                Optimized MySQL Server Docker images. Create…   741                                     [OK]
percona                           Percona Server is a fork of the MySQL relati…   511                 [OK]
centos/mysql-57-centos7           MySQL 5.7 SQL database server                   84
mysql/mysql-cluster               Experimental MySQL Cluster Docker images. Cr…   78
centurylink/mysql                 Image containing mysql. Optimized to be link…   60                                      [OK]
bitnami/mysql                     Bitnami MySQL Docker Image                      46                                      [OK]
deitch/mysql-backup               REPLACED! Please use http://hub.docker.com/r…   41                                      [OK]
tutum/mysql                       Base docker image to run a MySQL database se…   35
prom/mysqld-exporter                                                              31                                      [OK]
databack/mysql-backup             Back up mysql databases to... anywhere!         31
schickling/mysql-backup-s3        Backup MySQL to S3 (supports periodic backup…   29                                      [OK]
linuxserver/mysql                 A Mysql container, brought to you by LinuxSe…   26
centos/mysql-56-centos7           MySQL 5.6 SQL database server                   20
circleci/mysql                    MySQL is a widely used, open-source relation…   19
mysql/mysql-router                MySQL Router provides transparent routing be…   17
arey/mysql-client                 Run a MySQL client from a docker container      15                                      [OK]
fradelg/mysql-cron-backup         MySQL/MariaDB database backup using cron tas…   10                                      [OK]
yloeffler/mysql-backup            This image runs mysqldump to backup data usi…   7                                       [OK]
openshift/mysql-55-centos7        DEPRECATED: A Centos7 based MySQL v5.5 image…   6
devilbox/mysql                    Retagged MySQL, MariaDB and PerconaDB offici…   3
ansibleplaybookbundle/mysql-apb   An APB which deploys RHSCL MySQL                2                                       [OK]
jelastic/mysql                    An image of the MySQL database server mainta…   1
widdpim/mysql-client              Dockerized MySQL Client (5.7) including Curl…   1                                       [OK]


# 可选项,通过搜索来过滤,例如想要实现搜索出来的镜像收藏STARS数量大于3000的
# --filter=STARS=3000 
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


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

docker pull 下载镜像

能够搜索之后,我们就可以去下载镜像。

代码语言:javascript复制
# 下载镜像 docker pull 镜像名[:tag]
[root@localhost ~]# docker pull mysql
Using default tag: latest  #如果不写tag,默认就是latest
latest: Pulling from library/mysql   #分层下载: docker image 的核心 联合文件系统 
bb79b6b2107f: Pull complete
49e22f6fb9f7: Pull complete
842b1255668c: Pull complete
9f48d1f43000: Pull complete
c693f0615bce: Pull complete
8a621b9dbed2: Pull complete
0807d32aef13: Pull complete
a56aca0feb17: Pull complete
de9d45fd0f07: Pull complete
1d68a49161cc: Pull complete
d16d318b774e: Pull complete
49e112c55976: Pull complete
Digest: sha256:8c17271df53ee3b843d6e16d46cff13f22c9c04d6982eb15a9a47bd5c9ac7e2d   # 签名防伪   
Status: Downloaded newer image for mysql:latest
docker.io/library/mysql:latest   #真实地址



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

# 指定版本进行下载
[root@localhost ~]# docker pull mysql:5.7
5.7: Pulling from library/mysql
bb79b6b2107f: Already exists
49e22f6fb9f7: Already exists
842b1255668c: Already exists
9f48d1f43000: Already exists
c693f0615bce: Already exists
8a621b9dbed2: Already exists
0807d32aef13: Already exists
f15d42f48bd9: Pull complete
098ceecc0c8d: Pull complete
b6fead9737bc: Pull complete
351d223d3d76: Pull complete
Digest: sha256:4d2b34e99c14edb99cdd95ddad4d9aa7ea3f2c4405ff0c3509a29dc40bcb10ef
Status: Downloaded newer image for mysql:5.7
docker.io/library/mysql:5.7

可以发现存在共用镜像的时候,docker就不会去重复下载,极大的节省了内存。 等待下载完毕,我们再去查看主机上的docker的镜像文件。

可以发现下载的镜像都比较的大,这个时候我们就可以去考虑删除一些镜像。

docker rmi 删除镜像

代码语言:javascript复制
docker rmi -f 镜像id #删除指定的镜像
docker rmi -f 镜像id 镜像id 镜像id  # 删除多个镜像
docker rmi -f $(docker images -aq)  #  骚操作:删除全部的镜像,递归删除

[root@localhost ~]# docker rmi -f 1b12f2e9257b
Untagged: mysql:5.7
Untagged: mysql@sha256:4d2b34e99c14edb99cdd95ddad4d9aa7ea3f2c4405ff0c3509a29dc40bcb10ef
Deleted: sha256:1b12f2e9257be96da5c075f186dc371b18442b0f9281728ac64c9a69c6e0e264
Deleted: sha256:b21d85dcc43f7db4e532c3ca07e5adbc1e02beb37646b7079217ea2b1922af91
Deleted: sha256:603c9faa831d58a3f60eb377cd6246a281a97b906406a92bf3452726a6f15b69
Deleted: sha256:2d927a6eb4cc26ba5454193a3f4abf503b6cea710293d4f0e6d061c08578b687
Deleted: sha256:b96c2c2176ca7b5223469ad39c9e17509505233dd81030878bc12b03074baef4
...

3、容器命令

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

代码语言:javascript复制
[root@localhost ~]# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
3c72a8ed6814: Pull complete
Digest: sha256:76d24f3ba3317fa945743bb3746fbaf3a0b752f10b10376960de01da70685fbd
Status: Downloaded newer image for centos:latest
docker.io/library/centos:latest

新建容器并启动

代码语言:javascript复制
docker run [可选参数] image 

# 参数说明
--name = “Name”    容器名字 tomcat01   tomcat02,用于区分容器
-d                 后台方式运行
-it                使用交互式运行,进入容器查看内容
-p                 指定容器的端口    -p   8080:8080
		-p ip:主机端口:容器端口
		-p 主机端口:容器端口(常用)
		-p 容器端口
		(不加-p,直接加容器端口也可以)
		
-P(大写) 				随机指定端口

# 测试,启动并进入容器
[root@localhost /]# docker run -it centos /bin/bash
[root@e1ac54cd636a /]# ls      # 查看容器内的centos:基础版本,很多命令都是不完整的!   
bin  etc   lib    lost found  mnt  proc  run   srv  tmp  var
dev  home  lib64  media       opt  root  sbin  sys  usr
# 从容器中退回主机
[root@e1ac54cd636a /]# exit
exit
[root@localhost /]# ls
bin   dev  home  lib64  mnt  proc  run   srv  tmp  var
boot  etc  lib   media  opt  root  sbin  sys  usr

列出所有运行的容器

代码语言:javascript复制
# docker ps 命令   列出当前正在运行的容器
            -a ,--all   #列出当前正在运行的容器   带出历史运行过的容器
            -n=?, --last int   #列出最近创建的?个容器 ?为1则只列出最近创建的一个容器,为2则列出2个
            -q, --quiet    #只列出容器的编号
  


[root@localhost /]# docker ps
CONTAINER ID        IMAGE                 COMMAND             CREATED             STATUS              PORTS                    NAMES
fd5ea781f128        portainer/portainer   "/portainer"        14 hours ago        Up 14 hours         0.0.0.0:8088->9000/tcp   charming_volhard
[root@localhost /]# docker ps -a
CONTAINER ID        IMAGE                 COMMAND             CREATED             STATUS                     PORTS                    NAMES
e1ac54cd636a        centos                "/bin/bash"         5 minutes ago       Exited (0) 4 minutes ago                            epic_engelbart
fd5ea781f128        portainer/portainer   "/portainer"        14 hours ago        Up 14 hours                0.0.0.0:8088->9000/tcp   charming_volhard
ec6397ed87c8        bf756fb1ae65          "/hello"            17 hours ago        Exited (0) 17 hours ago                             ecstatic_mestorf
1db69ebb5c34        bf756fb1ae65          "/hello"            17 hours ago        Exited (0) 17 hours ago                             eager_lamport
a40257529012        bf756fb1ae65          "/hello"            22 hours ago        Exited (0) 22 hours ago                             crazy_greider

退出容器

代码语言:javascript复制
exit      # 容器直接退出
ctrl  P  Q    # 容器不停止退出    -- 注意: 这个是很有用的操作

删除容器

代码语言:javascript复制
docker rm 容器id   				#删除指定的容器,不能删除正在运行的容器,如果要强制删除 rm -rf
docker rm -f $(docker ps -aq)  	 #删除所有的容器
docker ps -a -q|xargs docker rm  #删除所有的容器

启动和停止容器的操作

代码语言:javascript复制
docker start 容器id	#启动容器
docker restart 容器id	#重启容器
docker stop 容器id	#停止当前正在运行的容器
docker kill 容器id	#强制停止当前容器

4、常用的其他命令

后台启动容器

代码语言:javascript复制
# 命令 docker run -d 镜像名
[root@localhost /]# docker run -d centos
c792b680e6250ba7c3892de771a7328baa936518cc35cd47eda0634419228dba
[root@localhost /]# docker ps
CONTAINER ID        IMAGE                 COMMAND             CREATED             STATUS              PORTS                    NAMES
fd5ea781f128        portainer/portainer   "/portainer"        15 hours ago        Up 15 hours         0.0.0.0:8088->9000/tcp   charming_volhard

# 问题:docker ps:发现 centos 停止了
# 常见的坑:docker容器使用后台运行,就必须要有一个前台进程,docker发现没有应用,就会自动停止

查看日志

代码语言:javascript复制
docker logs --help
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:37) or relative (e.g. 42m for 42 minutes)
*      --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:37) or relative (e.g. 42m for 42 minutes)
➜  ~ docker run -d centos /bin/sh -c "while true;do echo 6666;sleep 1;done" #模拟日志      
#显示日志
-tf		#显示日志信息(一直更新)
--tail number #需要显示日志条数
docker logs -t --tail n 容器id # 查看n行日志
docker logs -ft 容器id # 显示所有日志日志


# 运行centos 容器
[root@localhost /]# docker run -it centos /bin/bash
# 查看所有的容器运行情况
[root@localhost /]# docker ps -a
CONTAINER ID        IMAGE                 COMMAND             CREATED             STATUS                        PORTS                    NAMES
529d488fbb4b        centos                "/bin/bash"         50 seconds ago      Up 50 seconds                                          gracious_blackburn
4a0ba742b224        centos                "/bin/bash"         20 minutes ago      Exited (130) 19 minutes ago                            exciting_perlman
c792b680e625        centos                "/bin/bash"         26 minutes ago      Exited (0) 26 minutes ago                              nice_pike

# 根据容器id,查询最近的10条日志
[root@localhost /]# docker logs -f -t --tail 10 529d488fbb4b
#因为我们centos的容器暂时还没有进行任何的操作,所以可能日志显示为空

# 我们可以自己编写一段shell脚本
[root@localhost /]# docker run -d centos /bin/sh -c "while true;do echo 6666;sleep 1;done"
# 再次查看日志
[root@localhost /]# docker logs -f -t --tail 10 492b2410a53f
2020-11-08T05:54:01.436376750Z 6666
2020-11-08T05:54:02.438071320Z 6666
2020-11-08T05:54:03.440787888Z 6666
2020-11-08T05:54:04.443239744Z 6666
...
# 就可以观察到有源源不断的日志产生了

查看容器中进程信息

代码语言:javascript复制
# 命令 docker top 容器id
[root@localhost /]# docker top 9a1f7b30a10a
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                45074               45058               0                   14:03               ?                   00:00:00            /bin/bash

查看镜像的元数据信息

代码语言:javascript复制
# 命令  
docker inspect 容器id
# 测试
[root@localhost /]# docker inspect 9a1f7b30a10a
[
    {
        "Id": "9a1f7b30a10a33a36b7649e8f0992247c7767fccc2d253dfdf7a42b0c4cb1220",
        "Created": "2020-11-08T06:03:48.598473909Z",
        "Path": "/bin/bash",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 45074,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2020-11-08T06:03:48.796392054Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:0d120b6ccaa8c5e149176798b3501d4dd1885f961922497cd0abef155c869566",
        "ResolvConfPath": "/var/lib/docker/containers/9a1f7b30a10a33a36b7649e8f0992247c7767fccc2d253dfdf7a42b0c4cb1220/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/9a1f7b30a10a33a36b7649e8f0992247c7767fccc2d253dfdf7a42b0c4cb1220/hostname",
        "HostsPath": "/var/lib/docker/containers/9a1f7b30a10a33a36b7649e8f0992247c7767fccc2d253dfdf7a42b0c4cb1220/hosts",
        "LogPath": "/var/lib/docker/containers/9a1f7b30a10a33a36b7649e8f0992247c7767fccc2d253dfdf7a42b0c4cb1220/9a1f7b30a10a33a36b7649e8f0992247c7767fccc2d253dfdf7a42b0c4cb1220-json.log",
        "Name": "/jolly_mayer",
        "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,
            "Capabilities": null,
            "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/e9101448258930021351001b2ad30349f485f11800752a56c174cbf7ca0e0057-init/diff:/var/lib/docker/overlay2/2ffe0b620bf852329f5b2c405efb84cd6bbb1abbd75879276b4bed0e1962effc/diff",
                "MergedDir": "/var/lib/docker/overlay2/e9101448258930021351001b2ad30349f485f11800752a56c174cbf7ca0e0057/merged",
                "UpperDir": "/var/lib/docker/overlay2/e9101448258930021351001b2ad30349f485f11800752a56c174cbf7ca0e0057/diff",
                "WorkDir": "/var/lib/docker/overlay2/e9101448258930021351001b2ad30349f485f11800752a56c174cbf7ca0e0057/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "9a1f7b30a10a",
            "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": "20200809",
                "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": "f125e682faaca30a5ff2ea78298b6a63aa4b416de1a4150dc2271de55bb2bec5",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/f125e682faac",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "d49e14b7c195c2bb3d2ccad715cec0410d6b47e81fdec609296ac6ee84a47fb5",
            "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": "97d11e1f759394b549127015587527c5590965c6a66d0b1a5314dcf3b2ba626a",
                    "EndpointID": "d49e14b7c195c2bb3d2ccad715cec0410d6b47e81fdec609296ac6ee84a47fb5",
                    "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
                }
            }
        }
    }
]

进入当前正在运行的容器

代码语言:javascript复制
# 方式一:
docker exec -it 容器id bashshell
# 测试
[root@localhost /]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
9a1f7b30a10a        centos              "/bin/bash"         16 minutes ago      Up 15 minutes                           jolly_mayer
[root@localhost /]# docker exec -it 9a1f7b30a10a /bin/bash
[root@9a1f7b30a10a /]# ps -df
UID         PID   PPID  C STIME TTY          TIME CMD
root         32     19  0 06:19 pts/1    00:00:00 ps -df
[root@9a1f7b30a10a /]# ps -ef
UID         PID   PPID  C STIME TTY          TIME CMD
root          1      0  0 06:03 pts/0    00:00:00 /bin/bash
root         19      0  0 06:18 pts/1    00:00:00 /bin/bash
root         33     19  0 06:19 pts/1    00:00:00 ps -ef

# 方式二:
docker attach 容器id
# 测试
[root@localhost /]# docker attach  9a1f7b30a10a
正在执行代码....


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

从容器内拷贝到主机上 docker cp 容器id:容器内路径 主机目的路径

代码语言:javascript复制
# 进入正在运行的centos容器内部
[root@localhost /]# docker attach 9a1f7b30a10a
# 新建一个文件,并退出结束容器
[root@9a1f7b30a10a /]# touch test.java
[root@9a1f7b30a10a /]# exit
exit
# 查看此时正运行的容器
[root@localhost /]# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             S                       
# 查看所有的容器列表 ,只要容器还在,容器内的数据就丢不了                                                               TATUS              PORTS               NAMES
[root@localhost /]# docker ps -a
CONTAINER ID        IMAGE                 COMMAND                  CREATED                                                                                                    STATUS                           PORTS               NAMES
9a1f7b30a10a        centos                "/bin/bash"              46 minutes ago  
# 执行拷贝命令,将容器中的文件拷贝至本机
[root@localhost /]# docker cp 9a1f7b30a10a:/test.java /home
# 可以在本地查看到从docker容器中拷贝的文件
[root@localhost /]# ls /home
test.java

这里讲的拷贝实际上是一个拷贝的过程,未来我们使用 -v 卷的技术,可以实现,容器内与本地文件的自动同步。

小结

Docker的命令实际上非常多,我们最好整理一份命令行大全,今后需要进行查询的话,就可以从中快速获取。

代码语言:javascript复制
  attach      Attach local standard input, output, and error streams to a running container
  #当前shell下 attach连接指定运行的镜像
  build       Build an image from a Dockerfile # 通过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 to files or directories on a container's filesystem #查看docker容器的变化
  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 #导出容器文件系统作为一个tar归档文件[对应import]
  history     Show the history of an image # 展示一个镜像形成历史
  images      List images #列出系统当前的镜像
  import      Import the contents from a tarball to create a filesystem image #从tar包中导入内容创建一个文件系统镜像
  info        Display system-wide information # 显示系统相关信息
  inspect     Return low-level information on Docker objects #查看容器详细信息
  kill        Kill one or more running containers # kill 指定 docker容器
  load        Load an image from a tar archive or STDIN  # 从一个tar包或标准输入中加载一个镜像[对应save]
  login       Log in to a Docker registry # 注册或者登陆一下 docker 源服务器
  logout      Log out from a Docker registry  # 从当前 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  # 从 docker 镜像源服务器抽取指定镜像或者镜像库
  push        Push an image or a repository to a registry  # 推送指定镜像或者库镜像至docker源服务器
  rename      Rename a container  # 重新命名容器
  restart     Restart one or more containers   # 重启运行的容器
  rm          Remove one or more containers  # 移除一个或者多个容器
  rmi         Remove one or more images  # 移除一个或者多个镜像[无容器使用该镜像才可以删除,否则需删除相关容器才可继续或 -f 强制删除]
  run         Run a command in a new container # 创建一个新的容器并运行一个命令
  save        Save one or more images to a tar archive (streamed to STDOUT by default) # 保存一个镜像为一个 tar包[对应 load]
  search      Search the Docker Hub for images # 在 docker hub 中搜索镜像
  start       Start one or more stopped containers  # 启动容器
  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  # 查看 docker 版本号
  wait        Block until one or more containers stop, then print their exit codes  # 截取容器停止时的退出状态值

彩蛋

有幸收藏过一份尚硅谷周阳老师制作的Docker思维导图,想获取源文件的朋友,可以在公众号【猿人菌】后台回复“Docker思维导图”获取哟~

下期预告

下一篇文章将为大家带来关于在Docker中部署Nginx,Tomcat,ES Kibana 的教程…敬请期待!

一键三连,养成习惯~

文章持续更新,可以微信搜一搜「 猿人菌 」第一时间阅读,思维导图,大数据书籍,大数据高频面试题,海量一线大厂面经…期待您的关注!

0 人点赞