Docker之常用的基本命令

该笔记大部分搬运B站狂神说Java的Docker,顺便把图文合并记录,便于回顾,仅用于学习!
视频地址:https://www.bilibili.com/video/BV1og4y1q7M4 作者真的非常好,别白嫖,记得三连
如有侵权,请联系删除!

1. 帮助命令

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

Docker官网命令查询:https://docs.docker.com/reference/

2. 镜像命令

2.1 docker images

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

[root@localhost ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    d1165f221234   5 months ago   13.3kB
# 解释
#REPOSITORY			# 镜像的仓库源
#TAG				# 镜像的标签
#IMAGE ID			# 镜像的id
#CREATED			# 镜像的创建时间
#SIZE				# 镜像的大小
# 可选项
Options:
  -a, --all             Show all images (default hides intermediate images) #列出所有镜像
  -q, --quiet           Only show numeric IDs # 只显示镜像的id

2.2 docker search

docker search : 搜索镜像

[root@localhost ~]# docker search mysql --filter=STARS=3000
NAME      DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql     MySQL is a widely used, open-source relation…   11342     [OK]       
mariadb   MariaDB Server is a high performing open sou…   4309      [OK]
# --filter=STARS=3000 #搜索出来的镜像就是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

2.3 docker pull

docker pull:下载镜像

# 下载镜像 docker pull 镜像名[:tag]
[root@localhost ~]# docker pull mysql:8 #如果不写tag,默认就是latest
8: Pulling from library/mysql 					#分层下载: docker image 的核心 联合文件系统
e1acddbe380c: Pull complete 
bed879327370: Pull complete 
03285f80bafd: Pull complete 
ccc17412a00a: Pull complete 
1f556ecc09d1: Pull complete 
adc5528e468d: Pull complete 
1afc286d5d53: Pull complete 
6c724a59adff: Pull complete 
0f2345f8b0a3: Pull complete 
c8461a25b23b: Pull complete 
3adb49279bed: Pull complete 
77f22cd6c363: Pull complete 
Digest: sha256:d45561a65aba6edac77be36e0a53f0c1fba67b951cb728348522b671ad63f926 			# 签名 防伪
Status: Downloaded newer image for mysql:8																						# 真实地址
docker.io/library/mysql:8

#等价于
docker pull tomcat:8
docker pull docker.io/library/tomcat:8

2.4 docker rmi

docker rmi:删除镜像

docker rmi -f 镜像id #删除指定的镜像
docker rmi -f 镜像id 镜像id 镜像id 镜像id#删除指定的镜像
docker rmi -f $(docker images -aq) #删除全部的镜像

3. 容器命令

3.1 docker run

docker run 镜像id:新建容器并启动
说明:我们有了镜像才可以创建容器, linux,下载-个centos镜像来测试学习

docker pull centos

新建容器并启动

docker run [可选参数] image | docker container run [可选参数] image 

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

# 测试、启动并进入容器
[root@localhost ~]# docker run -d centos     #后台方式运行(不进入容器)
89885296c07ba7fb3a2b50103d59382eb8c8bab4d658ad3cbcc1df3b114f605e

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

3.2 docker ps

docker ps: 列出所有运行的容器

docker ps: 列出所有运行的容器
# 可选参数
-a                     #列出当前正在运行的容器+带出历史运行过的容器
-n=?                #显示最近创建的容器
-q                    #只显示容器的编号


[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@localhost ~]# docker ps -a   # 查看曾经运行的容器
CONTAINER ID   IMAGE          COMMAND       CREATED          STATUS                      PORTS     NAMES
05b66c345133   centos         "/bin/bash"   7 minutes ago    Exited (0) 3 minutes ago              gifted_wright
2da121d8e562   d1165f221234   "/hello"      43 minutes ago   Exited (0) 43 minutes ago             hopeful_galois
00615e7dbd5c   d1165f221234   "/hello"      16 hours ago     Exited (0) 16 hours ago               loving_hypatia

3.3 exit

退出容器

exit #容器直接退出
ctrl +P +Q #容器不停止退出


#举例
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@localhost ~]# docker run -it centos /bin/bash
[root@bc5dc85d1fcd /]# [root@localhost ~]# 
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
bc5dc85d1fcd   centos    "/bin/bash"   27 seconds ago   Up 25 seconds             brave_lovelace

3.4 docker rm

删除容器

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

3.5 docker start/restart/stop/kill

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

4. 其他命令

4.1 后台启动命令

# 命令 docker run -d 镜像名
[root@localhost ~]# docker run -d centos
89885296c07ba7fb3a2b50103d59382eb8c8bab4d658ad3cbcc1df3b114f605e
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
# 问题docker ps. 发现centos 停止了
# 常见的坑,docker容器使用后台运行,就必须要有要一个前台进程,docker发现没有应用,就会自动停止
# nginx,容器启动后,发现自己没有提供服务,就会立刻停止,就是没有程序了

4.2 查看日志

docker logs  # 查看日志
#显示日志
-tf		#显示日志信息(一直更新)
--tail number #需要显示日志条数
docker logs -t --tail n 容器id #查看n行日志
docker logs -ft 容器id #跟着日志

# 举例
[root@localhost ~]# docker run -it centos /bin/bash
[root@46b8ac7084b2 /]# 
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
46b8ac7084b2   centos    "/bin/bash"   12 seconds ago   Up 10 seconds             zen_ramanujan

[root@localhost ~]# docker run -d centos /bin/sh -c "while true;do echo 6666;sleep 1;done" #模拟日志   
[root@localhost ~]# docker logs -ft --tail 10 07aaf797bf5d
2021-08-31T03:07:26.977417235Z 6666
2021-08-31T03:07:27.981823922Z 6666
2021-08-31T03:07:28.991611562Z 6666
2021-08-31T03:07:30.003223007Z 6666
2021-08-31T03:07:31.005337520Z 6666
2021-08-31T03:07:32.008703388Z 6666
2021-08-31T03:07:33.012560130Z 6666
2021-08-31T03:07:34.016457371Z 6666
2021-08-31T03:07:35.017994507Z 6666
2021-08-31T03:07:36.020063232Z 6666
2021-08-31T03:07:37.022952066Z 6666
。。。。。。

4.3 查看容器中进程信息 ps

# 命令:docker top 容器id
[root@localhost ~]# docker top 07aaf797bf5d
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                4390                4372                0                   11:05               ?                   00:00:00            /bin/sh -c while... 
root                5271                4390                0                   11:16               ?                   00:00:00            /usr/bin/coreutils....

4.4 查看镜像的元数据

# 命令:docker inspect 容器id
[root@localhost ~]# docker inspect 07aaf797bf5d
[
    {
        "Id": "07aaf797bf5d6fee4d4f8a1b7fb9985fa9c0f7fb9faf17db0962f375dd96c1d4",
        "Created": "2021-08-31T03:05:17.547777625Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true;do echo 6666;sleep 1;done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 4390,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-08-31T03:05:18.125791263Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:300e315adb2f96afe5f0b2780b87f28ae95231fe3bdd1e16b9ba606307728f55",
        "ResolvConfPath": "/var/lib/docker/containers/07aaf797bf5d6fee4d4f8a1b7fb9985fa9c0f7fb9faf17db0962f375dd96c1d4/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/07aaf797bf5d6fee4d4f8a1b7fb9985fa9c0f7fb9faf17db0962f375dd96c1d4/hostname",
        "HostsPath": "/var/lib/docker/containers/07aaf797bf5d6fee4d4f8a1b7fb9985fa9c0f7fb9faf17db0962f375dd96c1d4/hosts",
        "LogPath": "/var/lib/docker/containers/07aaf797bf5d6fee4d4f8a1b7fb9985fa9c0f7fb9faf17db0962f375dd96c1d4/07aaf797bf5d6fee4d4f8a1b7fb9985fa9c0f7fb9faf17db0962f375dd96c1d4-json.log",
        "Name": "/nervous_allen",
        "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/5da445591b016e7967ae99096dd8adec5734d308165dc2bd7c5473e0647cb4e9-init/diff:/var/lib/docker/overlay2/25219b6712f3ae9b2c4a1e87dab0fe6027133f8164bac743fdcb2bcee71a1893/diff",
                "MergedDir": "/var/lib/docker/overlay2/5da445591b016e7967ae99096dd8adec5734d308165dc2bd7c5473e0647cb4e9/merged",
                "UpperDir": "/var/lib/docker/overlay2/5da445591b016e7967ae99096dd8adec5734d308165dc2bd7c5473e0647cb4e9/diff",
                "WorkDir": "/var/lib/docker/overlay2/5da445591b016e7967ae99096dd8adec5734d308165dc2bd7c5473e0647cb4e9/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "07aaf797bf5d",
            "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 6666;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": "0f4da16ab443d9567c8ea8aa26700199a72092563f3a1ff8d60add3927e55e2b",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/0f4da16ab443",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "357c90bdf0cd9abb588b4b871e8ee6508afd307146450763d77df85ea6aed1b6",
            "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": "c1bd6b7d22fc68018fd341f2c1c127c859e34dc2711f0cbd3946c76da14aaa95",
                    "EndpointID": "357c90bdf0cd9abb588b4b871e8ee6508afd307146450763d77df85ea6aed1b6",
                    "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
                }
            }
        }
    }
]

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

我们通常容器都是使用后台方式运行的,需要进入容器,修改一些配置

# 命令 docker exec -it 容器id bashshell

#测试
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS     NAMES
07aaf797bf5d   centos    "/bin/sh -c 'while t…"   19 minutes ago   Up 19 minutes             nervous_allen
[root@localhost ~]# docker exec -it 07aaf797bf5d /bin/bash
[root@07aaf797bf5d /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@07aaf797bf5d /]# 

# 方式二
# 命令 docker attach 容器id 

# 测试
[root@localhost ~]# docker ps
CONTAINER ID    IMAGE     	COMMAND                  CREATED          STATUS          PORTS     				NAMES
07aaf797bf5d   	 centos   	 "/bin/sh -c 'while t…"   22 minutes ago   	Up 				    22 minutes             nervous_allen
[root@localhost ~]# docker attach 07aaf797bf5d
6666
6666
6666
6666
6666
6666

区别
#docker exec #进入当前容器后开启一个新的终端,可以在里面操作。(常用)
#docker attach # 进入容器正在执行的终端

4.6 从容器内拷贝到主机上

#命令  docker cp 容器内复制的目录    主机目录

#进入docker容器内部
[root@localhost ~]# docker run -it centos /bin/bash
[root@a150eb0a305e /]# 
[root@localhost ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
a150eb0a305e   centos    "/bin/bash"   16 seconds ago   Up 13 seconds             vigorous_newton
[root@localhost ~]# docker attach a150eb0a305e
[root@a150eb0a305e /]# cd /home
[root@a150eb0a305e home]# ls
#新建一个文件
[root@a150eb0a305e home]# touch test.java
[root@a150eb0a305e home]# ls
test.java
[root@a150eb0a305e home]# exit
exit
# 进行拷贝
[root@localhost ~]# docker cp a150eb0a305e:/home/test.java /home
[root@localhost ~]# cd /home
[root@localhost home]# ls
admin  test.java

5. 总结

在这里插入图片描述

   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 # 拉取指定镜像或者库镜像
  push        Push an image or a repository to a registry # 推送指定镜像或者库镜像 
  rename      Rename a container # 重命名容器
  restart     Restart one or more containers # 重启动容器
  rm          Remove one or more containers
  rmi         Remove one or more images
  run         Run a command in a new container
  save        Save one or more images to a tar archive (streamed to STDOUT by default) # 保存镜像为一个tar包
  search      Search the Docker Hub for images
  start       Start one or more stopped containers
  stats       Display a live stream of container(s) resource usage statistics
  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
  wait        Block until one or more containers stop, then print their exit codes #截取容器停止时的推出状态值
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值