docker基础(一)

相关概念介绍

Docker是一个开源的应用容器引擎,让开发者可以打包他们的应用以及依赖到一个可移植的容器中,然后发布到任何流行的linux机器上,也可以实现虚拟化,容器是完全使用沙箱机制,互相之间不会有任何接口。

Docker有几个重要概念:

  1. dockerfile,配置文件,用来生成docker image
  2. docker image ,交付部署的最小单元
  3. docker命令与API,定义命令与接口,支持第三方系统集成

鲸鱼背上有集装箱
​ 蓝色的海洋----------宿主机系统Windows10
​ 鲸鱼-----------------docker
​ 集装箱---------------容器实例 from 来自我们的镜像模板

Docker的重要组成部分

docker的整个生命周期有三部分组成:镜像(image)+容器(container)+仓库(repository);

docker在contos7下的安装

​ 1、sudo yum install -y yum-utils

​ 2、sudo yum-config-manager
–add-repo
https://download.docker.com/linux/centos/docker-ce.repo

​ 3、sudo yum-config-manager --enable docker-ce-nightly
​ 4、sudo yum-config-manager --enable docker-ce-test
​ 5、yum-config-manager --disable docker-ce-nightly
​ 6、yum install docker-ce docker-ce-cli containerd.io

如果之前安装过docker需要在安装前执行卸载操作:
sudo yum remove docker
docker-client
docker-client-latest
docker-common
docker-latest
docker-latest-logrotate
docker-logrotate
docker-engine

​ 阿里云镜像加速地址:https://9p4r9rjm.mirror.aliyuncs.com
​ 阿里云加速器地址:https://cr.console.aliyun.com/cn-hangzhou/instances/mirrors

​ 在centos7系统中配置加速地址:
​ vim /etc/docker/daemon.json #可能本地没有此文件
​ {
“registry-mirrors”: [“https://9p4r9rjm.mirror.aliyuncs.com”]
​ }

​ systemctl daemon-reload
​ systemctl start docker

如果启动报如下错误:

Job for docker.service failed because start of the service was attempted too often. See “systemctl status docker.service” and “journalctl -xe” for details.

To force a start use “systemctl reset-failed docker.service” followed by “systemctl start docker.service” again.

解决办法:

[root@izuf6d7j6gct081hm8qivez docker]# mv daemon.json daemon.conf 			#重名了配置文件
[root@izuf6d7j6gct081hm8qivez docker]# systemctl restart docker				#重启docker进程
[root@izuf6d7j6gct081hm8qivez docker]# ps aux |grep docker					#查看docker进程
root      6458  3.1  3.5 570520 66760 ?        Ssl  10:22   0:00 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
root      6738  0.0  0.0 112728   968 pts/0    S+   10:22   0:00 grep --color=auto docker

问题解决!

docker是如何工作的

docker是一个Client-Server结构的系统,docker守护进程运行在主机上,然后通过socket连接从客户端访问,守护进程从客户端接收命令并管理运行在主机上的容器,容器,是一个运行时环境,类似于集装箱。

为什么docker比vm快

1)docker有着比虚拟机更少的抽象层。由于docker不需要Hypervisor实现硬件资源虚拟化,运行在docker容器上的程序直接使用的都是实际物理机的硬件资源。因此在CPU、内存利用率上docker将会在效率上有明显优势。
2)docker利用的是宿主机的内核,而不需要Guest OS。因此,当新建容器时,docker不需要和虚拟机一样重新加载一个操作系统内核。仍而避免引寻、加载操作系统内核返个比较费时费资源的过程,当新建一个虚拟机时,
虚拟机软件需要加载Guest OS,返个新建过程是分钟级别的。而docker由于直接利用宿主机的操作系统,则省略了返个过程,因此新建一个docker容器只需要几秒钟。

Docker容器 虚拟机(VM)
操作系统 与宿主机共享OS 宿主机OS上运行虚拟机OS
存储大小 镜像小,便于存储与传输 镜像庞大(vmdk、vdi等)
运行性能 几乎无额外性能损失 操作系统额外的CPU、内存消耗
移植性 轻便、灵活,适用于linux 笨重,与虚拟化技术耦合度高
硬件亲和性 面向软件开发者 面向硬件运维者
部署速度 快速,秒级 较慢,10s以上

常见的docker命令

常见docker帮助命令

​ docker version #显示版本信息

​ docker info #显示详细的docker信息

​ docker --help #docker的帮助信息

常见docker镜像命令
[root@host221 ~]# docker images
REPOSITORY					TAG				IMAGE  ID  				CREATE				SIZE
hello-world					latest			bf756fb1ae65			12 months ago		13.3kB

各项说明:

REPOSITORY:表示镜像仓库源

TAG:镜像的标签

IMAGE ID:镜像ID

CREATED:镜像创建时间

SIZE:镜像大小

说明:同一仓库源可以有多个TAG,代表这个仓库源的不同版本,我们使用REPOSITORY:TAG来定义不同的镜像。

如果你不指定一个镜像版本标签,例如你使用ubuntu,docker将默认使用Ubuntu:lastest镜像。后期我们可以操作REPOSITORY或者IMAGE ID。

docker images options说明: #宿主机上的镜像

-a 列出本地所有镜像(含中间映射层)
-q 只列镜像ID
–digests 显示镜像的摘要信息
–no-trunc 显示完整的镜像信息

查看本地已有镜像:

[root@host221 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
tomcat        latest    040bdb29ab37   13 days ago     649MB
nginx         latest    f6d0b4767a6c   2 weeks ago     133MB
centos        latest    300e315adb2f   7 weeks ago     209MB
hello-world   latest    bf756fb1ae65   13 months ago   13.3kB

docker search说明:

-no-trunc 显示完整镜像描述
-s 列出收藏不小于指定值的镜像
-automated 只列出automated build类型的镜像

docker search 某某镜像的名字,如:

[root@host221 ~]# docker search tomcat	

注意:搜索是在htts://hub.docker.com中进行搜索,拉去是从阿里云中进行拉取

[root@host221 ~]# docker search -s 30 tomcat

列出点赞数不少于30的Tomcat

docker pull 拉取镜像说明:

docker pull tomcat 等价于 docker pull Tomcat:latest #latest是最新版,这个默认是省略的,就是默认拉取最新版,如果需要拉取其他版本如:

[root@host221 ~]# docker pull tomcat:5.6

docker rmi 删除镜像:

删除单个镜像 docker rmi 镜像名或者镜像ID
[root@host221 ~]# docker rmi hello-world
Error response from daemon: conflict: unable to remove repository reference "hello-world" (must force) - container 937a42725473 is using its referenced image bf756fb1ae65

强行删除
[root@host221 ~]# docker rmi -f hello-world
Untagged: hello-world:latest
Untagged: hello-world@sha256:31b9c7d48790f0d8c50ab433d9c3b7e17666d6993084c002c2ff1ca09b96391d
Deleted: sha256:bf756fb1ae65adf866bd8c456593cd24beb6a0a061dedf42b26a993176745f6b

删除多个镜像,中间以空格分隔
docker rmi 镜像1 镜像2 ...

全部删除
docker rmi -f $(docker images -qa)		#-qa是查询当前环境所有的ID

注意:如果镜像在运行中是无法删除的,可以通过-f参数强行删除

常见docker 容器命令

新建并启动容器

语法:docker run [OPTIONS] IMAGE [COMMAND] [ARG…]

OPTIONS说明(常用):有些是一个减号,有些是两个减号

–name =“容器新名字”:为容器指定一个名称
-d 后台运行容器,并返回容器ID,也即启动守护式容器
-i 以交互模式运行容器,通常与-t同时使用
-t 为容器重新分配一个伪输入终端,通常与-i同时使用
-P 随机端口映射
-p 指定端口映射

-p 有四种格式:

​ 1.ip:hostPort:containerPort

​ 2.ip::containerPort

​ 3.hostPort:containerPort

​ 4.containerPort

常用的参数:-i -t 一般会写在一起,-it

[root@host221 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
tomcat        latest    040bdb29ab37   2 weeks ago     649MB
nginx         latest    f6d0b4767a6c   2 weeks ago     133MB
centos        latest    300e315adb2f   7 weeks ago     209MB
hello-world   latest    bf756fb1ae65   13 months ago   13.3kB
[root@host221 ~]# docker run -it 300e315adb2f
[root@7f98f4cfb7cf /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@7f98f4cfb7cf /]# 	

此时已经在docker镜像centos的目录中了,所有ls显示的目录也是docker镜像centos的目录

docker ps 命令

默认显示当前正在运行的容器

OPTIONS说明(常用):

-a 列出当前所有正在运行的容器+历史上运行过的
-l 显示最近创建的容器
-n 显示最近n个创建的容器
-q 静默模式,只显示容器编号
-no-trunc 不截断输出

查询有多少个容器在运行

[root@host221 ~]# docker ps
CONTAINER ID   IMAGE          COMMAND       CREATED       STATUS       PORTS     NAMES
4d8e6dd4c3c8   300e315adb2f   "/bin/bash"   9 hours ago   Up 9 hours             practical_pare
[root@4d8e6dd4c3c8 /]# ls
bin  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@4d8e6dd4c3c8 /]# exit					#停止容器并退出
exit
[root@host221 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@host221 ~]# docker ps -l				#查看上一个运行的容器
CONTAINER ID   IMAGE          COMMAND       CREATED       STATUS                     PORTS     NAMES
7f98f4cfb7cf   300e315adb2f   "/bin/bash"   3 hours ago   Exited (130) 2 hours ago             relaxed_bohr
[root@host221 ~]# 
[root@host221 ~]# docker ps -a				#查看现在运行的和原来运行过的
CONTAINER ID   IMAGE          COMMAND       CREATED        STATUS                     PORTS     NAMES
7f98f4cfb7cf   300e315adb2f   "/bin/bash"   3 hours ago    Exited (130) 2 hours ago             relaxed_bohr
4d8e6dd4c3c8   300e315adb2f   "/bin/bash"   11 hours ago   Exited (0) 4 minutes ago             practical_pare
70182ecc8453   hello-world    "/hello"      11 hours ago   Exited (0) 11 hours ago              affectionate_tesla
937a42725473   hello-world    "/hello"      28 hours ago   Exited (0) 28 hours ago              epic_noether
[root@host221 ~]# 
[root@host221 ~]# docker ps -n 2			#把上两次运行的列出来
CONTAINER ID   IMAGE          COMMAND       CREATED        STATUS                     PORTS     NAMES
7f98f4cfb7cf   300e315adb2f   "/bin/bash"   3 hours ago    Exited (130) 2 hours ago             relaxed_bohr
4d8e6dd4c3c8   300e315adb2f   "/bin/bash"   11 hours ago   Exited (0) 7 minutes ago             practical_pare
[root@host221 ~]# 						   #只显示上一个运行容器的ID
[root@host221 ~]# docker ps -ql
7f98f4cfb7cf
[root@host221 ~]# docker run -it --name mycentos0115 centos		#运行docker的centos容器,并起别名为mycentos0115
[root@288c6aaca880 /]# 

docker port命令

在linux命令行查看docker内端口情况

docker port 容器id

退出容器

两种退出方式:

​ 1.exit 容器停止退出

​ 2.ctrl+P+Q 容器不停止退出

启动容器

docker start 容器ID或者容器名

[root@host221 ~]# docker ps -n 2			#查看上两次运行的,可以从STATUS看出来第一个是正在运行的,第二个是停掉的
CONTAINER ID   IMAGE          COMMAND       CREATED          STATUS                     PORTS     NAMES
288c6aaca880   centos         "/bin/bash"   10 minutes ago   Up 10 minutes                        mycentos0115
7f98f4cfb7cf   300e315adb2f   "/bin/bash"   3 hours ago      Exited (130) 3 hours ago             relaxed_bohr
[root@host221 ~]# docker start 7f98f4cfb7cf	 #把第二个停掉的在从新启动
7f98f4cfb7cf
[root@host221 ~]# docker ps
CONTAINER ID   IMAGE          COMMAND       CREATED          STATUS          PORTS     NAMES
288c6aaca880   centos         "/bin/bash"   10 minutes ago   Up 10 minutes             mycentos0115
7f98f4cfb7cf   300e315adb2f   "/bin/bash"   3 hours ago      Up 7 seconds              relaxed_bohr
[root@host221 ~]# 

重启容器

docker restart 容器ID或者容器名

[root@host221 ~]# docker ps
CONTAINER ID   IMAGE          COMMAND       CREATED          STATUS          PORTS     NAMES
288c6aaca880   centos         "/bin/bash"   16 minutes ago   Up 16 minutes             mycentos0115
7f98f4cfb7cf   300e315adb2f   "/bin/bash"   3 hours ago      Up 5 minutes              relaxed_bohr
[root@host221 ~]# docker restart 288c6aaca880	#重启contos容器 
288c6aaca880			#启动完成会返回ID
[root@host221 ~]# docker ps					   #通过时间能判断出来是否重启完成
CONTAINER ID   IMAGE          COMMAND       CREATED          STATUS          PORTS     NAMES
288c6aaca880   centos         "/bin/bash"   17 minutes ago   Up 22 seconds             mycentos0115
7f98f4cfb7cf   300e315adb2f   "/bin/bash"   3 hours ago      Up 6 minutes              relaxed_bohr

停止容器

docker stop 容器ID或者容器名

[root@host221 ~]# docker ps
CONTAINER ID   IMAGE          COMMAND       CREATED          STATUS          PORTS     NAMES
288c6aaca880   centos         "/bin/bash"   17 minutes ago   Up 22 seconds             mycentos0115
7f98f4cfb7cf   300e315adb2f   "/bin/bash"   3 hours ago      Up 6 minutes              relaxed_bohr
[root@host221 ~]# docker stop 288c6aaca880		#停止centos容器
288c6aaca880
[root@host221 ~]# docker ps					   #查看进程已经没有centos的容器了
CONTAINER ID   IMAGE          COMMAND       CREATED       STATUS         PORTS     NAMES
7f98f4cfb7cf   300e315adb2f   "/bin/bash"   3 hours ago   Up 9 minutes             relaxed_bohr
[root@host221 ~]# 

强制停止容器

docker kill 容器ID或者容器名

[root@host221 ~]# docker ps
CONTAINER ID   IMAGE          COMMAND       CREATED       STATUS         PORTS     NAMES
7f98f4cfb7cf   300e315adb2f   "/bin/bash"   3 hours ago   Up 9 minutes             relaxed_bohr
[root@host221 ~]# docker kill 7f98f4cfb7cf		#直接杀死该进程,相对stop比较暴力
7f98f4cfb7cf
[root@host221 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

删除已停掉的容器

docker rm 容器ID

[root@host221 ~]# docker ps -n 2				#查看上两次运行的
CONTAINER ID   IMAGE          COMMAND       CREATED          STATUS                       PORTS     NAMES
288c6aaca880   centos         "/bin/bash"   29 minutes ago   Exited (0) 8 minutes ago               mycentos0115
7f98f4cfb7cf   300e315adb2f   "/bin/bash"   3 hours ago      Exited (137) 4 minutes ago             relaxed_bohr
[root@host221 ~]# docker rm 288c6aaca880		#删除已停止的contos容器
288c6aaca880

一次性删除多个容器

docker rm -f $(docker ps -a -q) 或 docker ps -a -q |xargs docker rm

[root@host221 ~]# docker ps -a -q
7f98f4cfb7cf
4d8e6dd4c3c8
70182ecc8453
937a42725473
[root@host221 ~]# docker rm -f $(docker ps -a -q)	#一次删除全部容器
7f98f4cfb7cf
4d8e6dd4c3c8
70182ecc8453
937a42725473
[root@host221 ~]# docker ps -a -q
[root@host221 ~]#
重要部分

启动守护式容器

docker run -d 容器名

[root@host221 ~]# docker ps 
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@host221 ~]# docker run -d centos			#后台启动centos容器
572ff64b0f4d104de694b5abbc3f40f3075063a32bc65999f8af3a4cc6bb7cb5
[root@host221 ~]# docker ps 					#后台启动后发现查不到centos的进程
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

问题:后台启动一个centos的容器,发现用docker -ps -a进行查看,会发现容器已经退出,很重要的要说明一点:Docker容器后台运行,就必须有一个前台进程,容器运行的命令如果不是那些一直挂起的命令(比如运行top,tail),就是会自动退出的

这个是docker的机制问题,比如你的web容器,我们以nginx为例,正常情况下,我们配置启动服务只需要启动响应的service即可,例如service nginx start

但是,这样,nginx为后台进程模式运行,就导致docker前台没有运行的应用,这样的容器后台启动后,会立即自杀因为他觉得他没事可做了,所以,最佳的解决方案是,将你要运行的程序以前台进程的形式运行

查看容器日志

​ docker logs -f -t --tail 容器ID # -t 是加入时间戳; -f 跟随最新的日志打印; --tail 数字 显示最后多少条

查看容器内部进程

docker top 容器ID

[root@host221 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
2cc8820777b1   centos    "/bin/sh -c 'while t…"   3 minutes ago   Up 3 minutes             interesting_wiles
[root@host221 ~]# docker top 2cc8820777b1			#查看容器内部运行的进程
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                9307                9285                0                   10:30               ?                   00:00:00            /bin/sh -c while true; do echo hello world; sleep 2; done
root                17767               9307                0                   10:34               ?                   00:00:00            /usr/bin/coreutils --coreutils-prog-shebang=sleep /usr/bin/sleep 2

查看容器内部细节

docker inspect 容器ID #以json键值对的形式显示容器内的全部细节

[root@host221 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED         STATUS         PORTS     NAMES
2cc8820777b1   centos    "/bin/sh -c 'while t…"   8 minutes ago   Up 8 minutes             interesting_wiles
[root@host221 ~]# docker inspect 2cc8820777b1
[
    {
        "Id": "2cc8820777b186bcffd2fd6266f534808bd8b40d0a5175b9a52074b2d97a518a",
        "Created": "2021-01-28T02:30:27.075972956Z",
        "Path": "/bin/sh",
        "Args": [
            "-c",
            "while true; do echo hello world; sleep 2; done"
        ],
        "State": {
            "Status": "running",
            "Running": true,
......

进入正在运行的容器并以命令行交互

docker exec -it 容器ID bashShell #在容器外执行容器内的命令

[root@host221 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
7ffd7d95f2f8   centos    "/bin/bash"   4 minutes ago   Up 4 minutes             vibrant_proskuriakova
[root@host221 ~]# docker exec -t 7ffd7d95f2 ls -l /tmp		#在容器外(宿主机)执行容器内的命令
total 8
-rwx------ 1 root root 701 Dec  4 17:37 ks-script-esd4my7v
-rwx------ 1 root root 671 Dec  4 17:37 ks-script-eusq_sc5
[root@host221 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
7ffd7d95f2f8   centos    "/bin/bash"   9 minutes ago   Up 9 minutes             vibrant_proskuriakova
[root@host221 ~]# docker exec -t 7ffd7d95f2f8 /bin/bash		#exec也可以直接进入容器内
[root@7ffd7d95f2f8 /]# 

重新进入docker attach 容器ID

[root@host221 ~]# docker run -it centos					#运行centos的容器
[root@7ffd7d95f2f8 /]# [root@host221 ~]# 				#ctrl+p+q切到后台运行
[root@host221 ~]# docker ps							   #查看centos的容器正在运行
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
7ffd7d95f2f8   centos    "/bin/bash"   49 seconds ago   Up 48 seconds             vibrant_proskuriakova
[root@host221 ~]# docker attach 7ffd7d95f2f8			#重新进入centos的容器
[root@7ffd7d95f2f8 /]# 

上述两个区别:

​ attach 直接进入容器启动命令终端,不会启动新的进程

​ exec 是在容器中打开新的终端,并且可以启动新的进程

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

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

[root@host221 ~]# ll				#查看宿主机root目录下的文件
总用量 197476
-rw-------. 1 root root      1323 8月  11 2019 anaconda-ks.cfg
drwxr-xr-x  9 root root       220 12月 12 21:38 apache-tomcat-8.5.60
-rw-r--r--  1 root root  10488933 12月 11 18:20 apache-tomcat-8.5.60.tar.gz
-rwxr-xr-x  1 root root      5532 12月 11 16:50 install_nginx_v0.0.2.sh
-rw-r--r--  1 root root 191710050 12月 12 20:23 jdk1.8.0_191.tgz
drwxr-xr-x  2 root root         6 1月   1 16:16 jenkins
[root@host221 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
7ffd7d95f2f8   centos    "/bin/bash"   22 minutes ago   Up 21 minutes             vibrant_proskuriakova
[root@host221 ~]# docker cp 7ffd7d95f2f8:/tmp/a.txt /root	#拷贝容器中tmp目录的a.txt文件到宿主机root目录下
[root@host221 ~]# ll
总用量 197476
-rw-------. 1 root root      1323 8月  11 2019 anaconda-ks.cfg
drwxr-xr-x  9 root root       220 12月 12 21:38 apache-tomcat-8.5.60
-rw-r--r--  1 root root  10488933 12月 11 18:20 apache-tomcat-8.5.60.tar.gz
-rw-r--r--  1 root root         0 1月  28 11:12 a.txt
-rwxr-xr-x  1 root root      5532 12月 11 16:50 install_nginx_v0.0.2.sh
-rw-r--r--  1 root root 191710050 12月 12 20:23 jdk1.8.0_191.tgz
drwxr-xr-x  2 root root         6 1月   1 16:16 jenkins

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

docker cp 宿主机路径/文件 容器ID:容器目录

[root@7ffd7d95f2f8 tmp]# ls									#查看容器tmp路径下文件
a.txt ks-script-esd4my7v  ks-script-eusq_sc5
[root@host221 ~]# docker ps									#查看容器的进程,主要是ID
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
7ffd7d95f2f8   centos    "/bin/bash"   29 minutes ago   Up 29 minutes             vibrant_proskuriakova
[root@host221 ~]# docker cp /root/b.txt 7ffd7d95f2f8:/tmp	   #拷贝宿主机上的b.txt文件到容器tmp
[root@host221 ~]# docker attach 7ffd7d95f2f8
[root@7ffd7d95f2f8 tmp]# ls 
a.txt  b.txt  ks-script-esd4my7v  ks-script-eusq_sc5

镜像

概念

​ 镜像是一种轻量级、可执行的独立软件包,用来打包软件运行环境和基于运行环境开发的软件,它包含某个软件所需的所有内容,包含

​ 代码、运行时、库、环境变量和配置文件。

是什么

docker镜像加载的原理:

​ docker的镜像实际上是由一层一层的文件系统组成,这种层级的文件系统UnionFS

​ bootfs(boot file system)主要包含bootloader和kernel,bootloader主要是引导加载kernel,linux刚启动时会加载bootfs文件系统,在docker镜像的最底层是bootfs。这一层与我们典型的linux/unix系统是一样的,包含boot加载器和内核,当boot加载完成之后整个内核就都在内存中了,此时内存的使用权已由bootfs转交给内核,此时系统也会卸载bootfs。

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

对于一个精简的OS,rootfs可以很小,只需要包括最基本的命令、工具和程序库就可以了,因为底层直接用Host的kernel,自己只需要提供rootfs就行了。由此可一件对于不同的linux发行版,bootfs基本是一致的,rootfs会有差别,因此不同的发行版可以共用bootfs。

特点

​ Docker镜像都是只读的。当容器启动时,一个新的可写层被加载到镜像的顶部。这一层通常被称作“容器”,“容器层”之下的都叫“镜像层”。

Docker镜像commit操作补充

​ docker commit提交容器副本使之成为一个新的镜像;docker commit -m=“提交的描述信息” -a=“作者” 容器ID要创建的目标镜像名:[标签名]

案例

从hub上下载tomcat镜像到本地并成功运行

docker run -it -p 8999:80 nginx

​ -p(小p) 主机端口:docker容器端口

​ -P (大P)随机分配端口

[root@host221 ~]# docker run -it -p 8999:80 nginx		#启动nginx容器,映射宿主机的8999端口
/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: Getting the checksum of /etc/nginx/conf.d/default.conf
10-listen-on-ipv6-by-default.sh: info: Enabled listen on IPv6 in /etc/nginx/conf.d/default.conf
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
192.168.21.1 - - [28/Jan/2021:07:40:10 +0000] "GET / HTTP/1.1" 200 612 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" "-"
2021/01/28 07:40:10 [error] 29#29: *1 open() "/usr/share/nginx/html/favicon.ico" failed (2: No such file or directory), client: 192.168.21.1, server: localhost, request: "GET /favicon.ico HTTP/1.1", host: "192.168.21.130:8999", referrer: "http://192.168.21.130:8999/"
192.168.21.1 - - [28/Jan/2021:07:40:10 +0000] "GET /favicon.ico HTTP/1.1" 404 555 "http://192.168.21.130:8999/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36" "-"

然后在输入宿主机IP+8999端口可以访问到容器的nginx服务

进入到运行的nginx容器中:

[root@host221 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                  NAMES
38ec3b886394   nginx     "/docker-entrypoint.…"   21 minutes ago   Up 21 minutes   0.0.0.0:8999->80/tcp   intelligent_mahavira
[root@host221 ~]# docker exec -it 38ec3b886394 /bin/bash		#进入到nginx的容器中
root@38ec3b886394:/# pwd
/

用原理的nginx镜像生成一个改过的nginx镜像,命名为mynginx1.2

[root@host221 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                  NAMES
f248815493f6   nginx     "/docker-entrypoint.…"   21 seconds ago   Up 20 seconds   0.0.0.0:8777->80/tcp   elegant_varahamihira
[root@host221 ~]# docker commit -a="gxy" -m="nginx new" f248815493f6 atg/mynginx:1.2
sha256:26eae4e26713855a2fd7a721dc31eb753e1649edd63678ee06f494d8e8970225
[root@host221 ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
atg/mynginx   1.2       26eae4e26713   7 seconds ago   133MB
tomcat        latest    040bdb29ab37   2 weeks ago     649MB
nginx         latest    f6d0b4767a6c   2 weeks ago     133MB
centos        latest    300e315adb2f   7 weeks ago     209MB
hello-world   latest    bf756fb1ae65   13 months ago   13.3kB

停掉所有正在运行的容器实例

[root@host221 ~]# docker ps						#有两个在运行
CONTAINER ID   IMAGE             COMMAND                  CREATED          STATUS          PORTS                  NAMES
508f3337fa2e   nginx             "/docker-entrypoint.…"   55 seconds ago   Up 54 seconds   0.0.0.0:8666->80/tcp   quirky_moser
cdd10749293f   atg/mynginx:1.2   "/docker-entrypoint.…"   3 minutes ago    Up 3 minutes    0.0.0.0:8999->80/tcp   hopeful_wilbur
[root@host221 ~]# docker rm -f $(docker ps -q)	  #停掉所有正在运行的实例
508f3337fa2e
cdd10749293f
[root@host221 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES

后台运行容器:

docker run -d -p 8666:80 nginx

[root@host221 ~]# docker run -d -p 8666:80 nginx		#后台运行nginx容器,映射宿主机的8666端口
d0068951f895265fa0c40fab7181bf3366025f1aaedac5524a9968f434ce3f61
[root@host221 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND                  CREATED          STATUS          PORTS                  NAMES
d0068951f895   nginx     "/docker-entrypoint.…"   10 seconds ago   Up 10 seconds   0.0.0.0:8666->80/tcp   happy_hertz
[root@host221 ~]# 

Docker容器数据卷

是什么

先来看下docker的理念:

​ 将运用与运行的环境进行打包形成容器运行,运行可以伴随着容器,但是我们对数据的要求希望是持久化的

​ 容器之间希望有可能共享数据

​ docker容器产生的数据,如果不通过docker commit生成新的镜像,使得数据作为镜像的一部分保存下来,那么当容器删除后,数据自然也就没有了。

​ 为了能保存数据在docker中我们使用卷。

能干嘛

卷就是我们的目录或文件,存在于一个或多个容器中,有docker挂载到容器,但不属于联合文件系统,因此能够绕过Union File System提供一些用于持续存储或共享数据的特性:

卷的设计目的就是数据的持久化,完全独立于容器的生存周期,因此Docker不会在容器删除时删除其挂在的数据卷

特点

  1. 数据卷可在容器之间共享或重用数据
  2. 卷中的更改可以直接生效
  3. 数据卷中的更改不会包含在镜像的更新中
  4. 数据卷的生命周期一直持续到没有容器使用它为止

容器的持久化

容器间的继承+共享数据

数据卷

​ 容器内添加:

​ 直接命令添加

​ 命令:docker run -it -v /宿主机绝对路径目录:/容器内目录 镜像名

容器:
[root@host221 ~]# docker run -it -v /myDataVolume:/dataVolumeContainer centos		#在宿主机和容器创建对应目录
[root@0e9f35ee1d07 /]# ls
bin  dataVolumeContainer  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
宿主机:
[root@host221 ~]# ls /
bin  boot  data  dev  etc  home  lib  lib64  media  mnt  myDataVolume  opt  proc  root  run  sbin  srv  sys  tmp  usr  var

注意:原宿主机是没有myDataVolume目录,容器中也没有dataVolumeContainer目录,-v就相当于mkdir

​ 查看数据卷是否挂载成功

通过docker inspect 命令查看绑定关系
[root@host221 ~]# docker ps
CONTAINER ID   IMAGE     COMMAND       CREATED         STATUS         PORTS     NAMES
0e9f35ee1d07   centos    "/bin/bash"   6 minutes ago   Up 6 minutes             serene_varahamihira
[root@host221 ~]# docker inspect 0e9f35ee1d07
......
"HostConfig": {
            "Binds": [
                "/myDataVolume:/dataVolumeContainer"			#通过主机配置信息能看出来绑定关系
            ],
......
 "Mounts": [
            {
                "Type": "bind",
                "Source": "/myDataVolume",
                "Destination": "/dataVolumeContainer",
                "Mode": "",
                "RW": true,									 #说明现在对容器中的dataVolumeContainer目录具有读写权限
                "Propagation": "rprivate"
            }
        ],
 ......

​ 容器和宿主机之间数据共享

在宿主机上的myDataVolume中创建host.txt文件
[root@host221 /]# cd myDataVolume/
[root@host221 myDataVolume]# ls
[root@host221 myDataVolume]# mkdir host.txt

在容器dataVolumeContainer目录中查看是否生成host.txt文件
[root@0e9f35ee1d07 dataVolumeContainer]# ls
host.txt

同样在容器的dataVolumeContainer目录创建a.txt
[root@0e9f35ee1d07 dataVolumeContainer]# mkdir a.txt
[root@0e9f35ee1d07 dataVolumeContainer]# ls
a.txt  host.txt

在宿主机上myDataVolume目录中查看a.txt是否同步
[root@host221 myDataVolume]# ls
a.txt  host.txt	
在对容器中dataVolumeContainer目录中的a.txt和host进行修改,宿主机对应绑定的目录下的文件也会随之修改,反之一样

​ 容器停止退出后,主机修改后数据是否同步

[root@host221 myDataVolume]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
停掉容器只会在主机对应的myDataVolume目录中追加内容为1-6的b.txt的文件
[root@host221 myDataVolume]# echo "123456" >b.txt
启动容器
[root@host221 myDataVolume]# docker ps -l
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS         PORTS     NAMES
0e9f35ee1d07   centos    "/bin/bash"   42 minutes ago   Up 6 minutes             serene_varahamihira
[root@host221 myDataVolume]# docker start 0e9f35ee1d07
0e9f35ee1d07
进入容器
[root@host221 ~]# docker attach 0e9f35ee1d07
[root@0e9f35ee1d07 /]# cd dataVolumeContainer/
[root@0e9f35ee1d07 dataVolumeContainer]# ls
a.txt  b.txt  host.txt
总结:当容器停止后,更新宿主机上绑定目录下文件,启动容器后仍会进行数据同步

​ 命令(带权限)

将容器停掉,把容器和宿主机上的对应目录全部删掉,从新创建
[root@host221 /]# docker run -it -v /myDataVolume:/dataVolumeContainer:ro centos		#重新创建对应同步目录,ro=read only
[root@host221 myDataVolume]# echo "123"> c.txt					#创建内容为123的文件
在容器端查看
[root@host221 ~]# docker ps 
CONTAINER ID   IMAGE     COMMAND       CREATED          STATUS          PORTS     NAMES
ee6d8e64b852   centos    "/bin/bash"   24 seconds ago   Up 23 seconds             jovial_spence
[root@host221 ~]# docker attach ee6d8e64b852
[root@ee6d8e64b852 /]# ls
bin  dataVolumeContainer  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
[root@ee6d8e64b852 dataVolumeContainer]# touch d.txt
touch: cannot touch 'd.txt': Read-only file system
[root@ee6d8e64b852 dataVolumeContainer]# cat c.txt 
123
总结:容器中只有读权限,无法编辑文件和创建文件

​ DockerFile添加(可以在容器内添加多个)

编辑Dockerfile文件

# volume ttest
FROM centos												#基于centos镜像
VOLUME ["/dataVolumeContainer1","/dataVolumeContainer2"]	#在容器内创建两个同步目录
CMD echo "finished,--------success1"					   #完成后打印success消息
CMD /bin/bash
说明:就是在容器内部创建两个共享目录

用DockerFile在容器内添加多个同步文件夹

[root@izuf6d7j6gct081hm8qivez mydocker]# docker build -f /mydocker/Dockerfile -t gxy/centos .	#-f是文件的意思
Sending build context to Docker daemon  2.048kB
Step 1/4 : FROM centos
 ---> 300e315adb2f
Step 2/4 : VOLUME ["/dataVolumeContainer1","/dataVolumeContainer2"]
 ---> Running in 9aefefd69937
Removing intermediate container 9aefefd69937
 ---> 46e94e284d80
Step 3/4 : CMD echo "finished,--------success1"
 ---> Running in 27a7c201cef4
Removing intermediate container 27a7c201cef4
 ---> 35ac5c0f29d0
Step 4/4 : CMD /bin/bash
 ---> Running in e935c6153112
Removing intermediate container e935c6153112
 ---> 442d7713764e
Successfully built 442d7713764e
Successfully tagged gxy/centos:latest

从上边的命令我们可以看出来是没有在宿主机上创建文件同步夹的

查看镜像文件,发现刚才构建好的镜像已经在镜像列表中了
[root@izuf6d7j6gct081hm8qivez mydocker]# docker images
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
gxy/centos   latest    442d7713764e   3 hours ago   209MB
centos       latest    300e315adb2f   7 weeks ago   209MB
启动构建好的容器
[root@izuf6d7j6gct081hm8qivez mydocker]# docker images gxy/centos
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
gxy/centos   latest    442d7713764e   3 hours ago   209MB
[root@izuf6d7j6gct081hm8qivez mydocker]# docker run -it gxy/centos
[root@a066d630f0a1 /]# ls
bin  dataVolumeContainer1  dataVolumeContainer2  dev  etc  home  lib  lib64  lost+found  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
可以看到我们刚才创建的两个目录已在容器中生成

查看在宿主机上生成的同步目录

[root@izuf6d7j6gct081hm8qivez ~]# docker ps
CONTAINER ID   IMAGE        COMMAND                  CREATED          STATUS          PORTS     NAMES
a066d630f0a1   gxy/centos   "/bin/sh -c /bin/bash"   11 minutes ago   Up 11 minutes             heuristic_rosalind
[root@izuf6d7j6gct081hm8qivez ~]# docker inspect a066d630f0a1
"Mounts": [
            {
                "Type": "volume",
                "Name": "09fe41d1dabe056a42eb056d14fda256e03866f5faca71cd9614a96ac0ec1be7",
                "Source": "/var/lib/docker/volumes/09fe41d1dabe056a42eb056d14fda256e03866f5faca71cd9614a96ac0ec1be7/_data",
                "Destination": "/dataVolumeContainer1",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            },
            {
                "Type": "volume",
                "Name": "5d6e16470035d159d0be28976011c970b6aed1e4e684eeaf30153522042990d0",
                "Source": "/var/lib/docker/volumes/5d6e16470035d159d0be28976011c970b6aed1e4e684eeaf30153522042990d0/_data",
                "Destination": "/dataVolumeContainer2",
                "Driver": "local",
                "Mode": "",
                "RW": true,
                "Propagation": ""
            }
        ],
可以看到宿主机目录为/var/lib/docker/volumes/5d6e16470035d159d0be28976011c970b6aed1e4e684eeaf30153522042990d0/_data

用DockerFile自定义的镜像文件可以自定义,例如如上添加两个同步文件的操作

进入宿主机查看是否生成该目录

[root@izuf6d7j6gct081hm8qivez ~]# cd /var/lib/docker/volumes/5d6e16470035d159d0be28976011c970b6aed1e4e684eeaf30153522042990d0/_data
[root@izuf6d7j6gct081hm8qivez _data]# pwd
/var/lib/docker/volumes/5d6e16470035d159d0be28976011c970b6aed1e4e684eeaf30153522042990d0/_data

查看是否进行数据同步

在容器上创建文件
[root@a066d630f0a1 dataVolumeContainer2]# echo "123">host.txt
在宿主机上查看是否同步
[root@izuf6d7j6gct081hm8qivez _data]# ls
host.txt
[root@izuf6d7j6gct081hm8qivez _data]# cat host.txt 
123
[root@izuf6d7j6gct081hm8qivez _data]# pwd
/var/lib/docker/volumes/5d6e16470035d159d0be28976011c970b6aed1e4e684eeaf30153522042990d0/_data
已同步

DockerFile

是什么

​ DockerFile是用来构建docker镜像的构建文件,是由一系列的命令和参数构成的脚本。

三步骤

​ 手动写一个DockerFile文件,当然,必须要符合file的规范 #编写

​ 有这个文件后,直接docker build命令执行,获得一个自定义的镜像 #构建

​ run #执行

​ dockerfile 以centos为例的官方file文件

FROM scratch
ADD centos-7-x86_64-docker.tar.xz /

LABEL \
    org.label-schema.schema-version="1.0" \
    org.label-schema.name="CentOS Base Image" \
    org.label-schema.vendor="CentOS" \
    org.label-schema.license="GPLv2" \
    org.label-schema.build-date="20201113" \
    org.opencontainers.image.title="CentOS Base Image" \
    org.opencontainers.image.vendor="CentOS" \
    org.opencontainers.image.licenses="GPL-2.0-only" \
    org.opencontainers.image.created="2020-11-13 00:00:00+00:00"

CMD ["/bin/bash"]
DockerFile构建过程解析

dockerfile内容基础知识

	1. 每条保留字指令都必须为大写字母且后面要跟随至少一个参数

 		2. 指令按照从上到下,顺序执行
             		3. 表示注释
            		4. 每条指令都会创建一个新的镜像层,并对镜像进行提交	
DockerFile执行流程
1. docker从基础镜像运行一个容器

2. 执行一条指令并对容器做出修改
3. 执行类似docker commit的操作提交一个新的镜像层
4. docker再基于刚提交的镜像运行一个新的容器
5. 执行DockerFile中的下一条指令知道所有指令都执行完成
小结

从应用软件的角度来看,DockerFile、Docker镜像与Docker容器分别代表软件的三个不同阶段

- DockerFile是软件的原材料
- docker镜像是软件的交付品
- docker容器则可以人事是软件运行态

Dockerfile面向开发,Docker镜像成为交付标准,Docker容器则涉及部署与运维,三者缺一不可,合力充当Docker体系的基石。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-hyGQlNZi-1617693557411)(F:\typora相关笔记\DockerFile.jpg)]

DockerFile体系结构(保留字指令)
FROM 基础镜像,当前新镜像是基于那个镜像的
MAINTAINER 镜像维护者的姓名和邮箱地址
RUN 容器构建时需要运行的命令
EXPOSE 当前容器对外暴露出的端口号
WORKDIR 指定在创建容器后,终端默认登录的进来工作目录,一个落脚点
ENV 用来在构建镜像过程中设置环境变量
ADD 将宿主机目录下的文件拷贝镜像且ADD命令会自动处理URL和解压tar压缩包
COPY 类似ADD,拷贝文件和目录到镜像中。将从构建上下文目录中<源路径>的文件/目录复制到新的一层的镜像内的<目标路径>位置
VOLUME 容器数据卷,用户数据保存和持久化工作
CMD 指定一个容器启动时要运行的命令。DockerFile中可以有多个CMD指令,但只有一个最后生效,CMD会被docker run之后的参数替换
ENTRYPOINT 指定一个容器启动时要运行的命令。ENTRYPOINT 的目的的和CMD一样,都是在指定容器期启动程序及参数
ONBUILD 更新到typora,请在typora中参考

ENV:例如:

ENV MY_PATH /usr/mytest

这个环境变量可以在后续的任何RUN指令中使用,这就是如同在命令前面制定了环境变量前缀一样;

比如:WORKEDIR $MY_PATH

COPY:

COPY src dest

COPY[“src”,“dest”]

CMD:

CMD容器启动命令

CMD 指令的格式和 RUN类似,也是两种格式:

shell 格式:CMD<命令>

exec 格式:CMD [“可执行文件”,“参数1”,“参数2”…]

参数列表格式:CMD [“参数1”,“参数2”…]。在指定了 ENTRYPOINT指令后,用CMD指定具体的参数

最后一个CMD的命令是替换之前所有的,只有最后一个生效

ENTRYPOINT:

最后添加的不会把之前的替换掉,而是直接追加

小结:

BUILD Both RUN
FROM WORKDIR CMD
MAINTAINER USER ENV
COPY EXPOSE
ADD VOLUME
RUN ENTRYPOINT
ONBUILD
.dockerignore

案例1

编写DockerFile文件

[root@izuf6d7j6gct081hm8qivez ~]# vim DockerFile 
from centos
ENV mypath /usr/local
WORKDIR $mypath

RUN yum -y install vim
RUN yum -y install net-tools

EXPOSE 80

CMD /echo $pypath
CMD /echo "success-----ok"
CMD /bin/bash

构建docker镜像

[root@izuf6d7j6gct081hm8qivez ~]# docker build -f /root/DockerFile -t mycentos:1.3 .
Sending build context to Docker daemon  720.4MB
Step 1/9 : from centos
 ---> 300e315adb2f
Step 2/9 : ENV mypath /usr/local
 ---> Running in fcf1fb902f35
Removing intermediate container fcf1fb902f35
 ---> 1c129126e6cc
Step 3/9 : WORKDIR $mypath
 ---> Running in 6925f8a5ead5
Removing intermediate container 6925f8a5ead5
 ---> 082f63f9889f
Step 4/9 : RUN yum -y install vim
 ---> Running in 749b6bbfdfe4
CentOS Linux 8 - AppStream                      2.7 MB/s | 6.3 MB     00:02    
CentOS Linux 8 - BaseOS                         1.5 MB/s | 2.3 MB     00:01    
CentOS Linux 8 - Extras                         4.3 kB/s | 8.6 kB     00:02    
Dependencies resolved.
================================================================================
 Package             Arch        Version                   Repository      Size
================================================================================
Installing:
 vim-enhanced        x86_64      2:8.0.1763-15.el8         appstream      1.4 M
Installing dependencies:
 gpm-libs            x86_64      1.20.7-15.el8             appstream       39 k
 vim-common          x86_64      2:8.0.1763-15.el8         appstream      6.3 M
 vim-filesystem      noarch      2:8.0.1763-15.el8         appstream       48 k
 which               x86_64      2.21-12.el8               baseos          49 k

Transaction Summary
================================================================================
Install  5 Packages

Total download size: 7.8 M
Installed size: 30 M
Downloading Packages:
(1/5): gpm-libs-1.20.7-15.el8.x86_64.rpm        215 kB/s |  39 kB     00:00    
(2/5): vim-filesystem-8.0.1763-15.el8.noarch.rp 707 kB/s |  48 kB     00:00    
(3/5): which-2.21-12.el8.x86_64.rpm             633 kB/s |  49 kB     00:00    
(4/5): vim-enhanced-8.0.1763-15.el8.x86_64.rpm  1.5 MB/s | 1.4 MB     00:00    
(5/5): vim-common-8.0.1763-15.el8.x86_64.rpm    4.5 MB/s | 6.3 MB     00:01    
--------------------------------------------------------------------------------
Total                                           2.3 MB/s | 7.8 MB     00:03     
warning: /var/cache/dnf/appstream-02e86d1c976ab532/packages/gpm-libs-1.20.7-15.el8.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 8483c65d: NOKEY
CentOS Linux 8 - AppStream                      1.6 MB/s | 1.6 kB     00:00    
Importing GPG key 0x8483C65D:
 Userid     : "CentOS (CentOS Official Signing Key) "
 Fingerprint: 99DB 70FA E1D7 CE22 7FB6 4882 05B5 55B3 8483 C65D
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
Key imported successfully
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                        1/1 
  Installing       : which-2.21-12.el8.x86_64                               1/5 
  Installing       : vim-filesystem-2:8.0.1763-15.el8.noarch                2/5 
  Installing       : vim-common-2:8.0.1763-15.el8.x86_64                    3/5 
  Installing       : gpm-libs-1.20.7-15.el8.x86_64                          4/5 
  Running scriptlet: gpm-libs-1.20.7-15.el8.x86_64                          4/5 
  Installing       : vim-enhanced-2:8.0.1763-15.el8.x86_64                  5/5 
  Running scriptlet: vim-enhanced-2:8.0.1763-15.el8.x86_64                  5/5 
  Running scriptlet: vim-common-2:8.0.1763-15.el8.x86_64                    5/5 
  Verifying        : gpm-libs-1.20.7-15.el8.x86_64                          1/5 
  Verifying        : vim-common-2:8.0.1763-15.el8.x86_64                    2/5 
  Verifying        : vim-enhanced-2:8.0.1763-15.el8.x86_64                  3/5 
  Verifying        : vim-filesystem-2:8.0.1763-15.el8.noarch                4/5 
  Verifying        : which-2.21-12.el8.x86_64                               5/5 

Installed:
  gpm-libs-1.20.7-15.el8.x86_64         vim-common-2:8.0.1763-15.el8.x86_64    
  vim-enhanced-2:8.0.1763-15.el8.x86_64 vim-filesystem-2:8.0.1763-15.el8.noarch
  which-2.21-12.el8.x86_64             

Complete!
Removing intermediate container 749b6bbfdfe4
 ---> 74f019b66158
Step 5/9 : RUN yum -y install net-tools
 ---> Running in 41010c643566
Last metadata expiration check: 0:00:15 ago on Tue Feb  2 01:24:09 2021.
Dependencies resolved.
================================================================================
 Package         Architecture Version                        Repository    Size
================================================================================
Installing:
 net-tools       x86_64       2.0-0.52.20160912git.el8       baseos       322 k

Transaction Summary
================================================================================
Install  1 Package

Total download size: 322 k
Installed size: 942 k
Downloading Packages:
net-tools-2.0-0.52.20160912git.el8.x86_64.rpm   3.1 MB/s | 322 kB     00:00    
--------------------------------------------------------------------------------
Total                                           681 kB/s | 322 kB     00:00     
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                        1/1 
  Installing       : net-tools-2.0-0.52.20160912git.el8.x86_64              1/1 
  Running scriptlet: net-tools-2.0-0.52.20160912git.el8.x86_64              1/1 
  Verifying        : net-tools-2.0-0.52.20160912git.el8.x86_64              1/1 

Installed:
  net-tools-2.0-0.52.20160912git.el8.x86_64                                     

Complete!
Removing intermediate container 41010c643566
 ---> 9ade25dfe857
Step 6/9 : EXPOSE 80
 ---> Running in 065dee6f55a4
Removing intermediate container 065dee6f55a4
 ---> 48bebddd24ab
Step 7/9 : CMD /echo $pypath
 ---> Running in 11483efc093c
Removing intermediate container 11483efc093c
 ---> 25ecbac09089
Step 8/9 : CMD /echo "success-----ok"
 ---> Running in 2e10106de7a7
Removing intermediate container 2e10106de7a7
 ---> dbd52bd4af5e
Step 9/9 : CMD /bin/bash
 ---> Running in 108fe7bc8155
Removing intermediate container 108fe7bc8155
 ---> 51e3e67533a3
Successfully built 51e3e67533a3
Successfully tagged mycentos:1.3
[root@izuf6d7j6gct081hm8qivez ~]# 

查看构建好的镜像

[root@izuf6d7j6gct081hm8qivez ~]# docker images mycentos
REPOSITORY   TAG       IMAGE ID       CREATED         SIZE
mycentos     1.3       51e3e67533a3   4 minutes ago   291MB

运行新构建的镜像

[root@izuf6d7j6gct081hm8qivez ~]# docker run -it mycentos:1.3
[root@f3ec66329787 local]# pwd
/usr/local

查看是否可以使用vim

[root@f3ec66329787 local]# vim test.txt
[root@f3ec66329787 local]# ls 
bin  etc  games  include  lib  lib64  libexec  sbin  share  src  test.txt
[root@f3ec66329787 local]# cat test.txt 
fdsaf

ifconfig同样可以使用,这里就不做过多演示了

列出镜像的变更历史

docker history 镜像名

[root@izuf6d7j6gct081hm8qivez ~]# docker images mycentos
REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
mycentos     1.3       51e3e67533a3   13 minutes ago   291MB
[root@izuf6d7j6gct081hm8qivez ~]# docker history 51e3e67533a3
IMAGE          CREATED          CREATED BY                                      SIZE      COMMENT
51e3e67533a3   13 minutes ago   /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "/bin…   0B        
dbd52bd4af5e   13 minutes ago   /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "/ech…   0B        
25ecbac09089   13 minutes ago   /bin/sh -c #(nop)  CMD ["/bin/sh" "-c" "/ech…   0B        
48bebddd24ab   13 minutes ago   /bin/sh -c #(nop)  EXPOSE 80                    0B        
9ade25dfe857   13 minutes ago   /bin/sh -c yum -y install net-tools             23.3MB    
74f019b66158   13 minutes ago   /bin/sh -c yum -y install vim                   58.1MB    
082f63f9889f   14 minutes ago   /bin/sh -c #(nop) WORKDIR /usr/local            0B        
1c129126e6cc   14 minutes ago   /bin/sh -c #(nop)  ENV mypath=/usr/local        0B        
300e315adb2f   8 weeks ago      /bin/sh -c #(nop)  CMD ["/bin/bash"]            0B        
      8 weeks ago      /bin/sh -c #(nop)  LABEL org.label-schema.sc…   0B        
      8 weeks ago      /bin/sh -c #(nop) ADD file:bd7a2aed6ede423b7…   209MB
# docker run -it -p 7777:8080 tomcat ls -l 等价于 ls -l /usr/local/tomcat ls -l会覆盖掉之前的启动命令,tomcat不会启动,只会查看tomcat目录
[root@izuf6d7j6gct081hm8qivez ~]# docker run -it -p 7777:8080 tomcat ls -l
total 156
-rw-r--r-- 1 root root 18982 Dec  3 11:48 BUILDING.txt
-rw-r--r-- 1 root root  5409 Dec  3 11:48 CONTRIBUTING.md
-rw-r--r-- 1 root root 57092 Dec  3 11:48 LICENSE
-rw-r--r-- 1 root root  2333 Dec  3 11:48 NOTICE
-rw-r--r-- 1 root root  3257 Dec  3 11:48 README.md
-rw-r--r-- 1 root root  6898 Dec  3 11:48 RELEASE-NOTES
-rw-r--r-- 1 root root 16507 Dec  3 11:48 RUNNING.txt
drwxr-xr-x 2 root root  4096 Feb  1 23:24 bin
drwxr-xr-x 2 root root  4096 Dec  3 11:48 conf
drwxr-xr-x 2 root root  4096 Feb  1 23:24 lib
drwxrwxrwx 2 root root  4096 Dec  3 11:43 logs
drwxr-xr-x 2 root root  4096 Feb  1 23:24 native-jni-lib
drwxrwxrwx 2 root root  4096 Feb  1 23:24 temp
drwxr-xr-x 2 root root  4096 Feb  1 23:24 webapps
drwxr-xr-x 7 root root  4096 Dec  3 11:45 webapps.dist
drwxrwxrwx 2 root root  4096 Dec  3 11:43 work

案例2

编写DockerFile文件

[root@izuf6d7j6gct081hm8qivez ~]# vim DockerFile2
FROM centos
RUN yum install -y curl
CMD [ "curl","-s","http://ip.cn" ]

构建docker镜像

[root@izuf6d7j6gct081hm8qivez ~]# docker build -f /root/DockerFile2 -t myip .
Sending build context to Docker daemon  720.4MB
Step 1/3 : FROM centos
 ---> 300e315adb2f
Step 2/3 : RUN yum install -y curl
 ---> Running in 449caac34afb
CentOS Linux 8 - AppStream                      3.6 MB/s | 6.3 MB     00:01    
CentOS Linux 8 - BaseOS                         2.3 MB/s | 2.3 MB     00:00    
CentOS Linux 8 - Extras                         9.3 kB/s | 8.6 kB     00:00    
Package curl-7.61.1-14.el8.x86_64 is already installed.
Dependencies resolved.
================================================================================
 Package               Architecture Version                  Repository    Size
================================================================================
Upgrading:
 curl                  x86_64       7.61.1-14.el8_3.1        baseos       353 k
 libcurl-minimal       x86_64       7.61.1-14.el8_3.1        baseos       285 k

Transaction Summary
================================================================================
Upgrade  2 Packages

Total download size: 638 k
Downloading Packages:
(1/2): libcurl-minimal-7.61.1-14.el8_3.1.x86_64 2.5 MB/s | 285 kB     00:00    
(2/2): curl-7.61.1-14.el8_3.1.x86_64.rpm        2.5 MB/s | 353 kB     00:00    
--------------------------------------------------------------------------------
Total                                           913 kB/s | 638 kB     00:00     
warning: /var/cache/dnf/baseos-f6a80ba95cf937f2/packages/curl-7.61.1-14.el8_3.1.x86_64.rpm: Header V3 RSA/SHA256 Signature, key ID 8483c65d: NOKEY
CentOS Linux 8 - BaseOS                         345 kB/s | 1.6 kB     00:00    
Importing GPG key 0x8483C65D:
 Userid     : "CentOS (CentOS Official Signing Key) "
 Fingerprint: 99DB 70FA E1D7 CE22 7FB6 4882 05B5 55B3 8483 C65D
 From       : /etc/pki/rpm-gpg/RPM-GPG-KEY-centosofficial
Key imported successfully
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                        1/1 
  Upgrading        : libcurl-minimal-7.61.1-14.el8_3.1.x86_64               1/4 
  Upgrading        : curl-7.61.1-14.el8_3.1.x86_64                          2/4 
  Cleanup          : curl-7.61.1-14.el8.x86_64                              3/4 
  Cleanup          : libcurl-minimal-7.61.1-14.el8.x86_64                   4/4 
  Running scriptlet: libcurl-minimal-7.61.1-14.el8.x86_64                   4/4 
  Verifying        : curl-7.61.1-14.el8_3.1.x86_64                          1/4 
  Verifying        : curl-7.61.1-14.el8.x86_64                              2/4 
  Verifying        : libcurl-minimal-7.61.1-14.el8_3.1.x86_64               3/4 
  Verifying        : libcurl-minimal-7.61.1-14.el8.x86_64                   4/4 

Upgraded:
  curl-7.61.1-14.el8_3.1.x86_64     libcurl-minimal-7.61.1-14.el8_3.1.x86_64    

Complete!
Removing intermediate container 449caac34afb
 ---> 5dc4967f28f7
Step 3/3 : CMD [ "curl","-s","http://ip.cn" ]
 ---> Running in 0c1f550713a0
Removing intermediate container 0c1f550713a0
 ---> 1bd4f1f4b319
Successfully built 1bd4f1f4b319
Successfully tagged myip:latest
[root@izuf6d7j6gct081hm8qivez ~]# 

查看构建好的镜像

[root@izuf6d7j6gct081hm8qivez ~]# docker images myip
REPOSITORY   TAG       IMAGE ID       CREATED              SIZE
myip         latest    1bd4f1f4b319   About a minute ago   243MB

运行时报错

[root@izuf6d7j6gct081hm8qivez ~]# docker run myip -i
docker: Error response from daemon: OCI runtime create failed: container_linux.go:370: starting container process caused: exec: "-i": executable file not found in $PATH: unknown.

why

​ 我们可以看到可执行文件找不到的报错,executable file not found。

​ 之前我们说过,跟在镜像名后边的是command,运行时会替换CMD的默认值。

​ 因此我们这里边的-i 替换了原来的CMD,而不是添加在原来的curl -s http://ip.cn后边。而-i 根本不是命令,所以自然找不到。

​ 那么如果我们希望加入 -i 这个参数,我们就必须重新完整的输入这个命令:

​ $ docker run myip curl -s http://ip.cn -i

制作ENTRYPOINT版查询IP信息容器

[root@izuf6d7j6gct081hm8qivez ~]# vim DockerFile2
FROM centos
RUN yum install -y curl
ENTRYPOINT [ "curl","-s","http://ip.cn" ]

构建

[root@izuf6d7j6gct081hm8qivez ~]# docker build -f /root/DockerFile3 -t myip3 .
Sending build context to Docker daemon  720.4MB
Step 1/3 : FROM centos
 ---> 300e315adb2f
Step 2/3 : RUN yum install -y curl
 ---> Using cache
 ---> 5dc4967f28f7
Step 3/3 : ENTRYPOINT [ "curl","-s","http://ip.cn" ]
 ---> Running in 00b908f11d53
Removing intermediate container 00b908f11d53
 ---> d40be39fb652
Successfully built d40be39fb652
Successfully tagged myip3:latest
[root@izuf6d7j6gct081hm8qivez ~]# ^C
[root@izuf6d7j6gct081hm8qivez ~]# ^C
[root@izuf6d7j6gct081hm8qivez ~]# cat DockerFile3
FROM centos
RUN yum install -y curl
ENTRYPOINT [ "curl","-s","http://ip.cn" ]
[root@izuf6d7j6gct081hm8qivez ~]# 

运行

# 在运行该命令就不会报错了,因为CMD是替换,而ENTRYPOINT是追加
[root@izuf6d7j6gct081hm8qivez ~]# docker run myip3 -i
HTTP/1.1 301 Moved Permanently
Date: Tue, 02 Feb 2021 03:41:05 GMT
Transfer-Encoding: chunked
Connection: keep-alive
Cache-Control: max-age=3600
Expires: Tue, 02 Feb 2021 04:41:05 GMT
Location: https://ip.cn/
cf-request-id: 08026d70d70000368a27841000000001
Report-To: {"endpoints":[{"url":"https:\/\/a.nel.cloudflare.com\/report?s=bAsjdq9x3nHvmVI0vwCVgiPTcG3NXSTy2rUIMGpVR9s8oSX6b2VO%2Fa1fxgG56s1HzpDTi6Uc05AodFZwUMFcLvAYceEG2Q%3D%3D"}],"group":"cf-nel","max_age":604800}
NEL: {"report_to":"cf-nel","max_age":604800}
Server: cloudflare
CF-RAY: 61b0e4fafd45368a-LAX
alt-svc: h3-27=":443"; ma=86400, h3-28=":443"; ma=86400, h3-29=":443"; ma=86400

[root@izuf6d7j6gct081hm8qivez ~]# 

案例3

自定义镜像 Tomcat9

[root@izuf6d7j6gct081hm8qivez /]# mkdir -p /zzyyuse/mydockerfile/tomcat9
[root@izuf6d7j6gct081hm8qivez /]# touch c.txt
[root@izuf6d7j6gct081hm8qivez /]# vim Dockerfile
FROM centos
MAINTAINER      gxy<[email protected]>
#把宿主机当前上下文的c.txt拷贝到容器/usr/local/路径下
COPY c.txt /usr/local/cincontainer.txt
#把java与tomcat添加到容器中
ADD jdk-8u251-linux-x64.tar.gz /usr/local/
ADD apache-tomcat-9.0.41.tar.gz /usr/local/
#安装vim编辑器
RUN yum -y install vim
#设置工作访问时候的workdir路径,登录落脚点
ENV MYPATH /usr/local
WORKDIR $MYPATH
#配置java与tomcat环境变量
ENV JAVA_HOME /usr/local/jdk1.8.0_191
ENV CLASSPATH $JAVA_HOME/lib/dt.jar:$JAVA_HOME/lib/tools.jar
ENV CATALINA_HOME /usr/local/apache-tomcat-9.0.41
ENV CATALINA_BASE /usr/local/apache-tomcat-9.0.41
ENV PATH $PATH:$JAVA_HOME/bin:$CATALINA_HOME/lib:$CATALINA_HOME/bin
#容器运行时监听的端口
EXPOSE  8080
#启动时运行tomcat
# ENTRYPOINT ["/usr/local/apache-tomcat-9.0.41/bin/startup.sh"]
# CMD ["/usr/local/apache-tomcat-9.0.41/bin/catalina.sh","run"]
CMD /usr/local/apache-tomcat-9.0.41/bin/startup.sh && tail -F /usr/local/apache-tomcat-9.0.41/bin/logs/catalina.out

构建

[root@izuf6d7j6gct081hm8qivez tomcat9]# ll
总用量 201740
-rw-r--r-- 1 root root  11442169 2月   2 16:59 apache-tomcat-9.0.41.tar.gz
-rw-r--r-- 1 root root         0 2月   2 14:40 c.txt
-rw-r--r-- 1 root root      1032 2月   2 18:26 Dockerfile
-rw-r--r-- 1 root root 195132576 2月   2 17:02 jdk-8u251-linux-x64.tar.gz
[root@izuf6d7j6gct081hm8qivez tomcat9]# docker build -f Dockerfile -t zzyytomcat9 .
Sending build context to Docker daemon  206.6MB
Step 1/15 : FROM centos
 ---> 300e315adb2f
Step 2/15 : MAINTAINER  gxy<[email protected]>
 ---> Running in 1fe1b230c056
....
Removing intermediate container de7c0f8a1dc7
 ---> a57fd7cbc95b
Successfully built a57fd7cbc95b
Successfully tagged zzyytomcat9:latest
[root@izuf6d7j6gct081hm8qivez tomcat9]# 
构建成功

查看当前构建的镜像

[root@izuf6d7j6gct081hm8qivez tomcat9]# docker images zzyytomcat9
REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
zzyytomcat9   latest    a57fd7cbc95b   5 minutes ago   689MB

根据zzyytomcat9跑一个容器实例

# -d 后台运行 -p 映射端口 -v 添加容器卷 此次一共添加了两个容器卷 --privileged=true 给容器目录写权限打开
[root@izuf6d7j6gct081hm8qivez ~]# docker run -d -p 9080:8080 --name myt9 -v /zzyyuse/mydockerfile/tomcat9/test:/usr/local/apache-tomcat9.0.41/webapps/test -v /zzyyuse/mydockerfile/tomcat9/tomcat9logs/:/usr/local/apache-tomcat9.0.41/logs --privileged=true zzyytomcat9
601511a2f10b1685783dcf20a08fd143e50d4dd27f28b6a64e49cd391fe0772c
[root@izuf6d7j6gct081hm8qivez ~]# docker ps
CONTAINER ID   IMAGE         COMMAND                  CREATED          STATUS          PORTS                    NAMES
601511a2f10b   zzyytomcat9   "/bin/sh -c '/usr/lo…"   12 seconds ago   Up 11 seconds   0.0.0.0:9080->8080/tcp   myt9
[root@izuf6d7j6gct081hm8qivez ~]# docker exec 601511a2f10b ls -l
total 56
drwxr-xr-x 1 root  root  4096 Feb  2 10:31 apache-tomcat-9.0.41
drwxr-xr-x 4 root  root  4096 Feb  3 03:23 apache-tomcat9.0.41
drwxr-xr-x 2 root  root  4096 Nov  3 15:22 bin
-rw-r--r-- 1 root  root     0 Feb  2 06:40 cincontainer.txt
drwxr-xr-x 2 root  root  4096 Nov  3 15:22 etc
drwxr-xr-x 2 root  root  4096 Nov  3 15:22 games
drwxr-xr-x 2 root  root  4096 Nov  3 15:22 include
drwxr-xr-x 7 10143 10143 4096 Mar 12  2020 jdk1.8.0_251
drwxr-xr-x 2 root  root  4096 Nov  3 15:22 lib
drwxr-xr-x 3 root  root  4096 Dec  4 17:37 lib64
drwxr-xr-x 2 root  root  4096 Nov  3 15:22 libexec
drwxr-xr-x 2 root  root  4096 Nov  3 15:22 sbin
drwxr-xr-x 5 root  root  4096 Dec  4 17:37 share
drwxr-xr-x 2 root  root  4096 Nov  3 15:22 src

安装mysql

​ 步骤:

	1. docker hub上面查找mysql镜像

 		2. 从docker hub上(阿里云加速器)拉取mysql镜像到本地标签为5.6
             		3. 使用mysql5.6镜像创建容器(也就运行镜像)

1.从docker hub上面查找mysql镜像

[root@izuf6d7j6gct081hm8qivez ~]# docker search mysql
NAME                              DESCRIPTION                                     STARS     OFFICIAL   AUTOMATED
mysql                             MySQL is a widely used, open-source relation…   10455     [OK]       
mariadb                           MariaDB is a community-developed fork of MyS…   3886      [OK]       
mysql/mysql-server                Optimized MySQL Server Docker images. Create…   767                  [OK]
percona                           Percona Server is a fork of the MySQL relati…   526       [OK]       
centos/mysql-57-centos7           MySQL 5.7 SQL database server                   87                   
mysql/mysql-cluster               Experimental MySQL Cluster Docker images. Cr…   79                   
centurylink/mysql                 Image containing mysql. Optimized to be link…   59                   [OK]
bitnami/mysql                     Bitnami MySQL Docker Image                      48                   [OK]
deitch/mysql-backup               REPLACED! Please use http://hub.docker.com/r…   41                   [OK]
databack/mysql-backup             Back up mysql databases to... anywhere!         37                   
prom/mysqld-exporter                                                              37                   [OK]
tutum/mysql                       Base docker image to run a MySQL database se…   35                   
schickling/mysql-backup-s3        Backup MySQL to S3 (supports periodic backup…   29                   [OK]
linuxserver/mysql                 A Mysql container, brought to you by LinuxSe…   27                   
centos/mysql-56-centos7           MySQL 5.6 SQL database server                   20                   
circleci/mysql                    MySQL is a widely used, open-source relation…   20                   
arey/mysql-client                 Run a MySQL client from a docker container      17                   [OK]
mysql/mysql-router                MySQL Router provides transparent routing be…   17                   
fradelg/mysql-cron-backup         MySQL/MariaDB database backup using cron tas…   11                   [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]

2.从docker hub上面拉取镜像到本地

[root@izuf6d7j6gct081hm8qivez ~]# docker pull mysql:5.6
5.6: Pulling from library/mysql
8aff230071c9: Pull complete 
134fc34c9927: Pull complete 
27dfb473d52e: Pull complete 
702c333a167e: Pull complete 
699bc078b452: Pull complete 
01dd862365bd: Pull complete 
7dbfc4425b5a: Pull complete 
038f3579b073: Pull complete 
d03e96fd56ed: Pull complete 
d4e40c94cc3e: Pull complete 
552099682f91: Pull complete 
Digest: sha256:a1868bd2d1c8c32a46baa7d06f38c3de76e949c8f811a5bc42bac6738520f3a7
Status: Downloaded newer image for mysql:5.6
docker.io/library/mysql:5.6

# 查询是否成功拉取到mysql镜像
[root@izuf6d7j6gct081hm8qivez ~]# docker images mysql:5.6
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
mysql        5.6       eb4e842271a4   2 weeks ago   303MB

3.使用mysql5.6镜像创建容器(也就运行镜像)

[root@izuf6d7j6gct081hm8qivez ~]# docker run -p 12345:3306 --name mysql -v /zzyyuse/mysql/conf:/etc/mysql/conf.d -v /zzyyuse/mysql/logs:/logs -v /zzyyuse/mysql/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 -d mysql:5.6
226634c8ea479c162724684c569483c72678d95d732cac58623cc0b64d2bf3ca

命令说明:
-p123456:3306 将主机的12345端口映射到docker容器的3306端口。
--name mysql: 运行服务名字,也就是别名
-v /zzyyuse/mysql/conf:/etc/mysql/conf.d将主机/zzyyuse/mysql目录下的conf/my.cnf挂载到容器的/etc/mysql/conf.d
-v /zzyyuse/mysql/logs:/logs: 将主机/zzyyuse/mysql目录下的logs目录挂载到容器的/logs
-v /zzyyuse/mysql/data:/var/lib/mysql:将主机/zzyyuse/mysql目录下的data目录挂载到容器的/var/lib/mysql
-e MYSQL_ROOT_PASSWORD=123456:初始化root用户的密码
-d mysql:5.6 后台程序运行mysql5.6

# 查看运行的镜像
[root@izuf6d7j6gct081hm8qivez ~]# docker ps
CONTAINER ID   IMAGE       COMMAND                  CREATED          STATUS          PORTS                     NAMES
226634c8ea47   mysql:5.6   "docker-entrypoint.s…"   17 seconds ago   Up 15 seconds   0.0.0.0:12345->3306/tcp   mysql

# 进入容器
[root@izuf6d7j6gct081hm8qivez ~]# docker exec -it 226634c8ea47 /bin/bash
root@226634c8ea47:/# 

#进入mysql数据库
root@226634c8ea47:/# mysql -uroot -p
Enter password: 
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.6.51 MySQL Community Server (GPL)

Copyright (c) 2000, 2021, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql>
mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
+--------------------+
3 rows in set (0.01 sec)

mysql> 

# 创建数据库db01
mysql> create database db01;
Query OK, 1 row affected (0.00 sec)

mysql> use db01;
Database changed

# 创建t_book表
mysql> create table t_book(id int not null primary key,bookName varchar(20));
Query OK, 0 rows affected (0.03 sec)

mysql> show tables;
+----------------+
| Tables_in_db01 |
+----------------+
| t_book         |
+----------------+
1 row in set (0.00 sec)

mysql> 

# 插入数据库测试字段
mysql> insert into t_book values(1,'java');
Query OK, 1 row affected (0.01 sec)

mysql> select * from t_book;
+----+----------+
| id | bookName |
+----+----------+
|  1 | java     |
+----+----------+
1 row in set (0.00 sec)

mysql> 

通过宿主机的数据库连接工具连接到容器的数据后进行增删改查,对应容器中的数据也会发响应的变化

安装redis

  1. 从docker hub上(阿里云加速)拉取redis镜像到本地标签为3.2
  2. 使用redis3.2镜像创建容器(也就运行容器)

拉取镜像

# 拉取redis镜像
[root@izuf6d7j6gct081hm8qivez ~]# docker stop 226634c8ea47
226634c8ea47
[root@izuf6d7j6gct081hm8qivez ~]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@izuf6d7j6gct081hm8qivez ~]# docker pull redis:3.2
3.2: Pulling from library/redis
f17d81b4b692: Pull complete 
b32474098757: Pull complete 
8980cabe8bc2: Pull complete 
58af19693e78: Pull complete 
a977782cf22d: Pull complete 
9c1e268980b7: Pull complete 
Digest: sha256:7b0a40301bc1567205e6461c5bf94c38e1e1ad0169709e49132cafc47f6b51f3
Status: Downloaded newer image for redis:3.2
docker.io/library/redis:3.2

# 查看拉取到redis镜像
[root@izuf6d7j6gct081hm8qivez ~]# docker images redis:3.2
REPOSITORY   TAG       IMAGE ID       CREATED       SIZE
redis        3.2       87856cc39862   2 years ago   76MB

运行镜像

[root@izuf6d7j6gct081hm8qivez ~]# docker run -p 6389:6379 -v /zzyyuse/myredis/data:/data -v /zzyyuse/myredis/conf/redis.conf:/usr/local/etc/redis/redis.conf -d redis:3.2 redis-server /usr/local/etc/redis/redis.conf --appendonly yes
cbdc019dc08b94be0a15f38c9a3a07e860cf5a1e677c15a39fb52505d167316a

# 查看redis是在运行
[root@izuf6d7j6gct081hm8qivez ~]# docker ps
CONTAINER ID   IMAGE       COMMAND                  CREATED          STATUS          PORTS                    NAMES
cbdc019dc08b   redis:3.2   "docker-entrypoint.s…"   17 seconds ago   Up 15 seconds   0.0.0.0:6389->6379/tcp   hopeful_shockley

创建redis配置文件

# 将redis的配置文件写入到redis.conf
[root@izuf6d7j6gct081hm8qivez redis.conf]# vim redis.conf
[root@izuf6d7j6gct081hm8qivez redis.conf]# pwd
/zzyyuse/myredis/conf/redis.conf

测试连接redis

[root@izuf6d7j6gct081hm8qivez redis.conf]# docker ps
CONTAINER ID   IMAGE       COMMAND                  CREATED          STATUS          PORTS                    NAMES
cbdc019dc08b   redis:3.2   "docker-entrypoint.s…"   14 minutes ago   Up 14 minutes   0.0.0.0:6389->6379/tcp   hopeful_shockley
[root@izuf6d7j6gct081hm8qivez redis.conf]# docker exec -it cbdc019d redis-cli
127.0.0.1:6379> 

# 创建测试数据
[root@izuf6d7j6gct081hm8qivez redis.conf]# docker exec -it cbdc019d redis-cli
127.0.0.1:6379> set key1 v1
OK
127.0.0.1:6379> set key2 v2
OK
127.0.0.1:6379> set key3 v3
OK
127.0.0.1:6379> 

到宿主机上查看数据是否持久化

[root@izuf6d7j6gct081hm8qivez redis.conf]# docker ps
CONTAINER ID   IMAGE       COMMAND                  CREATED          STATUS          PORTS                    NAMES
cbdc019dc08b   redis:3.2   "docker-entrypoint.s…"   19 minutes ago   Up 19 minutes   0.0.0.0:6389->6379/tcp   hopeful_shockley

# 将服务停掉
[root@izuf6d7j6gct081hm8qivez redis.conf]# docker stop cbdc019dc08b
cbdc019dc08b
[root@izuf6d7j6gct081hm8qivez redis.conf]# docker ps
CONTAINER ID   IMAGE     COMMAND   CREATED   STATUS    PORTS     NAMES
[root@izuf6d7j6gct081hm8qivez data]# cd /zzyyuse/myredis/data
[root@izuf6d7j6gct081hm8qivez data]# pwd
/zzyyuse/myredis/data
[root@izuf6d7j6gct081hm8qivez data]# ll
-rw-r--r-- 1 systemd-bus-proxy ssh_keys 116 2月   3 16:50 appendonly.aof
[root@izuf6d7j6gct081hm8qivez data]# cat appendonly.aof 
*2
$6
SELECT
$1
0
*3
$3
set
$4
key1
$2
v1
*3
$3
set
$4
key2
$2
v2
*3
$3
set
$4
key3
$2
v3
# 可以看到数据已经持久化了,此时的redis已经是关闭了

本地镜像发布到阿里云

  1. 本地镜像发布到阿里云路流程
  2. 镜像的生产方法
  3. 将本地镜像推送到阿里云
  4. 将阿里云的镜像下载到本地

先构建本地镜像

[root@izuf6d7j6gct081hm8qivez ~]# docker commit -a gxy -m "new mycentos1.4 with vim and ifconfig" 15d11191193a mycentos:1.4
sha256:5dfb533c7867c8a46a009613b660e220b0eee0ff298d5ba910cfbf75a52d6bea

OPTIONS说明:
-a:提交镜像作者;
-m:提交时的说明文字;

# 查看构建好的镜像
[root@izuf6d7j6gct081hm8qivez ~]# docker images mycentos:1.4
REPOSITORY   TAG       IMAGE ID       CREATED          SIZE
mycentos     1.4       5dfb533c7867   40 seconds ago   291MB

将镜像推到registry

$ sudo docker login --username=guoxuyang1991 registry.cn-hangzhou.aliyuncs.com
$ sudo docker tag [ImageId] registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021:[镜像版本号]
$ sudo docker push registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021:[镜像版本号]
# 登录到registry
[root@izuf6d7j6gct081hm8qivez ~]# docker login --username=guoxuyang1991 registry.cn-hangzhou.aliyuncs.com
Password:
WARNING! Your password will be stored unencrypted in /root/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded
[root@izuf6d7j6gct081hm8qivez ~]# 

# 选择要上传的镜像
[root@izuf6d7j6gct081hm8qivez ~]# docker images mycentos:1.4
REPOSITORY   TAG       IMAGE ID       CREATED        SIZE
mycentos     1.4       5dfb533c7867   17 hours ago   291MB
[root@izuf6d7j6gct081hm8qivez ~]# docker tag 5dfb533c7867 registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021:1.4
[root@izuf6d7j6gct081hm8qivez ~]# 

# 从本地推送到阿里云服务器
[root@izuf6d7j6gct081hm8qivez ~]# docker push registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021:1.4
The push refers to repository [registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021]
edebd4d0d50c: Pushed 
8053f652c9e1: Pushed 
2653d992f4ef: Pushed 
1.4: digest: sha256:c3a1a85140e6c616b01436f524a4f8e1e76e3d947a69aea21ebcff3ab1e81932 size: 953
[root@izuf6d7j6gct081hm8qivez ~]# 

#查看镜像
[root@izuf6d7j6gct081hm8qivez ~]# docker images
REPOSITORY                                                         TAG       IMAGE ID       CREATED        SIZE
mycentos                                                           1.4       5dfb533c7867   17 hours ago   291MB
registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021   1.4       5dfb533c7867   17 hours ago   291MB
zzyytomcat9                                                        latest    a57fd7cbc95b   40 hours ago   689MB
myip3                                                              latest    d40be39fb652   47 hours ago   243MB
myip                                                               latest    1bd4f1f4b319   2 days ago     243MB
mycentos                                                           1.3       51e3e67533a3   2 days ago     291MB
tomcat                                                             latest    66d886628b2a   2 days ago     668MB
gxy/centos                                                         latest    442d7713764e   5 days ago     209MB
mysql                                                              5.6       eb4e842271a4   2 weeks ago    303MB
centos                                                             latest    300e315adb2f   8 weeks ago    209MB
redis                                                              3.2       87856cc39862   2 years ago    76MB

从私有仓库拉上传后的镜像到本地

# 删除上传的镜像
[root@izuf6d7j6gct081hm8qivez ~]# docker images
REPOSITORY                                                         TAG       IMAGE ID       CREATED        SIZE
mycentos                                                           1.4       5dfb533c7867   17 hours ago   291MB
registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021   1.4       5dfb533c7867   17 hours ago   291MB
zzyytomcat9                                                        latest    a57fd7cbc95b   40 hours ago   689MB
myip3                                                              latest    d40be39fb652   47 hours ago   243MB
myip                                                               latest    1bd4f1f4b319   2 days ago     243MB
mycentos                                                           1.3       51e3e67533a3   2 days ago     291MB
tomcat                                                             latest    66d886628b2a   2 days ago     668MB
gxy/centos                                                         latest    442d7713764e   5 days ago     209MB
mysql                                                              5.6       eb4e842271a4   2 weeks ago    303MB
centos                                                             latest    300e315adb2f   8 weeks ago    209MB
redis                                                              3.2       87856cc39862   2 years ago    76MB
[root@izuf6d7j6gct081hm8qivez ~]# docker rmi registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021:1.4
Untagged: registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021:1.4
Untagged: registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021@sha256:c3a1a85140e6c616b01436f524a4f8e1e76e3d947a69aea21ebcff3ab1e81932

# 查看当前镜像
[root@izuf6d7j6gct081hm8qivez ~]# docker images
REPOSITORY    TAG       IMAGE ID       CREATED        SIZE
mycentos      1.4       5dfb533c7867   18 hours ago   291MB
zzyytomcat9   latest    a57fd7cbc95b   41 hours ago   689MB
myip3         latest    d40be39fb652   2 days ago     243MB
myip          latest    1bd4f1f4b319   2 days ago     243MB
mycentos      1.3       51e3e67533a3   2 days ago     291MB
tomcat        latest    66d886628b2a   2 days ago     668MB
gxy/centos    latest    442d7713764e   6 days ago     209MB
mysql         5.6       eb4e842271a4   2 weeks ago    303MB
centos        latest    300e315adb2f   8 weeks ago    209MB
redis         3.2       87856cc39862   2 years ago    76MB

# 从私有仓库拉取镜像到本地
[root@izuf6d7j6gct081hm8qivez ~]# sudo docker pull registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021:1.4
1.4: Pulling from gxy_docker2021/gxy_docker_2021
Digest: sha256:c3a1a85140e6c616b01436f524a4f8e1e76e3d947a69aea21ebcff3ab1e81932
Status: Downloaded newer image for registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021:1.4
registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021:1.4
[root@izuf6d7j6gct081hm8qivez ~]# docker images
REPOSITORY                                                         TAG       IMAGE ID       CREATED        SIZE
mycentos                                                           1.4       5dfb533c7867   18 hours ago   291MB
registry.cn-hangzhou.aliyuncs.com/gxy_docker2021/gxy_docker_2021   1.4       5dfb533c7867   18 hours ago   291MB
zzyytomcat9                                                        latest    a57fd7cbc95b   41 hours ago   689MB
myip3                                                              latest    d40be39fb652   2 days ago     243MB
myip                                                               latest    1bd4f1f4b319   2 days ago     243MB
mycentos                                                           1.3       51e3e67533a3   2 days ago     291MB
tomcat                                                             latest    66d886628b2a   2 days ago     668MB
gxy/centos                                                         latest    442d7713764e   6 days ago     209MB
mysql                                                              5.6       eb4e842271a4   2 weeks ago    303MB
centos                                                             latest    300e315adb2f   8 weeks ago    209MB
redis                                                              3.2       87856cc39862   2 years ago    76MB

docker的内存分配机制

如何查看centos中docker的内存分配参数

在 CentOS 中,你可以使用 docker inspect 命令来查看一个运行中容器的详细信息,包括其内存分配参数。

通过docker ps来获取容器ID

[root@VM-4-14-centos ~]# docker ps
CONTAINER ID   IMAGE     COMMAND             CREATED         STATUS         PORTS                                       NAMES
56568a01a220   tomcat    "catalina.sh run"   3 minutes ago   Up 3 minutes   0.0.0.0:8080->8080/tcp, :::8080->8080/tcp   my_tomcat

查看内存分配参数

# 返回值为0,通常意味着该容器没有设置具体的内存限制,或者它可能继承了默认的内存限制。如果一个容器没有显式设置内存限制,那么它将会使用系统的默认限制,这通常是无限制的,意味着容器可以使用主机上所有可用的内存。所以,返回0可能意味着该容器可以使用主机上的所有可用内存,没有受到具体的内存限制。
[root@VM-4-14-centos ~]# docker inspect --format='{{.HostConfig.Memory}}' 56568a01a220
0

这将会返回容器的内存限制,单位为字节。

如果你想获取内存限制的其他格式,可以替换 {{.HostConfig.Memory}} 部分,比如 {{.HostConfig.Memory}} 可以替换成 {{.HostConfig.Memory}} / 1024 / 1024 以获取以兆字节为单位的内存限制。

请确保容器正在运行以及你有相应的权限来运行 Docker 命令。如果容器已经停止,你可能需要重新启动它以查看其内存配置。
**声明:**本笔记是根据尚硅谷视频所做笔记,有侵权者可联系本人给予删除!

你可能感兴趣的:(容器-docker,docker,容器,运维)