Docker入门

  1. Docker概述

   Docker为什么会出现?

      考虑一种情况,有一种产品,有开发和上线两种环境!应用环境,应用配置!

      开发-----运维。问题:我在我的电脑上可以运行!版本更新,导致服务不可用!对于运维来说,考验就十分大?

      环境配置是十分麻烦的,每一台机器都需要部署环境(集群Redis,ES,Hadoop....)费时费力。

      发布一个项目 (jar+(Redis MySQL jdk ES)),项目能不能带上环境安装打包!

      例如:

        之前在一个服务器配置一个应用的环境 Redis MySQL jdk Hadoop.配置起来超麻烦,不能够跨平台。

        Windows开发,最后发布在Linux!

          传统:开发jar,环境由运维来做!

          现在:开发打包部署上线,一套流程做完!

     Docker给以上问题提供了解决方案

      举个例子:

      手机软件开发流程:

        java ---> apk --->发布(应用商店) ---> 第三方使用apk --->安装即可用

      相对应的,Docker优化jar包开发部署流程:

        java ---> jar(环境) ---> 打包带上环境(镜像)--->(Docker仓库:对应应用商店)---> 下载我们发布的镜像 ---> 直接运行即可!

      

      

 

      Docker的思想来自于集装箱!

      原本 JRE---多个应用(端口冲突)----原来都是交叉的!

      隔离:Docker核心思想!打包装箱!每个箱子都是互相隔离的。

      Docker 通过隔离机制,可以将服务器压榨到机制

   Docker历史

      2010年,几个搞IT的年轻人,就在美国成立了一家公司dotCloud

      做一些pass的云计算服务!LXC有关的容器技术!

      他们将自己的技术(容器化技术)命名为Docker!

      Docker刚刚诞生的时候,没有引起行业的注意!dotCloud,就活不下去了!

      开源

      开放源代码!

      2013年,Docker开源!

      Docker越来越多的人发现了docker的优点!火了,Docker每个月都会更新一个版本!

      2014年4月9日,Docker1.0发布!

      Dcoker为什么这么火?十分的轻巧!

      在容器技术出现之前我们使用的都是虚拟机技术!

      虚拟机:在window中安装一个Vmware,通过这个软件我们可以虚拟出来一台或者多台电脑!缺点:笨重!

      虚拟机也是虚拟化技术,Docker容器技术,也是一种虚拟化技术!    

        vm:linux centos原生镜像(一个电脑!) 隔离:需要开启多台虚拟机! 几个G

        docker:隔离,镜像(最核心的环境:4m+jdk+mysql) 十分的小巧,运行镜像就可以了!小巧!几个M      

    到现在,所有的开发/运维人员都必须掌握Docker!

    聊聊Docker

    Docker是基于Go语言开发的!开源项目!

    Docker官方文档 Docker文档超级详细

    DockerHub Docker镜像仓库

    Docker可以干什么?

      之前的虚拟机技术

      1. 资源占用十分多
      2. 冗余步骤多
      3. 启动十分满

      

 

 

       容器技术不是模拟一个完整的操作系统

      

      

 

 

     比较Docker和虚拟机技术的不同:

      传统虚拟机,虚拟出一个硬件,运行一个完整的操作系统,然后再这个系统上安装和运行软件

      容器内的应用直接运行在宿主机的内容,容器是没有内核的,也没有虚拟我们的硬件,也没有虚拟我们的硬件,所以就轻便了

      每个容器之间是互相隔离,每个容器都有一个属于自己的文件系统,互不影响。

    DevOps(开发,运维)

    更快速的交付和部署

      传统:一堆帮助文档,安装成簇

      Docker:一键运行打包发布测试,一键运行

    更便捷的升级和扩缩容

      使用了Docker之后,我们部署应用就和搭积木一样!

      项目打包成一个镜像,扩展 服务器B,服务器B一键运行

    更简单的系统运维

      在容器化之后,我们的开发,测试环境都是高度的一致。

    更高效的计算资源利用

      Docker是内核级别的虚拟化,可以在一个物理机上运行很多的容器实例!

  1. Docker安装

   Docker架构图

    

 

 

 

 

     镜像(iamge):

      docker镜像就好比一个模板,可以通过这个模板来创建容器服务,tomcat镜像===》run===>tomcat01容器(提供服务器)

      通过这个容器可以创建多个容器(最终服务运行或者项目运行就是在容器中的)。

    容器(container):

      Docker利用容器技术,独立运行一个或者一组应用,通过镜像来创建的。

      启动,停止,删除,基本命令!

      目前就可以把这个容器理解为一个简单的linux系统

    仓库(repository):

      仓库就是存放镜像的地方!

      仓库可以分为共有仓库和私有仓库!

      Docker Hub

      阿里云...都有容器服务器(配置镜像加速!)

   Docker安装步骤

    环境准备

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#系统版本
[root@iZ2zec2gz7h1jgw8klihsnZ /]# cat /etc/os-release
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"
 
CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"

     Centos7安装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#1.卸载旧的版本
[root@iZ2zec2gz7h1jgw8klihsnZ /]# yum remove docker \
>                   docker-client \
>                   docker-client-latest \
>                   docker-common \
>                   docker-latest \
>                   docker-latest-logrotate \
>                   docker-logrotate \
>                   docker-engine
Loaded plugins: fastestmirror
No Match for argument: docker
No Match for argument: docker-client
No Match for argument: docker-client-latest
No Match for argument: docker-common
No Match for argument: docker-latest
No Match for argument: docker-latest-logrotate
No Match for argument: docker-logrotate
No Match for argument: docker-engine
No Packages marked for removal

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#2。安装安装包
[root@iZ2zec2gz7h1jgw8klihsnZ /]# yum install -y yum-utils
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
base                                                                                                            | 3.6 kB  00:00:00    
epel                                                                                                            | 4.7 kB  00:00:00    
extras                                                                                                          | 2.9 kB  00:00:00    
updates                                                                                                         | 2.9 kB  00:00:00    
Resolving Dependencies
--> Running transaction check
---> Package yum-utils.noarch 0:1.1.31-54.el7_8 will be installed
--> Processing Dependency: python-kitchen for package: yum-utils-1.1.31-54.el7_8.noarch
--> Processing Dependency: libxml2-python for package: yum-utils-1.1.31-54.el7_8.noarch
--> Running transaction check
---> Package libxml2-python.x86_64 0:2.9.1-6.el7_9.6 will be installed
--> Processing Dependency: libxml2 = 2.9.1-6.el7_9.6 for package: libxml2-python-2.9.1-6.el7_9.6.x86_64
---> Package python-kitchen.noarch 0:1.1.1-5.el7 will be installed
--> Processing Dependency: python-chardet for package: python-kitchen-1.1.1-5.el7.noarch
--> Running transaction check
---> Package libxml2.x86_64 0:2.9.1-6.el7_2.3 will be updated
---> Package libxml2.x86_64 0:2.9.1-6.el7_9.6 will be an update
---> Package python-chardet.noarch 0:2.2.1-3.el7 will be installed
--> Finished Dependency Resolution
 
Dependencies Resolved
 
=======================================================================================================================================
 Package                            Arch                       Version                               Repository                   Size
=======================================================================================================================================
Installing:
 yum-utils                          noarch                     1.1.31-54.el7_8                       base                        122 k
Installing for dependencies:
 libxml2-python                     x86_64                     2.9.1-6.el7_9.6                       updates                     247 k
 python-chardet                     noarch                     2.2.1-3.el7                           base                        227 k
 python-kitchen                     noarch                     1.1.1-5.el7                           base                        267 k
Updating for dependencies:
 libxml2                            x86_64                     2.9.1-6.el7_9.6                       updates                     668 k
 
Transaction Summary
=======================================================================================================================================
Install  1 Package  (+3 Dependent packages)
Upgrade             ( 1 Dependent package)
 
Total download size: 1.5 M
Downloading packages:
Delta RPMs disabled because /usr/bin/applydeltarpm not installed.
(1/5): python-kitchen-1.1.1-5.el7.noarch.rpm                                                                    | 267 kB  00:00:00    
(2/5): libxml2-2.9.1-6.el7_9.6.x86_64.rpm                                                                       | 668 kB  00:00:00    
(3/5): yum-utils-1.1.31-54.el7_8.noarch.rpm                                                                     | 122 kB  00:00:00    
(4/5): python-chardet-2.2.1-3.el7.noarch.rpm                                                                    | 227 kB  00:00:00    
(5/5): libxml2-python-2.9.1-6.el7_9.6.x86_64.rpm                                                                | 247 kB  00:00:00    
---------------------------------------------------------------------------------------------------------------------------------------
Total                                                                                                  4.9 MB/s | 1.5 MB  00:00:00    
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
  Updating   : libxml2-2.9.1-6.el7_9.6.x86_64                                                                                      1/6
  Installing : libxml2-python-2.9.1-6.el7_9.6.x86_64                                                                               2/6
  Installing : python-chardet-2.2.1-3.el7.noarch                                                                                   3/6
  Installing : python-kitchen-1.1.1-5.el7.noarch                                                                                   4/6
  Installing : yum-utils-1.1.31-54.el7_8.noarch                                                                                    5/6
  Cleanup    : libxml2-2.9.1-6.el7_2.3.x86_64                                                                                      6/6
  Verifying  : python-chardet-2.2.1-3.el7.noarch                                                                                   1/6
  Verifying  : libxml2-2.9.1-6.el7_9.6.x86_64                                                                                      2/6
  Verifying  : libxml2-python-2.9.1-6.el7_9.6.x86_64                                                                               3/6
  Verifying  : python-kitchen-1.1.1-5.el7.noarch                                                                                   4/6
  Verifying  : yum-utils-1.1.31-54.el7_8.noarch                                                                                    5/6
  Verifying  : libxml2-2.9.1-6.el7_2.3.x86_64                                                                                      6/6
 
Installed:
  yum-utils.noarch 0:1.1.31-54.el7_8                                                                                                  
 
Dependency Installed:
  libxml2-python.x86_64 0:2.9.1-6.el7_9.6        python-chardet.noarch 0:2.2.1-3.el7        python-kitchen.noarch 0:1.1.1-5.el7      
 
Dependency Updated:
  libxml2.x86_64 0:2.9.1-6.el7_9.6                                                                                                    
 
Complete!

 

1
2
3
4
5
6
7
8
9
#3.设置镜像的仓库
#这里使用阿里云的镜像地址 http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
[root@iZ2zec2gz7h1jgw8klihsnZ /]# yum-config-manager \
>     --add-repo \
>     http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
Loaded plugins: fastestmirror
adding repo from: http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
grabbing file http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo to /etc/yum.repos.d/docker-ce.repo
repo saved to /etc/yum.repos.d/docker-ce.repo

 

1
2
3
4
5
6
7
8
9
10
11
12
13
#清空yum索引
[root@iZ2zec2gz7h1jgw8klihsnZ /]# yum makecache fast
Loaded plugins: fastestmirror
Loading mirror speeds from cached hostfile
base                                                                                                            | 3.6 kB  00:00:00    
docker-ce-stable                                                                                                | 3.5 kB  00:00:00    
epel                                                                                                            | 4.7 kB  00:00:00    
extras                                                                                                          | 2.9 kB  00:00:00    
updates                                                                                                         | 2.9 kB  00:00:00    
(1/2): docker-ce-stable/7/x86_64/updateinfo                                                                     |   55 B  00:00:00    
(2/2): docker-ce-stable/7/x86_64/primary_db                                                                     |  76 kB  00:00:00    
Metadata Cache Created
[root@iZ2zec2gz7h1jgw8klihsnZ /]#

 

1
2
#4.安装Docker引擎
#docker-ce 社区版 ee 企业版<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# yum install docker-ce docker-ce-cli containerd.io docker-compose-plugin

 

1
2
#5.启动Docker
[root@iZ2zec2gz7h1jgw8klihsnZ /]# systemctl start docker

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#使用docker version 测试是否安装成功
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker version
Client: Docker Engine - Community
 Version:           20.10.15
 API version:       1.41
 Go version:        go1.17.9
 Git commit:        fd82621
 Built:             Thu May  5 13:16:58 2022
 OS/Arch:           linux/amd64
 Context:           default
 Experimental:      true
 
Server: Docker Engine - Community
 Engine:
  Version:          20.10.15
  API version:      1.41 (minimum version 1.12)
  Go version:       go1.17.9
  Git commit:       4433bf6
  Built:            Thu May  5 13:15:18 2022
  OS/Arch:          linux/amd64
  Experimental:     false
 containerd:
  Version:          1.6.4
  GitCommit:        212e8b6fa2f44b9c21b2798135fc6fb7c53efc16
 runc:
  Version:          1.1.1
  GitCommit:        v1.1.1-0-g52de29d
 docker-init:
  Version:          0.19.0
  GitCommit:        de40ad0

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#7.docker run hello-world
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
2db29710123e: Pull complete
Digest: sha256:10d7d58d5ebd2a652f4d93fdd86da8f265f5318c6a73cc5b6a9798ff6d2b2e67
Status: Downloaded newer image for hello-world:latest
 
Hello from Docker!
This message shows that your installation appears to be working correctly.
 
To generate this message, Docker took the following steps:
 1. The Docker client contacted the Docker daemon.
 2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
    (amd64)
 3. The Docker daemon created a new container from that image which runs the
    executable that produces the output you are currently reading.
 4. The Docker daemon streamed that output to the Docker client, which sent it
    to your terminal.
 
To try something more ambitious, you can run an Ubuntu container with:
 $ docker run -it ubuntu bash
 
Share images, automate workflows, and more with a free Docker ID:
 https://hub.docker.com/
 
For more examples and ideas, visit:
 https://docs.docker.com/get-started/

 

1
2
3
4
#8.查看下载的这个 hello-world镜像
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
hello-world   latest    feb5d9fea6a5   7 months ago   13.3kB

 如何卸载Docker?

1
2
#1.Uninstall the Docker Engine, CLI, Containerd, and Docker Compose packages:
yum remove docker-ce docker-ce-cli containerd.io

 

1
2
3
4
#2.Images, containers, volumes, or customized configuration files on your host are not automatically removed. To delete all images, containers, and volumes:<br>#删除docker资源  /var/lib/ docker默认资源路径
 rm -rf /var/lib/docker
 
 rm -rf /var/lib/containerd

 如何设置内部阿里云镜像加速?

1.找到阿里云的镜像加速器页面

  

 

 

 2.配置竞相加速器

1
2
3
4
5
6
7
8
sudo mkdir -p /etc/docker<br>
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["https://ct2e6f86.mirror.aliyuncs.com"]
}
EOF<br>
sudo systemctl daemon-reload<br>
sudo systemctl restart docker

 Docker run的流程图

 

 

 底层原理:Docker是怎么工作的?

  Docker是一个Client-Server结构的系统,Docker的守护进程运行在主机,通过Socket从客户端访问!

  DockerServer接收到Docker-Client的指令,就会执行这个命令!

 

 

 Docker为什么比虚拟机快?

  1.Docker有着比虚拟机更少的抽象层。

  

 

 

   2.Docker利用的是宿主机的内核,而VM需要的是Guest OS.

  所以说,新建一个容器的时候,docker不需要虚拟机一样重新加载一个操作系统内核,避免引导。虚拟机是加载Guest OS,分钟级别;而docker是利用宿主机的操作系统,省略了复杂的过程,秒级!

  

 

 

 

 

Docker命令

 

 

帮助命令

 

1
2
#docker version 显示docker版本信息
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker version<br>Client: Docker Engine - Community<br> Version:           20.10.15<br> API version:       1.41<br> Go version:        go1.17.9<br> Git commit:        fd82621<br> Built:             Thu May  5 13:16:58 2022<br> OS/Arch:           linux/amd64<br> Context:           default<br> Experimental:      true<br><br>Server: Docker Engine - Community<br> Engine:<br>  Version:          20.10.15<br>  API version:      1.41 (minimum version 1.12)<br>  Go version:       go1.17.9<br>  Git commit:       4433bf6<br>  Built:            Thu May  5 13:15:18 2022<br>  OS/Arch:          linux/amd64<br>  Experimental:     false<br> containerd:<br>  Version:          1.6.4<br>  GitCommit:        212e8b6fa2f44b9c21b2798135fc6fb7c53efc16<br> runc:<br>  Version:          1.1.1<br>  GitCommit:        v1.1.1-0-g52de29d<br> docker-init:<br>  Version:          0.19.0<br>  GitCommit:        de40ad0

 

1
#docker info 显示Docker的系统信息,包括镜像和容器的数量<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker info<br>Client:<br> Context:    default<br> Debug Mode: false<br> Plugins:<br>  app: Docker App (Docker Inc., v0.9.1-beta3)<br>  buildx: Docker Buildx (Docker Inc., v0.8.2-docker)<br>  compose: Docker Compose (Docker Inc., v2.5.0)<br>  scan: Docker Scan (Docker Inc., v0.17.0)<br><br>Server:<br> Containers: 1<br>  Running: 0<br>  Paused: 0<br>  Stopped: 1<br> Images: 1<br> Server Version: 20.10.15<br> Storage Driver: overlay2<br>  Backing Filesystem: extfs<br>  Supports d_type: true<br>  Native Overlay Diff: true<br>  userxattr: false<br> Logging Driver: json-file<br> Cgroup Driver: cgroupfs<br> Cgroup Version: 1<br> Plugins:<br>  Volume: local<br>  Network: bridge host ipvlan macvlan null overlay<br>  Log: awslogs fluentd gcplogs gelf journald json-file local logentries splunk syslog<br> Swarm: inactive<br> Runtimes: io.containerd.runtime.v1.linux runc io.containerd.runc.v2<br> Default Runtime: runc<br> Init Binary: docker-init<br> containerd version: 212e8b6fa2f44b9c21b2798135fc6fb7c53efc16<br> runc version: v1.1.1-0-g52de29d<br> init version: de40ad0<br> Security Options:<br>  seccomp<br>   Profile: default<br> Kernel Version: 3.10.0-1062.18.1.el7.x86_64<br> Operating System: CentOS Linux 7 (Core)<br> OSType: linux<br> Architecture: x86_64<br> CPUs: 1<br> Total Memory: 1.795GiB<br> Name: iZ2zec2gz7h1jgw8klihsnZ<br> ID: T2TL:C3VA:3VFE:KVI6:S4CL:X4HL:NNWR:GLBH:NDIC:Y35B:GGDE:TQVG<br> Docker Root Dir: /var/lib/docker<br> Debug Mode: false<br> Registry: https://index.docker.io/v1/<br> Labels:<br> Experimental: false<br> Insecure Registries:<br>  127.0.0.0/8<br> Registry Mirrors:<br>  https://ct2e6f86.mirror.aliyuncs.com/<br> Live Restore Enabled: false

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#docker --help 帮助命令
[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker --help
 
Usage:  docker [OPTIONS] COMMAND
 
A self-sufficient runtime for containers
 
Options:
      --config string      Location of client config files (default "/root/.docker")
  -c, --context string     Name of the context to use to connect to the daemon (overrides DOCKER_HOST env var and default
                           context set with "docker context use")
  -D, --debug              Enable debug mode
  -H, --host list          Daemon socket(s) to connect to
  -l, --log-level string   Set the logging level ("debug"|"info"|"warn"|"error"|"fatal") (default "info")
      --tls                Use TLS; implied by --tlsverify
      --tlscacert string   Trust certs signed only by this CA (default "/root/.docker/ca.pem")
      --tlscert string     Path to TLS certificate file (default "/root/.docker/cert.pem")
      --tlskey string      Path to TLS key file (default "/root/.docker/key.pem")
      --tlsverify          Use TLS and verify the remote
  -v, --version            Print version information and quit
 
Management Commands:
  app*        Docker App (Docker Inc., v0.9.1-beta3)
  builder     Manage builds
  buildx*     Docker Buildx (Docker Inc., v0.8.2-docker)
  compose*    Docker Compose (Docker Inc., v2.5.0)
  config      Manage Docker configs
  container   Manage containers
  context     Manage contexts
  image       Manage images
  manifest    Manage Docker image manifests and manifest lists
  network     Manage networks
  node        Manage Swarm nodes
  plugin      Manage plugins
  scan*       Docker Scan (Docker Inc., v0.17.0)
  secret      Manage Docker secrets
  service     Manage services
  stack       Manage Docker stacks
  swarm       Manage Swarm
  system      Manage Docker
  trust       Manage trust on Docker images
  volume      Manage volumes
 
Commands:
  attach      Attach local standard input, output, and error streams to a running container
  build       Build an image from a 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
  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
  history     Show the history of an image
  images      List images
  import      Import the contents from a tarball to create a filesystem image
  info        Display system-wide information
  inspect     Return low-level information on Docker objects
  kill        Kill one or more running containers
  load        Load an image from a tar archive or STDIN
  login       Log in to a Docker registry
  logout      Log out from a 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)
  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
 
Run 'docker COMMAND --help' for more information on a command.
 
To get more help with docker, check out our guides at https://docs.docker.com/go/guides/

 Docker命令查询文档链接

镜像命令

1
#docker images 查看本地主机上的镜像<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker images --help<br><br>Usage:  docker images [OPTIONS] [REPOSITORY[:TAG]]<br><br>List images<br><br>Options:<br>  -a, --all             Show all images (default hides intermediate images)<br>      --digests         Show digests<br>  -f, --filter filter   Filter output based on conditions provided<br>      --format string   Pretty-print images using a Go template<br>      --no-trunc        Don't truncate output<br>  -q, --quiet           Only show image IDs<br><br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker images<br>REPOSITORY    TAG       IMAGE ID       CREATED        SIZE<br>hello-world   latest    feb5d9fea6a5   7 months ago   13.3kB<br>#解释<br>#REPOSITORY 镜像的仓库源<br>#TAG        镜像的标签<br>#IMAGE ID   镜像的id<br>#CREATED    镜像的创建时间<br>#SIZE       镜像的大小

 

1
#docker search命令 搜索镜像<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker search --help<br><br>Usage:  docker search [OPTIONS] TERM<br><br>Search the Docker Hub for images<br><br>Options:<br>  -f, --filter filter   Filter output based on conditions provided<br>      --format string   Pretty-print search using a Go template<br>      --limit int       Max number of search results (default 25)<br>      --no-trunc        Don't truncate output<br>#--filter=STARS=3000 这时候就会搜索出STARS>3000的候选项<br><br><br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker search mysql<br>NAME                             DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED<br>mysql                            MySQL is a widely used, open-source relation…   12521     [OK]       <br>mariadb                          MariaDB Server is a high performing open sou…   4816      [OK]       <br>mysql/mysql-server               Optimized MySQL Server Docker images. Create…   925                  [OK]<br><br>

 

1
#docker pull 下载镜像 docker pull 镜像名 [:tag]<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker pull --help<br><br>Usage:  docker pull [OPTIONS] NAME[:TAG|@DIGEST]<br><br>Pull an image or a repository from a registry<br><br>Options:<br>  -a, --all-tags                Download all tagged images in the repository<br>      --disable-content-trust   Skip image verification (default true)<br>      --platform string         Set platform if server is multi-platform capable<br>  -q, --quiet                   Suppress verbose output<br><br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker pull mysql<br>Using default tag: latest#如果不写tag,默认就是latest 最新版   docker pull mysql 等价于 docker pull mysql:latest<br>latest: Pulling from library/mysql<br>72a69066d2fe: Pull complete #分层下载,docker image的核心 联合文件系统<br>93619dbc5b36: Pull complete <br>99da31dd6142: Pull complete <br>626033c43d70: Pull complete <br>37d5d7efb64e: Pull complete <br>ac563158d721: Pull complete <br>d2ba16033dad: Pull complete <br>688ba7d5c01a: Pull complete <br>00e060b6d11d: Pull complete <br>1c04857f594f: Pull complete <br>4d7cfa90e6ea: Pull complete <br>e0431212d27d: Pull complete <br>Digest: sha256:e9027fe4d91c0153429607251656806cc784e914937271037f7738bd5b8e7709 #签名<br>Status: Downloaded newer image for mysql:latest #<br>docker.io/library/mysql:latest #真实地址<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# <br>#############################################<br>#制定版本下载<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker pull mysql:5.7<br>5.7: Pulling from library/mysql<br>72a69066d2fe: Already exists <br>93619dbc5b36: Already exists <br>99da31dd6142: Already exists <br>626033c43d70: Already exists <br>37d5d7efb64e: Already exists <br>ac563158d721: Already exists <br>d2ba16033dad: Already exists <br>0ceb82207cd7: Pull complete <br>37f2405cae96: Pull complete <br>e2482e017e53: Pull complete <br>70deed891d42: Pull complete <br>Digest: sha256:f2ad209efe9c67104167fc609cca6973c8422939491c9345270175a300419f94<br>Status: Downloaded newer image for mysql:5.7<br>docker.io/library/mysql:5.7<br>

 

1
#docker rmi 删除镜像<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker rmi --help<br><br>Usage:  docker rmi [OPTIONS] IMAGE [IMAGE...]<br><br>Remove one or more images<br><br>Options:<br>  -f, --force      Force removal of the image<br>      --no-prune   Do not delete untagged parents<br><br>#指定ID删除 docker rmi -f 容器id<br>#删除多个容器 docker rmi -f 容器id1 容器id2 ...<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker rmi -f 3218b38490ce<br>Untagged: mysql:latest<br>Untagged: mysql@sha256:e9027fe4d91c0153429607251656806cc784e914937271037f7738bd5b8e7709<br>Deleted: sha256:3218b38490cec8d31976a40b92e09d61377359eab878db49f025e5d464367f3b<br>Deleted: sha256:aa81ca46575069829fe1b3c654d9e8feb43b4373932159fe2cad1ac13524a2f5<br>Deleted: sha256:0558823b9fbe967ea6d7174999be3cc9250b3423036370dc1a6888168cbd224d<br>Deleted: sha256:a46013db1d31231a0e1bac7eeda5ad4786dea0b1773927b45f92ea352a6d7ff9<br>Deleted: sha256:af161a47bb22852e9e3caf39f1dcd590b64bb8fae54315f9c2e7dc35b025e4e3<br>Deleted: sha256:feff1495e6982a7e91edc59b96ea74fd80e03674d92c7ec8a502b417268822ff<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# <br>#回调删除<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker rmi $(docker images -qa)<br>Untagged: mysql:5.7<br>Untagged: mysql@sha256:f2ad209efe9c67104167fc609cca6973c8422939491c9345270175a300419f94<br>Deleted: sha256:c20987f18b130f9d144c9828df630417e2a9523148930dc3963e9d0dab302a76<br>Deleted: sha256:6567396b065ee734fb2dbb80c8923324a778426dfd01969f091f1ab2d52c7989<br>Deleted: sha256:0910f12649d514b471f1583a16f672ab67e3d29d9833a15dc2df50dd5536e40f<br>Deleted: sha256:6682af2fb40555c448b84711c7302d0f86fc716bbe9c7dc7dbd739ef9d757150<br>Deleted: sha256:5c062c3ac20f576d24454e74781511a5f96739f289edaadf2de934d06e910b92<br>Deleted: sha256:8805862fcb6ef9deb32d4218e9e6377f35fb351a8be7abafdf1da358b2b287ba<br>Deleted: sha256:872d2f24c4c64a6795e86958fde075a273c35c82815f0a5025cce41edfef50c7<br>Deleted: sha256:6fdb3143b79e1be7181d32748dd9d4a845056dfe16ee4c827410e0edef5ad3da<br>Deleted: sha256:b0527c827c82a8f8f37f706fcb86c420819bb7d707a8de7b664b9ca491c96838<br>Deleted: sha256:75147f61f29796d6528486d8b1f9fb5d122709ea35620f8ffcea0e0ad2ab0cd0<br>Deleted: sha256:2938c71ddf01643685879bf182b626f0a53b1356138ef73c40496182e84548aa<br>Deleted: sha256:ad6b69b549193f81b039a1d478bc896f6e460c77c1849a4374ab95f9a3d2cea2<br>Error response from daemon: conflict: unable to delete feb5d9fea6a5 (must be forced) - image is being used by stopped container 8b4dd872b6e7<br>

 

容器命令

我们有了镜像才可以常见容器,linux,下载一个linux镜像来测试学习

1
#下载一个centos镜像<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker search centos<br>NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED<br>centos                            The official build of CentOS.                   7133      [OK]       <br>centos/systemd                    systemd enabled base container.                 108                  [OK]<br>centos/mysql-57-centos7           MySQL 5.7 SQL database server                   94                   <br>centos/postgresql-96-centos7      PostgreSQL is an advanced Object-Relational …   45                   <br>centos/httpd-24-centos7           Platform for running Apache httpd 2.4 or bui…   44                   <br>centos/php-56-centos7             Platform for building and running PHP 5.6 ap…   34                   <br>centos/mysql-56-centos7           MySQL 5.6 SQL database server                   22                   <br>kasmweb/centos-7-desktop          CentOS 7 desktop for Kasm Workspaces            19                   <br>centos/postgresql-10-centos7      PostgreSQL is an advanced Object-Relational …   19                   <br>centos/nginx-112-centos7          Platform for running nginx 1.12 or building …   16                   <br>centos/nginx-18-centos7           Platform for running nginx 1.8 or building n…   14                   <br>centos/mariadb-101-centos7        MariaDB 10.1 SQL database server                13                   <br>centos/mongodb-36-centos7         MongoDB NoSQL database server                   8                    <br>centos/mariadb-102-centos7        MariaDB 10.2 SQL database server                6                    <br>centos/redis-32-centos7           Redis in-memory data structure store, used a…   6                    <br>kasmweb/core-centos-7             CentOS 7 base image for Kasm Workspaces         3                    <br>centos/ruby-25-centos7            Platform for building and running Ruby 2.5 a…   3                    <br>continuumio/centos5_gcc5_base                                                     3                    <br>centos/mongodb-34-centos7         MongoDB NoSQL database server                   3                    <br>ibmcom/fhe-toolkit-centos         The IBM Fully Homomorphic Encryption (FHE) T…   0                    <br>ibmcom/fhe-toolkit-centos-amd64   The IBM Fully Homomorphic Encryption (FHE) T…   0                    <br>datadog/centos-i386                                                               0                    <br>bitnami/centos-extras-base                                                        0                    <br>bitnami/centos-base-buildpack     Centos base compilation image                   0                    [OK]<br>centos/nginx-110-centos7          Platform for running nginx 1.10 or building …   0                    <br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# doucker pull  centos<br>-bash: doucker: command not found<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# douker pull  centos<br>-bash: douker: command not found<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker pull  centos<br>Using default tag: latest<br>latest: Pulling from library/centos<br>a1d0c7532777: Pull complete <br>Digest: sha256:a27fd8080b517143cbbbab9dfb7c8571c40d67d534bbdee55bd6c473f432b177<br>Status: Downloaded newer image for centos:latest<br>docker.io/library/centos:latest

 

1
#docker run 新建容器启动<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker run --help<br><br>Usage:  docker run [OPTIONS] IMAGE [COMMAND] [ARG...]<br>#常见参数说明<br>#--name="容器名" 容器名字 tomcat01 tomcat02,用来区分容器<br>#-d             后台运行<br>#-it            使用交互方式运行,进入容器查看内容<br>#-p             制定容器端口 -p 8080:8080<br>  #-p使用方式<br>    #-p ip:主机端口:容器端口<br>    #-p 主机端口:容器端口(常用)<br>    #-p 容器端口<br><br>#-P             随机制定端口<br><br>Run a command in a new container<br><br>Options:<br>      --add-host list                  Add a custom host-to-IP mapping (host:ip)<br>  -a, --attach list                    Attach to STDIN, STDOUT or STDERR<br>      --blkio-weight uint16            Block IO (relative weight), between 10 and 1000, or 0 to disable (default 0)<br>      --blkio-weight-device list       Block IO weight (relative device weight) (default [])<br>      --cap-add list                   Add Linux capabilities<br>      --cap-drop list                  Drop Linux capabilities<br>      --cgroup-parent string           Optional parent cgroup for the container<br>      --cgroupns string                Cgroup namespace to use (host|private)<br>                                       'host':    Run the container in the Docker host's cgroup namespace<br>                                       'private': Run the container in its own private cgroup namespace<br>                                       '':        Use the cgroup namespace as configured by the<br>                                                  default-cgroupns-mode option on the daemon (default)<br>      --cidfile string                 Write the container ID to the file<br>      --cpu-period int                 Limit CPU CFS (Completely Fair Scheduler) period<br>      --cpu-quota int                  Limit CPU CFS (Completely Fair Scheduler) quota<br>      --cpu-rt-period int              Limit CPU real-time period in microseconds<br>      --cpu-rt-runtime int             Limit CPU real-time runtime in microseconds<br>  -c, --cpu-shares int                 CPU shares (relative weight)<br>      --cpus decimal                   Number of CPUs<br>      --cpuset-cpus string             CPUs in which to allow execution (0-3, 0,1)<br>      --cpuset-mems string             MEMs in which to allow execution (0-3, 0,1)<br>  -d, --detach                         Run container in background and print container ID<br>      --detach-keys string             Override the key sequence for detaching a container<br>      --device list                    Add a host device to the container<br>      --device-cgroup-rule list        Add a rule to the cgroup allowed devices list<br>      --device-read-bps list           Limit read rate (bytes per second) from a device (default [])<br>      --device-read-iops list          Limit read rate (IO per second) from a device (default [])<br>      --device-write-bps list          Limit write rate (bytes per second) to a device (default [])<br>      --device-write-iops list         Limit write rate (IO per second) to a device (default [])<br>      --disable-content-trust          Skip image verification (default true)<br>      --dns list                       Set custom DNS servers<br>      --dns-option list                Set DNS options<br>      --dns-search list                Set custom DNS search domains<br>      --domainname string              Container NIS domain name<br>      --entrypoint string              Overwrite the default ENTRYPOINT of the image<br>  -e, --env list                       Set environment variables<br>      --env-file list                  Read in a file of environment variables<br>      --expose list                    Expose a port or a range of ports<br>      --gpus gpu-request               GPU devices to add to the container ('all' to pass all GPUs)<br>      --group-add list                 Add additional groups to join<br>      --health-cmd string              Command to run to check health<br>      --health-interval duration       Time between running the check (ms|s|m|h) (default 0s)<br>      --health-retries int             Consecutive failures needed to report unhealthy<br>      --health-start-period duration   Start period for the container to initialize before starting health-retries countdown<br>                                       (ms|s|m|h) (default 0s)<br>      --health-timeout duration        Maximum time to allow one check to run (ms|s|m|h) (default 0s)<br>      --help                           Print usage<br>  -h, --hostname string                Container host name<br>      --init                           Run an init inside the container that forwards signals and reaps processes<br>  -i, --interactive                    Keep STDIN open even if not attached<br>      --ip string                      IPv4 address (e.g., 172.30.100.104)<br>      --ip6 string                     IPv6 address (e.g., 2001:db8::33)<br>      --ipc string                     IPC mode to use<br>      --isolation string               Container isolation technology<br>      --kernel-memory bytes            Kernel memory limit<br>  -l, --label list                     Set meta data on a container<br>      --label-file list                Read in a line delimited file of labels<br>      --link list                      Add link to another container<br>      --link-local-ip list             Container IPv4/IPv6 link-local addresses<br>      --log-driver string              Logging driver for the container<br>      --log-opt list                   Log driver options<br>      --mac-address string             Container MAC address (e.g., 92:d0:c6:0a:29:33)<br>  -m, --memory bytes                   Memory limit<br>      --memory-reservation bytes       Memory soft limit<br>      --memory-swap bytes              Swap limit equal to memory plus swap: '-1' to enable unlimited swap<br>      --memory-swappiness int          Tune container memory swappiness (0 to 100) (default -1)<br>      --mount mount                    Attach a filesystem mount to the container<br>      --name string                    Assign a name to the container<br>      --network network                Connect a container to a network<br>      --network-alias list             Add network-scoped alias for the container<br>      --no-healthcheck                 Disable any container-specified HEALTHCHECK<br>      --oom-kill-disable               Disable OOM Killer<br>      --oom-score-adj int              Tune host's OOM preferences (-1000 to 1000)<br>      --pid string                     PID namespace to use<br>      --pids-limit int                 Tune container pids limit (set -1 for unlimited)<br>      --platform string                Set platform if server is multi-platform capable<br>      --privileged                     Give extended privileges to this container<br>  -p, --publish list                   Publish a container's port(s) to the host<br>  -P, --publish-all                    Publish all exposed ports to random ports<br>      --pull string                    Pull image before running ("always"|"missing"|"never") (default "missing")<br>      --read-only                      Mount the container's root filesystem as read only<br>      --restart string                 Restart policy to apply when a container exits (default "no")<br>      --rm                             Automatically remove the container when it exits<br>      --runtime string                 Runtime to use for this container<br>      --security-opt list              Security Options<br>      --shm-size bytes                 Size of /dev/shm<br>      --sig-proxy                      Proxy received signals to the process (default true)<br>      --stop-signal string             Signal to stop a container (default "SIGTERM")<br>      --stop-timeout int               Timeout (in seconds) to stop a container<br>      --storage-opt list               Storage driver options for the container<br>      --sysctl map                     Sysctl options (default map[])<br>      --tmpfs list                     Mount a tmpfs directory<br>  -t, --tty                            Allocate a pseudo-TTY<br>      --ulimit ulimit                  Ulimit options (default [])<br>  -u, --user string                    Username or UID (format: <name|uid>[:<group|gid>])<br>      --userns string                  User namespace to use<br>      --uts string                     UTS namespace to use<br>  -v, --volume list                    Bind mount a volume<br>      --volume-driver string           Optional volume driver for the container<br>      --volumes-from list              Mount volumes from the specified container(s)<br>  -w, --workdir string                 Working directory inside the container<br>#################################################################################<br>#测试docker run 命令的使用<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# <br><br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker run -it centos /bin/bash  #启动并进入容器<br>[root@4cc85a317196 /]# ls #查看容器内的centos,基础版本,很多命令都是不完善的<br>bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var<br>[root@4cc85a317196 /]# exit #从容器中退回主机<br>exit<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]#

 

1
#docker ps查看运行中的容器<br>#     列出当前正在运行的容器<br>#-a   列出当前正在运行的容器,带出历史运行过的容器<br>#-n=? 显示最近创建的容器<br>#-q   只显示容器的ID<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps #列出当前正在运行中的容器<br>CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps -a #列出<br>CONTAINER ID   IMAGE         COMMAND       CREATED         STATUS                          PORTS     NAMES<br>4cc85a317196   centos        "/bin/bash"   3 minutes ago   Exited (0) About a minute ago             ecstatic_robinson<br>8b4dd872b6e7   hello-world   "/hello"      2 hours ago     Exited (0) 2 hours ago                    admiring_gould<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps -aq<br>4cc85a317196<br>8b4dd872b6e7 <br>

 

1
#退出容器相关命令<br>exit #直接容器停止并退出<br>ctrl+p+q #容器不停止退出

 

1
#删除容器<br>docker rm 容器id               #删除指定容器  不能删除正在运行中的容器, docker rm -f 容器id强制删除容器<br>docker rm -f $(docker ps -aq) #删除所有容器<br>docker ps -a|xargs docker rm  #通过管道符删除所有容器

 

1
#启动和停止容器的操作<br>docker start 容器id    #启动容器<br>docker restart 容器id  #重启容器<br>docker stop 容器id   #停止当前运行容器<br>docker kill 容器id     #强制停止当前容器

 

1
#后台启动容器<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker run -d --name="centos02" centos <br>1a0f5a321118bd793f70fabdd868e2a543ba18ee83838fa766a525a7869d15a8<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps -a<br>CONTAINER ID   IMAGE         COMMAND       CREATED          STATUS                     PORTS     NAMES<br>1a0f5a321118   centos        "/bin/bash"   6 seconds ago    Exited (0) 5 seconds ago             centos02<br>8be72caaa4a7   centos        "/bin/bash"   8 minutes ago    Up 8 minutes                         centos01<br>4cc85a317196   centos        "/bin/bash"   20 minutes ago   Up About a minute                    ecstatic_robinson<br>8b4dd872b6e7   hello-world   "/hello"      2 hours ago      Exited (0) 2 hours ago               admiring_gould<br><br>#########问题:docker ps 发现启动的命名为"centos02"的容器状态停止了<br>#########常见的坑:容器使用后台运行,就必须要有一个前台进程,docker发现该容器没有应用,就会自动停止<br>#########Nginx,容器启动后,发现自己没有提供服务,就会立刻停止(它自己就会认为没有程序了)<br><br>

 

1
#docker logs          查看日志命令<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker logs --help<br><br>Usage:  docker logs [OPTIONS] CONTAINER<br><br>Fetch the logs of a container<br><br>Options:<br>      --details        Show extra details provided to logs<br>  -f, --follow         Follow log output<br>      --since string   Show logs since timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)<br>  -n, --tail string    Number of lines to show from the end of the logs (default "all")<br>  -t, --timestamps     Show timestamps<br>      --until string   Show logs before a timestamp (e.g. 2013-01-02T13:23:37Z) or relative (e.g. 42m for 42 minutes)<br><br>docker logs -f -t 容器id, 没有日志<br>#自己编写一个shell脚本<br>root@iZ2zec2gz7h1jgw8klihsnZ /]# docker logs -f -t --tail=10 87c4f1ebc327  #--tail=number 要显示的日志条数<br>2022-05-06T11:22:38.879103869Z kuangshen<br>2022-05-06T11:22:39.881477695Z kuangshen<br>2022-05-06T11:22:40.886896828Z kuangshen<br>2022-05-06T11:22:41.888957987Z kuangshen<br>2022-05-06T11:22:42.891040169Z kuangshen<br>2022-05-06T11:22:43.893141573Z kuangshen<br>2022-05-06T11:22:44.895206262Z kuangshen<br>2022-05-06T11:22:45.897327442Z kuangs

 

1
#docker top 容器id  查看容器中的进程信息 <br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker ps<br>CONTAINER ID   IMAGE     COMMAND                  CREATED             STATUS             PORTS     NAMES<br>87c4f1ebc327   centos    "/bin/sh -c 'while t…"   3 minutes ago       Up 3 minutes                 sad_babbage<br>8be72caaa4a7   centos    "/bin/bash"              About an hour ago   Up About an hour             centos01<br>4cc85a317196   centos    "/bin/bash"              About an hour ago   Up 57 minutes                ecstatic_robinson<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker top 87c4f1ebc327<br>UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD<br>root                18172               18153               0                   19:21               ?                   00:00:00            /bin/sh -c while true;do echo kuangshen;sleep 1;done<br>root                18533               18172               0                   19:25               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 1<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]#

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#docker inspect 容器id  #查看镜像容器的元数据<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker inspect 87c4f1ebc327
[
    {
        "Id": "87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8",
        "Created": "2022-05-06T11:21:30.439030234Z",
        "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": 18172,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2022-05-06T11:21:30.731601995Z",
            "FinishedAt": "0001-01-01T00:00:00Z"
        },
        "Image": "sha256:5d0da3dc976460b72c77d94c8a1ad043720b0416bfc16c52c45d4847e53fadb6",
        "ResolvConfPath": "/var/lib/docker/containers/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8/hostname",
        "HostsPath": "/var/lib/docker/containers/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8/hosts",
        "LogPath": "/var/lib/docker/containers/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8/87c4f1ebc32701f27c3a437cdbbfa23f699b206e26087b681d0bca484e60a5c8-json.log",
        "Name": "/sad_babbage",
        "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/9b9a635e925c8aa964088742fd2928d071db52a0fca036846b4e6ce404096bdb-init/diff:/var/lib/docker/overlay2/f0b92d162490bac978b459ad6cc2a7e24cf8a2b60c0f10b0e9c66d0638936237/diff",
                "MergedDir": "/var/lib/docker/overlay2/9b9a635e925c8aa964088742fd2928d071db52a0fca036846b4e6ce404096bdb/merged",
                "UpperDir": "/var/lib/docker/overlay2/9b9a635e925c8aa964088742fd2928d071db52a0fca036846b4e6ce404096bdb/diff",
                "WorkDir": "/var/lib/docker/overlay2/9b9a635e925c8aa964088742fd2928d071db52a0fca036846b4e6ce404096bdb/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [],
        "Config": {
            "Hostname": "87c4f1ebc327",
            "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": "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": "3f9ef183276fa2747b7fd8abd5b9eccfc62bd17e7e2ac2036f79625a395bee89",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/3f9ef183276f",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "ed5f048fa928944e057d1c1b068f89253ace616e56b9dc4a9aada0916c8c959c",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.4",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:04",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "feb3d1ca8d81153ef6a23103a75495fc92bc2776d479880673eafebf84c46e11",
                    "EndpointID": "ed5f048fa928944e057d1c1b068f89253ace616e56b9dc4a9aada0916c8c959c",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.4",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:04",
                    "DriverOpts": null
                }
            }
        }
    }
]

 

 

1
2
3
4
5
6
7
#进入当前正在运行的容器<br>#方式一<br>#docker exec -it 容器id bashshell   
#我们通常容器都是使用后台方式进行的,需要进入容器,修改一些配置
#命令
root@iZ2zec2gz7h1jgw8klihsnZ /]# docker exec -it 8be72caaa4a7 /bin/bash
[root@8be72caaa4a7 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@8be72caaa4a7 /]# <br><br>#方式二<br>#docker attach 容器id<br>#正在执行当前的代码。。。<br>[root@iZ2zec2gz7h1jgw8klihsnZ /]# docker attach --help<br><br>Usage:  docker attach [OPTIONS] CONTAINER<br><br>Attach local standard input, output, and error streams to a running container<br><br>Options:<br>      --detach-keys string   Override the key sequence for detaching a container<br>      --no-stdin             Do not attach STDIN<br>      --sig-proxy            Proxy all received signals to the process (default true)<br><br>#####################################<br>#docker exec 和 docker attach的区别<br>#docker exec #进入容器后开启一个新的终端,可以在里面操作(常用)<br>#docker attach #进入容器后正在执行的终端,不会启动新的进程!

 

1
#docker cp 容器id:/目录/文件  主机目录         容器内容从容器拷贝到主机上<br>[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker cp 4cc85a317196:/home/tmp_cp.java /home<br>[root@iZ2zec2gz7h1jgw8klihsnZ ~]# cd /home<br>[root@iZ2zec2gz7h1jgw8klihsnZ home]# ls<br>tmp_cp.java  wgy<br>[root@iZ2zec2gz7h1jgw8klihsnZ home]# <br>###################################<br>#docker是一个手动过程,为了我们使用 -v 卷的技术,可以实现,自动同步 /home /home

 操作命令总结

 

 Docker安装Nginx

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#Docker安装Nginx
#步骤1 搜索镜像 docker search nginx
#步骤2 下载镜像 docker pull nginx
#步骤3 查看镜像 docker images
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker run -d --name nginx01 -p:3344:80 nginx  #后台运行nginx容器
45114e9800fba66d6c9c5e05180014a3a901e9df19f3bb393406cd104038ef48
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS                  NAMES
45114e9800fb   nginx     "/docker-entrypoint.…"   4 seconds ago   Up 4 seconds   0.0.0.0:3344->80/tcp   nginx01
87c4f1ebc327   centos    "/bin/sh -c 'while t…"   20 hours ago    Up 20 hours                           sad_babbage
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# curl localhost:3344  # curl 是一种命令行工具,作用是发出网络请求,然后获取数据,显示在"标准输出"(stdout)上面。它支持多种协议,下面列举其常用功能。
<!DOCTYPE html>
<html>
<head>
<title>Welcome to nginx!</title>
<style>
html { color-scheme: light dark; }
body { width: 35em; margin: 0 auto;
font-family: Tahoma, Verdana, Arial, sans-serif; }
</style>
</head>
<body>
<h1>Welcome to nginx!</h1>
<p>If you see this page, the nginx web server is successfully installed and
working. Further configuration is required.</p>
 
<p>For online documentation and support please refer to
<a href="http://nginx.org/">nginx.org</a>.<br/>
Commercial support is available at
<a href="http://nginx.com/">nginx.com</a>.</p>
 
<p><em>Thank you for using nginx.</em></p>
</body>
</html>

此处需要讲解一下 -p 宿主机端口:容器端口 的作用

  用户无法直接访问容器端口,我们使用-p,来将宿主机端口与容器端口进行绑定(打通端口),从而用户可以通过宿主机端口访问到容器端口,进而访问容器端口相应的服务。

  

 

 

 此时可以通过宿主机的端口:ip访问nginx容器启动的nginx服务的欢迎页面

 

 

 

1
#进入到nginx容器内部<br>root@8597a6f04b0d:/usr/sbin# cd /etc/nginx<br>root@8597a6f04b0d:/etc/nginx# ls<br>conf.d  fastcgi_params  mime.types  modules  nginx.conf  scgi_params  uwsgi_params<br>root@8597a6f04b0d:/etc/nginx# cat nginx.conf<br><br>user  nginx;<br>worker_processes  auto;<br><br>error_log  /var/log/nginx/error.log notice;<br>pid        /var/run/nginx.pid;<br><br><br>events {<br>    worker_connections  1024;<br>}<br><br><br>http {<br>    include       /etc/nginx/mime.types;<br>    default_type  application/octet-stream;<br><br>    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '<br>                      '$status $body_bytes_sent "$http_referer" '<br>                      '"$http_user_agent" "$http_x_forwarded_for"';<br><br>    access_log  /var/log/nginx/access.log  main;<br><br>    sendfile        on;<br>    #tcp_nopush     on;<br><br>    keepalive_timeout  65;<br><br>    #gzip  on;<br><br>    include /etc/nginx/conf.d/*.conf;<br>}

问题:每次改动nginx配置文件,都需要进入容器内部?十分地麻烦,我要是可以在容器外部提供一个映射路径,达到在容器外部修改文件,容器内部就可以自动修改的目的。

Docker部署Tomcat

dockerHub官方提供的安装命令

1
docker run -it --rm tomcat:9.0<br>#我们之前的启动都是后台,停止了容器之后,容器还是可以看到 docker run -it --rm 一般用来测试,运行完就删除<br>

 学习过程中部署Docker的安装命令

1
#下载tomcat镜像 docker pull tomcat<br>#运行tomcat容器<br>[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker run -d -p 3345:8080 --name tomcat01 tomcat<br>405e34e4755157541f480adeb758c76504266c14cd63ccc2034e762ba5dc616c<br>#进入到tomcat容器中<br>[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker exec -it 405e34e47551 /bin/bash<br>root@405e34e47551:/usr/local/tomcat# whereis tomcat<br>tomcat: /usr/local/tomcat<br>root@405e34e47551:/usr/local/tomcat# ls<br>BUILDING.txt     LICENSE  README.md      RUNNING.txt  conf  logs            temp     webapps.dist<br>CONTRIBUTING.md  NOTICE   RELEASE-NOTES  bin          lib   native-jni-lib  webapps  work<br>root@405e34e47551:/usr/local/tomcat# cd webapps #此时发现webapps目录下为空<br>root@405e34e47551:/usr/local/tomcat/webapps# <br>####发现问题 webapps目录下什么都没有,阿里云镜像默认是最小镜像,所有不必要的镜像都剔除掉<br>####保证最小可运行的环境

 以后要部署项目,每次都要进入容器是不是十分麻烦?要是可以在容器外部提供一个映射路径,webapps,在外部放置项目就自动同步到内部就好了!

部署es+kibana

1
#es 暴露的端口非常多<br>#es 十分的耗内存<br>#es 的数据一般都放置到安全目录,<br>#--net somework 网络配置#docker run -d --name elasticsearch --net somenetwork -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:tag<br>#启动docker容器服务<br>[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker run -d --name elasticsearch -p 9200:9200 -p 9300:9300 -e "discovery.type=single-node" elasticsearch:7.6.2 <br>Unable to find image 'elasticsearch:7.6.2' locally<br>7.6.2: Pulling from library/elasticsearch<br>ab5ef0e58194: Pull complete <br>c4d1ca5c8a25: Pull complete <br>941a3cc8e7b8: Pull complete <br>43ec483d9618: Pull complete <br>c486fd200684: Pull complete <br>1b960df074b2: Pull complete <br>1719d48d6823: Pull complete <br>Digest: sha256:1b09dbd93085a1e7bca34830e77d2981521a7210e11f11eda997add1c12711fa<br>Status: Downloaded newer image for elasticsearch:7.6.2<br>5bed8e09f3e4644ac7f99027810c65d521325bd99a57dd8edb7836f6cbd3d6d1<br>#docker status 查看cpu的状态<br>[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker ps -aq<br>CONTAINER ID   NAME            CPU %     MEM USAGE / LIMIT     MEM %     NET I/O   BLOCK I/O       PIDS<br>ec208095a057   elasticsearch   98.01%    1.244GiB / 1.795GiB   69.34%    0B / 0B   207MB / 246kB   26<br>#关闭当前es容器,增加内存限制,修改配置文件, -e 环境配置修改<br><br>[root@iZ2zec2gz7h1jgw8klihsnZ ~]# curl localhost:9200<br>{<br>  "name" : "71773db7f220",<br>  "cluster_name" : "docker-cluster",<br>  "cluster_uuid" : "3CayxfTES_mRBzO-fDlurw",<br>  "version" : {<br>    "number" : "7.6.2",<br>    "build_flavor" : "default",<br>    "build_type" : "docker",<br>    "build_hash" : "ef48eb35cf30adf4db14086e8aabd07ef6fb113f",<br>    "build_date" : "2020-03-26T06:34:37.794943Z",<br>    "build_snapshot" : false,<br>    "lucene_version" : "8.4.0",<br>    "minimum_wire_compatibility_version" : "6.8.0",<br>    "minimum_index_compatibility_version" : "6.0.0-beta1"<br>  },<br>  "tagline" : "You Know, for Search"<br>}<br>

 es和kibana交互原理

 

 

 可视化

portainer

Docker图形化管理工具,提供一个后台面板供我们操作!

1
2
3
4
5
6
7
8
9
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker run -d -p 3346:9000 --restart=always -v /var/run/docker.sock:/var/run/docker.sock --privileged=true portainer/portainer
Unable to find image 'portainer/portainer:latest' locally
latest: Pulling from portainer/portainer
94cfa856b2b1: Pull complete
49d59ee0881a: Pull complete
a2300fd28637: Pull complete
Digest: sha256:fb45b43738646048a0a0cc74fcee2865b69efde857e710126084ee5de9be0f3f
Status: Downloaded newer image for portainer/portainer:latest
9f66596e5679ff98d0ce8ae51e36dc35d5dcbe489c6750e6f68471217cd55adb

 

Rancher(CI/CD再用)

 

Docker镜像

镜像是什么?

镜像是一个轻量级,可执行的独立软件包,用来打包软件运行环境和基于运行环境开发的软件,它包含某个软件所需的所有内容,包含代码,运行时,库,环境变量和配置文件。

所有的应用,直接打包成为一个docker镜像,就可以直接跑起来!

如何得到镜像?

  • 从远程仓库下载
  • 朋友拷贝给你
  • 自己制作一个镜像DockerFile

镜像加载原理

Docker是一个轻量级的、可执行的独立软件包,将一个应用程序和环境打包成为一个文件包,这个打包好的文件包就是Docker镜像。只有通过镜像文件才能生成容器实例。。镜像文件是分层的,底层采用联合文件系统来实现。


联合文件系统(UnionFS)

联合文件系统是一个轻量级、高性能的文件系统;他支持对文件系统的修改作为一次提交来一层层叠加;同时可以将不同的目录挂载到同一个文件系统下.UnionFs是Docker镜像的基础。可以通过分层来继承基础镜像,提高文件的复用。

 

 

 

 

 

 
Docker镜像加载原理

    bootfs(boot file system) 主要包含bootloader和kernel, bpotloader 主要是引导加载kernel,当我们加载镜像的时候,会通过bootloader加载kernal,Docker镜像最底层是bootfs,当boot加载完成后整个kernal内核都在内存中了,bootfs也就可以卸载,值得注意的是,bootfs是被所有镜像共用的,许多镜像images都是在base image(rootfs)基础上叠加的。

    rootfs (root file system),在bootfs之 上.包含的就是典型Linux系统中的/dev, /proc, /bin, /etc等标准目录和文件。rootfs就是 各种不同的操作系统发行版,比如Ubuntu, Centos等等 。

分层原理介绍

1
2
3
4
5
6
7
8
9
10
11
12
13
[root@iZ2zec2gz7h1jgw8klihsnZ ~]# docker pull redis
Using default tag: latest
latest: Pulling from library/redis
a2abf6c4d29d: Already exists
c7a4e4382001: Pull complete
4044b9ba67c9: Pull complete
c8388a79482f: Pull complete
413c8bb60be2: Pull complete
1abfd3011519: Pull complete
Digest: sha256:db485f2e245b5b3329fdc7eff4eb00f913e09d8feb9ca720788059fdc2ed8339
Status: Downloaded newer image for redis:latest
docker.io/library/redis:latest
[root@iZ2zec2gz7h1jgw8klihsnZ ~]#

 

1
2
3
4
5
6
7
8
#docker inspect redis 看到配置文件中有一个Layers,里面包含       <br>     "Layers": [
                "sha256:2edcec3590a4ec7f40cf0743c15d78fb39d8326bc029073b41ef9727da6c851f",
                "sha256:9b24afeb7c2f21e50a686ead025823cd2c6e9730c013ca77ad5f115c079b57cb",
                "sha256:4b8e2801e0f956a4220c32e2c8b0a590e6f9bd2420ec65453685246b82766ea1",
                "sha256:529cdb636f61e95ab91a62a51526a84fd7314d6aab0d414040796150b4522372",
                "sha256:9975392591f2777d6bf4d9919ad1b2c9afa12f9a9b4d260f45025ec3cc9b18ed",
                "sha256:8e5669d8329116b8444b9bbb1663dda568ede12d3dbcce950199b582f6e94952"
            ]

 Docker镜像分层原理详解链接

特点

Docker镜像都是只读的,当容器启动时,一个新的可写层被加载到镜像的顶部!

这一层是我们经常说的容器层,容器之下的都叫做镜像层

 

 如何提交(Commit)一个镜像?

  1. 容器数据卷

  2. DockerFile

  3. Docker网络原理

  4. IDEA整合Docker

  5. Docker Compose

  6. Docker Swarm

  7. CI\CD Jenkins

 

posted @   王广元  阅读(159)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 上周热点回顾(2.24-3.2)
分享到:
点击右上角即可分享
微信分享提示