05_Docker镜像基础

Docker镜像基础

镜像构成

分层 说明
App 应用层
Base Image 系统层
Bootfs 底层

Docker Registry 仓库分为3种

​ Docker Hub 官方仓库

​ Mirror Registry 镜像加速仓库

​ Private Registry 私有镜像库

仓库结构

​ Index(用户身份认证,检索信息)

​ repository

​ repo的名称(应用的名称)

​ tag标识一个应用的不通版本

下载镜像:

docker pull <registry>:[port]/<namespace>/<name>:<tag>

docker pull dockerhub.com/lin/nginx:1.2

创建镜像

Dockerfile

​ 可以提前构建一个配置文件模版,然后在构建镜像的时候通过变量来生成不同的镜像。

内核不能识别变量所以要使用shell来做变量替换

  • 使用模板文件在里面定义好变量。

  • 在构建镜像的时候使用shell传递变量。

  • shell变量传递结束后使用exec 启动Nginx。

  • exec启动Nginx以后会替换当前shell的进程ID。

    exec执行的命令会替换当前shell窗口的进程,例如exec ls执行完毕以后终端窗口会关闭,因为ls在执行完毕后会自动退出。

image-20210609151137383

Dockerfile的构成
  • #注释行

  • 指令 参数,指令的大小写不敏感.

  • 第一个非注释行必须是FROM指令.

注意的问题:

编写Dockerfile必须在一个目录下进行,这个目录称之为工作目录(workspace).

Dockerfile文件命令的首字母必须大写

制作镜像所要用的文件必须放在工作目录或者工作目录的子目录之下,不能放在父目录.

在工作目录下,可以有子目录并可以通过隐藏文件.dockeringnore来制定不要放入到镜像中的文件,一行一个文件可以使用通配符.

以下指令列表支持环境变量Dockerfile

  • ADD

  • COPY

  • ENV

  • EXPOSE

  • FROM

  • LABEL

  • STOPSIGNAL

  • USER

  • VOLUME

  • WORKDIR

  • ONBUILD (与上述支持的指令之一结合使用时)

Shell
  • 定义变量

    var=value

  • 替换变量

    $var

    ${var}

  • 变量扩展

    ${var:-value} 如果变量存在就输出如果不存在就给变量设置一个默认值.

    # name=centeros
    # echo {name:-test}
    centeros
    # echo{123:-test}
    test
    

    ${var:+value} 如果变量存在就输出value如果不存在就输出空.

    # name=centeros
    # echo {name:+test}
    test
    # echo{123:+test}
    
    
Dockerfile指令
FROM

指定基础镜像

FROM <registry>:[tag] 可能会被冒充

FROM <registry>@<digest> 使用数字摘要(hash)防止串改.

MATNTAINER

用来指定作者信息(已经废弃但是兼容)

LABEL

设定一些元数据 作者 版本信息

LABEL author=“test@gmail.com”

COPY

将工作目录下的一个文件或者目录复制到所做的镜像的文件系统中.

复制单个文件:COPY <src> <dest>

复制多个文件:COPY [<src> <src> <src>...<dest>]

注意:

源文件路径用相对路径,目标文件路径为绝对路径,目标路径可以不存在会自动创建.

如果源文件是一个目录,会自动递归复制目录下的文件到目标位置,但是目录自身不会复制.

如果复制多个文件,或者源文件中用了通配符,那么目标路径必须以/为结尾.

例:

[root@localhost03 testdock]# ls
Dockerfile  index.html

[root@localhost03 testdock]# cat Dockerfile
# fist docker images
# ltest@gmail.com
FROM centos:latest
LABEL author=“test@gmail.com”
COPY index.html /data/html/

[root@localhost03 testdock]# docker build -t mycentos:v1.0 .
Sending build context to Docker daemon  3.072kB
Step 1/3 : FROM centos:latest
latest: Pulling from library/centos
7a0437f04f83: Pull complete
Digest: sha256:5528e8b1b1719d34604c87e11dcd1c0a20bedf46e83b5632cdeac91b8c04efc1
Status: Downloaded newer image for centos:latest
 ---> 300e315adb2f
Step 2/3 : LABEL author=“test@gmail.com”
 ---> Running in 94ee53e32c91
Removing intermediate container 94ee53e32c91
 ---> 323fb65db1f1
Step 3/3 : COPY index.html /data/html/
 ---> 53394a83ced6
Successfully built 53394a83ced6
Successfully tagged mycentos:v1.0

[root@localhost03 testdock]# docker images
REPOSITORY            TAG       IMAGE ID       CREATED         SIZE
mycentos              v1.0      53394a83ced6   2 minutes ago   209MB
ADD

ADD和COPY类似区别是如果源文件压缩包会自动解压压缩包,也可以实现从网络下载文件到镜像(下载的tar包无法解压)

复制单个文件:ADD <src> <dest>

复制多个文件:ADD ["<src>" "<src>" "<src>"..."<src>"]

例:

[root@localhost03 testdock]# cat Dockerfile
# fist docker images
# ltest@gmail.com
FROM centos:latest
LABEL author=“test@gmail.com”
COPY index.html /data/html/
ADD http://nginx.org/download/nginx-1.21.0.tar.gz /download/src/

[root@localhost03 testdock]# docker build -t mycentos:v1.1 .
Sending build context to Docker daemon  3.072kB
Step 1/4 : FROM centos:latest
 ---> 300e315adb2f
Step 2/4 : LABEL author=“test@gmail.com”
 ---> Using cache
 ---> 323fb65db1f1
Step 3/4 : COPY index.html /data/html/
 ---> Using cache
 ---> 53394a83ced6
Step 4/4 : ADD http://nginx.org/download/nginx-1.21.0.tar.gz /download/src/
Downloading [==================================================>]  1.064MB/1.064MB
 ---> 61c3ea49954d
Successfully built 61c3ea49954d
Successfully tagged mycentos:v1.1
WORKDIR

用来镜像中的工作目录

WORKDIR /download/src/

[root@localhost03 testdock]# cat Dockerfile
# fist docker images
# ltest@gmail.com
FROM centos:latest
LABEL author=“test@gmail.com”
COPY index.html /data/html/
WORKDIR /download/src/
ADD http://nginx.org/download/nginx-1.21.0.tar.gz ./

[root@localhost03 testdock]# docker build -t mycentos:v1.3 .
Sending build context to Docker daemon  3.072kB
Step 1/5 : FROM centos:latest
 ---> 300e315adb2f
Step 2/5 : LABEL author=“test@gmail.com”
 ---> Using cache
 ---> 323fb65db1f1
Step 3/5 : COPY index.html /data/html/
 ---> Using cache
 ---> 53394a83ced6
Step 4/5 : WORKDIR /download/src/
 ---> Running in 5dd4daee4617
Removing intermediate container 5dd4daee4617
 ---> 5f4002bf3c33
Step 5/5 : ADD http://nginx.org/download/nginx-1.21.0.tar.gz ./
Downloading [==================================================>]  1.064MB/1.064MB
 ---> 7b1ecd2e4908
Successfully built 7b1ecd2e4908
Successfully tagged mycentos:v1.3

[root@localhost03 testdock]# docker run --name centos1 -it -h test.com --rm mycentos:v1.3
[root@test src]# cd /download/src/
[root@test src]# ls
nginx-1.21.0.tar.gz
VOLUME

指定容器中数据卷的挂载点(不存在会自动创建)

VOLUME /data/mysql/mysqldate/

:

[root@localhost03 testdock]# cat Dockerfile
# fist docker images
# ltest@gmail.com
FROM centos:latest
LABEL author=“test@gmail.com”
COPY index.html /data/html/
WORKDIR /download/src/
ADD http://nginx.org/download/nginx-1.21.0.tar.gz ./
VOLUME /data/mysql/mysqldate/

[root@localhost03 testdock]# docker build -t mycentos:v1.5 .
Sending build context to Docker daemon  3.072kB
Step 1/6 : FROM centos:latest
 ---> 300e315adb2f
Step 2/6 : LABEL author=“test@gmail.com”
 ---> Using cache
 ---> 323fb65db1f1
Step 3/6 : COPY index.html /data/html/
 ---> Using cache
 ---> 53394a83ced6
Step 4/6 : WORKDIR /download/src/
 ---> Using cache
 ---> 5f4002bf3c33
Step 5/6 : ADD http://nginx.org/download/nginx-1.21.0.tar.gz ./
Downloading [==================================================>]  1.064MB/1.064MB
 ---> Using cache
 ---> 7b1ecd2e4908
Step 6/6 : VOLUME /data/mysql/mysqldate/
 ---> Running in c4c9784e1eed
Removing intermediate container c4c9784e1eed
 ---> 16d3fd62a1f0
Successfully built 16d3fd62a1f0
Successfully tagged mycentos:v1.5

[root@localhost03 testdock]# docker run --name centos1 -it -h test.com --rm mycentos:v1.5
[root@test src]# mount | grep mysql
/dev/mapper/centos-root on /data/mysql/mysqldate type xfs (rw,relatime,seclabel,attr2,inode64,noquota)
EXPOSE

为容器暴露指定的端口到宿主机(仅仅是表示容器可以暴露指定端口,但是是否暴露需要运行的时候使用-P暴露)

EXPOSE PORT/[PROTOCOL] 默认TCP

ENV

设置环境变量

ENV NGX_DOC_ROOT "/data/html/"设置一个变量.

ENV var1=value1 var2=value2 ..... 设置多个变量.

[root@test html]# printenv查看当前变量.

例:

[root@localhost03 testdock]# cat Dockerfile
# fist docker images
# ltest@gmail.com
FROM centos:latest
LABEL author=“test@gmail.com”
ENV NGX_DOC_ROOT "/data/html/"
COPY index.html {NGX_DOC_ROOT}
WORKDIR /download/src/
ADD http://nginx.org/download/nginx-1.21.0.tar.gz ./
VOLUME /data/mysql/mysqldate/
EXPOSE 80/tcp

[root@localhost03 testdock]# docker build -t mycentos:v1.7 .
Sending build context to Docker daemon  3.072kB
Step 1/8 : FROM centos:latest
 ---> 300e315adb2f
Step 2/8 : LABEL author=“test@gmail.com”
 ---> Using cache
 ---> 323fb65db1f1
Step 3/8 : ENV NGX_DOC_ROOT "/data/html/"
 ---> Running in cf9b885b6985
Removing intermediate container cf9b885b6985
 ---> 930e7661e9da
Step 4/8 : COPY index.html{NGX_DOC_ROOT}
 ---> 4359e728f32c
Step 5/8 : WORKDIR /download/src/
 ---> Running in 4b57a0cd666d
Removing intermediate container 4b57a0cd666d
 ---> 7be1e75803ed
Step 6/8 : ADD http://nginx.org/download/nginx-1.21.0.tar.gz ./
Downloading [==================================================>]  1.064MB/1.064MB
 ---> 4f03cf8c5fbd
Step 7/8 : VOLUME /data/mysql/mysqldate/
 ---> Running in 74bc92c609fe
Removing intermediate container 74bc92c609fe
 ---> dd36b393bf68
Step 8/8 : EXPOSE 80/tcp
 ---> Running in dbaa5e57bc95
Removing intermediate container dbaa5e57bc95
 ---> d8d9e725ff2a
Successfully built d8d9e725ff2a
Successfully tagged mycentos:v1.7

注意:
通过ENV所定义的变量是可以传递到容器之中,但是在创建容器的时候,如果手动指定了变量的值,那么这个值会覆盖掉镜像中原有的值

[root@localhost03 testdock]# docker run --name centos1 -it -h test.com -p 81:81 --rm -e NGX_DOC_ROOT="/data/newhtml/" mycentos:v1.7

[root@test src]# printenv
NGX_DOC_ROOT=/data/newhtml/
RUN

基于镜像构建容器的时候运行的命令

RUN cd /download/src/

例:

[root@localhost03 testdock]# cat Dockerfile
# fist docker images
# ltest@gmail.com
FROM centos:latest
LABEL author=“test@gmail.com”
ENV NGX_DOC_ROOT "/data/html/"
COPY index.html {NGX_DOC_ROOT}
WORKDIR /download/src/
ADD http://nginx.org/download/nginx-1.21.0.tar.gz ./
RUN cd /download/src/ && tar -xzf nginx-1.21.0.tar.gz \
    && mkdir -p /data/mysql/mysqldate/ \
    && mv nginx-1.21.0 /data/mysql/mysqldate/
VOLUME /data/mysql/mysqldate/
EXPOSE 80/tcp

[root@localhost03 testdock]# docker build -t mycentos:v1.8 .
Sending build context to Docker daemon  3.072kB
Step 1/9 : FROM centos:latest
 ---> 300e315adb2f
Step 2/9 : LABEL author=“test@gmail.com”
 ---> Using cache
 ---> 323fb65db1f1
Step 3/9 : ENV NGX_DOC_ROOT "/data/html/"
 ---> Using cache
 ---> 930e7661e9da
Step 4/9 : COPY index.html{NGX_DOC_ROOT}
 ---> Using cache
 ---> 4359e728f32c
Step 5/9 : WORKDIR /download/src/
 ---> Using cache
 ---> 7be1e75803ed
Step 6/9 : ADD http://nginx.org/download/nginx-1.21.0.tar.gz ./
Downloading [==================================================>]  1.064MB/1.064MB
 ---> Using cache
 ---> 4f03cf8c5fbd
Step 7/9 : RUN cd /download/src/ && tar -xzf nginx-1.21.0.tar.gz    && mkdir -p /data/mysql/mysqldate/  && mv nginx-1.21.0 /data/mysql/mysqldate/
 ---> Running in 9b8f8b151be8
Removing intermediate container 9b8f8b151be8
 ---> 7f0f47361cf9
Step 8/9 : VOLUME /data/mysql/mysqldate/
 ---> Running in 29d999cae189
Removing intermediate container 29d999cae189
 ---> e897e62e0ee3
Step 9/9 : EXPOSE 80/tcp
 ---> Running in f41ce998db4a
Removing intermediate container f41ce998db4a
 ---> 7d33e4fd21fa
Successfully built 7d33e4fd21fa
Successfully tagged mycentos:v1.8

[root@localhost03 testdock]# docker run --name centos1 -it -h test.com -p 81:81 --rm -e NGX_DOC_ROOT="/data/newhtml/" mycentos:v1.8
[root@test src]# cd /data/mysql/mysqldate/
CMD

定义容器启动以后默认运行的程序,PID为1的程序.

PID为1的进程由内核启动,俗称天父进程.

可以在启动容器的时候用指定的命令替换掉镜像所要执行的命令.

启动过程 init>>shell>>shell -c "command" 类似于exec "command"会替换shell成为[PID]为1的进程.

CMD <命令>

CMD ["<命令>","<参数>","<参数>"]

httpd -f -h /data/html
CMD ["httpd","-f","-h /data/html/"]

CMD ["<参数>","<参数>"] <<<< 需要借助于 ENTRYPOINT指令

ENTRYPOINT

定义容器启动以后默认运行的程序,PID为1的程序不能被run命令定义的命令覆盖.

RUN后面的命令会被以参数的方式追加到原本要执行的命令的末尾

ENTRYPOINT /bin/httpd -f -h ${DOC_ROOT}

ENTRYPOINT ["<命令>","<参数>","<参数>"]

[root@localhost03 testdock]# cat Dockerfile
# fist docker images
# ltest@gmail.com
FROM busybox:latest
LABEL author=“test@gmail.com”
ENV NGX_DOC_ROOT "/usr/sahre/nginx/html/"
COPY index.html {NGX_DOC_ROOT}
#RUN yum install nginx -y && systemctl start nginx
VOLUME{NGX_DOC_ROOT}
EXPOSE 80/tcp
ENTRYPOINT /bin/httpd -f -h ${NGX_DOC_ROOT}

CMD,ENTRYPOINT同时使用,CMD的命令会被追加在ENTRYPOINT后面.

CMD ["-f","-h","/usr/sahre/nginx/html/"]

ENTRYPOINT ["/bin/httpd"]

例:

[root@localhost03 testdock]# cat Dockerfile
# fist docker images
# ltest@gmail.com
FROM busybox:latest
LABEL author=“test@gmail.com”
ENV NGX_DOC_ROOT "/usr/sahre/nginx/html/"
COPY index.html {NGX_DOC_ROOT}
VOLUME{NGX_DOC_ROOT}
EXPOSE 80/tcp
CMD ["-f","-h","/usr/sahre/nginx/html/"]
ENTRYPOINT ["/bin/httpd"]
ARG

定义变量,这个变量是用在第一阶段(构建镜像-build)

Dockerfile中ENV和ARG的区别

在指定 docker build过程中传参数,要用ARG .

在执行 docker run的过程中传参数,要用ENV.

例:

[root@localhost03 test2docker]# cat Dockerfile
FROM busybox:latest
ARG myname="test@qq.com"
MAINTAINER name={myname}
RUN echo{myname} >/myname.txt

[root@localhost03 test2docker]# docker build --build-arg myname="123@qq.com" -t test:v1.0 .
Sending build context to Docker daemon  2.048kB
Step 1/3 : FROM busybox:latest
 ---> d3cd072556c2
Step 2/3 : ARG myname="test@qq.com"
 ---> Running in f0906ccc016c
Removing intermediate container f0906ccc016c
 ---> e58163c04565
Step 3/3 : LABEL author=${myname}
 ---> Running in 08976dc7b686
Removing intermediate container 08976dc7b686
 ---> 4d1b08b22689
Successfully built 4d1b08b22689
Successfully tagged test:v1.0
USER

定义容器中的进程以哪个用户的身份运行
该用户必须存在于容器的用户空间中(容器的文件系统的中的/etc/ passwd中)

USER <UID>|<USERNAME>

HEALTHCHECK

docker daemon检查 docker容器是否正常,如果异常会将该容器stop

HEALTHCHECK [OPTIONS] CMD command

将容器stop的条件

​ 1)主进程停止了

​ 2)主进程工作在了后台

--interval=DURATION(默认值:30s)
--timeout=DURATION(默认值:30s)
--start-period=DURATION(默认值:0s)
--retries=N(默认值:3)

运行状况检查将在容器启动后首先运行interval秒,然后在每次之前的检查完成后再次运行interval秒。

如果检查的单次运行时间超过timeout秒,则认为检查失败。

它需要重试连续的健康检查失败才能考虑容器unhealthy

start period为需要时间引导的容器提供初始化时间。在此期间的探测失败将不计入最大重试次数。但是,如果在启动期间健康检查成功,则认为容器已启动,所有连续失败都将计入最大重试次数。

HEALTHCHECK一个 Dockerfile 中只能有一条指令。如果您列出多个,则只有最后一个HEALTHCHECK才会生效。

CMD关键字后的命令可以是 shell 命令(例如HEALTHCHECK CMD /bin/check-running)或exec数组(与其他 Dockerfile 命令一样;ENTRYPOINT有关详细信息,请参见 eg )。

命令的退出状态指示容器的健康状态。可能的值为:

  • 0:成功 – 容器运行良好,可以使用
  • 1:不健康 – 容器不能正常工作
  • 2:reserved – 不要使用这个退出代码

例如,每五分钟左右检查一次网络服务器是否能够在三秒钟内为站点的主页提供服务:

HEALTHCHECK --interval=5m --timeout=3s \
  CMD curl -f http://localhost/ || exit 1

为了帮助调试失败的探测,命令在 stdout 或 stderr 上写入的任何输出文本(UTF-8 编码)都将存储在健康状态中,并且可以使用 docker inspect. 此类输出应保持简短(当前仅存储前 4096 个字节)。

当容器的健康状态发生变化时,health_status会生成具有新状态的事件。

SHELL

可以用来指定系统中默认的she11类型

SHELL ["executable", "parameters"]

SHELL指令允许覆盖用于命令的shell形式的默认 shell 。Linux 上的默认 shell 是["/bin/sh", "-c"],Windows上的默认 shell是["cmd", "/S", "/C"]. 该SHELL指令必须以 JSON 格式写入 Dockerfile。

SHELL指令在 Windows 上特别有用,因为 Windows 有两种常用且截然不同的本机 shell:cmdpowershell,以及可用的备用 shell,包括sh.

SHELL指令可以出现多次。每条SHELL指令都会覆盖所有先前的SHELL指令,并影响所有后续指令。例如:

FROM microsoft/windowsservercore

# Executed as cmd /S /C echo default
RUN echo default

# Executed as cmd /S /C powershell -command Write-Host default
RUN powershell -command Write-Host default

# Executed as powershell -command Write-Host hello
SHELL ["powershell", "-command"]
RUN Write-Host hello

# Executed as cmd /S /C echo hello
SHELL ["cmd", "/S", "/C"]
RUN echo hello
STOPSIGNAL

向容器中pid为1的进程发送一个信号,通过这个信号来关闭这个主进程默认是15信号
STOPSTGNAL 9

ONBULID

定义一个触发器,用来实现当基于这个这个镜像做新镜像的时候要执行的命令.

基于现有容器创建镜像

创建镜像
# docker commit --help

Usage:  docker commit [OPTIONS] CONTAINER [REPOSITORY[:TAG]]

Create a new image from a container's changes

Options:
  # 指定作者
  -a, --author string    Author (e.g., "John Hannibal Smith <hannibal@a-team.com>")
  # 修改执行命令
  -c, --change list      Apply Dockerfile instruction to the created image
  -m, --message string   Commit message
  # 创建镜像时自动暂停容器
  -p, --pause            Pause container during commit (default true)

# docker commit -p portainer_edge_03 test:1.0
sha256:c6d1a72b3c9ed6d52fe362db372af20ff07c08ba2a7955bf0fb1c5cbb482402c
# docker images
REPOSITORY            TAG       IMAGE ID       CREATED          SIZE
test                  1.0       c6d1a72b3c9e   12 seconds ago   94.8MB

# 指定命令并工作在前台(httpd -f -h /data/)
# docker commit -a "test@qq.com" -c 'CMD ["/bin/httpd","-f","-h","/data"]' -p portainer_edge_03 test:1.1
sha256:eeb8637a0b0c6b3c78f4cc936e1b0a4c5d171aa042ef4116ce184f1e2bf8f9b5
# docker images
REPOSITORY            TAG       IMAGE ID       CREATED          SIZE
test                  1.1       eeb8637a0b0c   37 seconds ago   94.8MB
test                  1.0       c6d1a72b3c9e   15 minutes ago   94.8MB
# docker ps --no-trunc -a
CONTAINER ID                                                       IMAGE             COMMAND                            CREATED          STATUS                      PORTS     NAMES
186938b8cbf6cbfb492f273321fe140057ec0f35c6bab9e6b9cf16f55e969bd0   test:1.1          "./agent /bin/httpd -f -h /data"   13 seconds ago   Exited (1) 12 seconds ago             test1
上传镜像到仓库

阿里云上创建账号和开通服务

  1. 登录阿里云Docker Registry
$ docker login --username=****@***.com registry.cn-shanghai.aliyuncs.com

用于登录的用户名为阿里云账号全名,密码为开通服务时设置的密码。

您可以在访问凭证页面修改凭证密码。

  1. 从Registry中拉取镜像
$ docker pull registry.cn-shanghai.aliyuncs.com/li*****/nginx:[镜像版本号]
  1. 将镜像推送到Registry
$ docker login --username=lin*****@*****.com registry.cn-shanghai.aliyuncs.com
$ docker tag [ImageId] registry.cn-shanghai.aliyuncs.com/lin*****/nginx:[镜像版本号]
$ docker push registry.cn-shanghai.aliyuncs.com/lin*****/nginx:[镜像版本号]

请根据实际镜像信息替换示例中的[ImageId]和[镜像版本号]参数。

  1. 选择合适的镜像仓库地址

从ECS推送镜像时,可以选择使用镜像仓库内网地址。推送速度将得到提升并且将不会损耗您的公网流量。

如果您使用的机器位于VPC网络,请使用 registry-vpc.cn-shanghai.aliyuncs.com 作为Registry的域名登录。

  1. 示例

使用”docker tag”命令重命名镜像,并将它通过专有网络地址推送至Registry。

$ docker images
REPOSITORY                                                         TAG                 IMAGE ID            CREATED             VIRTUAL SIZE
registry.aliyuncs.com/acs/agent                                    0.7-dfb6816         37bb9c63c8b2        7 days ago          37.89 MB
$ docker tag 37bb9c63c8b2 registry-vpc.cn-shanghai.aliyuncs.com/acs/agent:0.7-dfb6816

使用 “docker push” 命令将该镜像推送至远程。

$ docker push registry-vpc.cn-shanghai.aliyuncs.com/acs/agent:0.7-dfb6816

docker hub 自动创建镜像

文件系统Mount

存储卷( volume)

  • 实现让容器中的一个目录和宿主机中的一个文件或者目录进行绑定

功能

  • 容器中数据的持久存储
  • 容器间的资源共享
  • 容器的迁移(分布式)

image-20210607213028003

Docker volume

  • Bind Moun Volume :明确指定使用文件目录
    # docker run --name test1 -it --rm -v /home/test1:/disk busybox
    / # cd /disk/
    /disk # ls
    show.sh
    /disk # exit
    
    # cd /home/test1/
    # ls
    show.sh
    
  • Docker Management Volume : Docker Daemon自行管理将容器中的目录和宿主机中的哪个目录进行绑定
    # docker run --name test1 -it --rm -v /disk busybox
    / # ls /disk
    / # echo "123">/disk/t.txt
    / # cat /disk/t.txt
    123
    / # mount | grep disk
    /dev/mapper/centos-root on /disk type xfs (rw,seclabel,relatime,attr2,inode64,noquota)
    
    # docker inspect test1
    "Mounts": [
              {
                  "Type": "volume",
                  "Name": "e97a64888011a555a1eb6fe67555e391e36e402c2bbd9f43bcb632120b915119",
                  "Source": "/var/lib/docker/volumes/e97a64888011a555a1eb6fe67555e391e36e402c2bbd9f43bcb632120b915119/_data",
                  "Destination": "/disk",
                  "Driver": "local",
                  "Mode": "",
                  "RW": true,
                  "Propagation": ""
              }
          ],
    
    # cat /var/lib/docker/volumes/e97a64888011a555a1eb6fe67555e391e36e402c2bbd9f43bcb632120b915119/_data/t.txt
    123
    

    使用运行的容器已绑定的配置docker run --name test2 -it --volumes-from test1 busybox

获取Josn文件内容

  • Josn文件如下
[
    {
    "akey1": "value",
    "akey2": "value",
    "key1": 
        {
        "akey1": "value",
        "akey2": "value",
        "key2": 
            {
                "akey1": "value",
                "akey2": "value",
                "key3": "value"
            }
        }
    }
]

获取方法{.key1.key2.key3}

  • 举例获取网络信息
# docker inspect portainer_edge_03
[
    {
        "Id": "f2df8998de12829617783cb1d0b0a78358647159b8c2e304b2aa4ffded707f0f",
        "Created": "2021-02-03T07:29:08.793920863Z",
        "Path": "./agent",
        "Args": [],
        "State": {
            "Status": "running",
            "Running": true,
            "Paused": false,
            "Restarting": false,
            "OOMKilled": false,
            "Dead": false,
            "Pid": 2235,
            "ExitCode": 0,
            "Error": "",
            "StartedAt": "2021-06-01T14:21:58.126159983Z",
            "FinishedAt": "2021-06-01T14:21:17.049668454Z"
        },
        "Image": "sha256:c81206f03f4ab591bc8db5782d2a45d0546d5df9ba0ebb55e55fd33bf7f7aed7",
        "ResolvConfPath": "/var/lib/docker/containers/f2df8998de12829617783cb1d0b0a78358647159b8c2e304b2aa4ffded707f0f/resolv.conf",
        "HostnamePath": "/var/lib/docker/containers/f2df8998de12829617783cb1d0b0a78358647159b8c2e304b2aa4ffded707f0f/hostname",
        "HostsPath": "/var/lib/docker/containers/f2df8998de12829617783cb1d0b0a78358647159b8c2e304b2aa4ffded707f0f/hosts",
        "LogPath": "/var/lib/docker/containers/f2df8998de12829617783cb1d0b0a78358647159b8c2e304b2aa4ffded707f0f/f2df8998de12829617783cb1d0b0a78358647159b8c2e304b2aa4ffded707f0f-json.log",
        "Name": "/portainer_edge_03",
        "RestartCount": 0,
        "Driver": "overlay2",
        "Platform": "linux",
        "MountLabel": "",
        "ProcessLabel": "",
        "AppArmorProfile": "",
        "ExecIDs": null,
        "HostConfig": {
            "Binds": [
                "portainer_agent_data:/data",
                "/var/run/docker.sock:/var/run/docker.sock",
                "/var/lib/docker/volumes:/var/lib/docker/volumes",
                "/:/host"
            ],
            "ContainerIDFile": "",
            "LogConfig": {
                "Type": "json-file",
                "Config": {}
            },
            "NetworkMode": "default",
            "PortBindings": {},
            "RestartPolicy": {
                "Name": "always",
                "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": true,
            "PublishAllPorts": false,
            "ReadonlyRootfs": false,
            "SecurityOpt": [
                "label=disable"
            ],
            "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": null,
            "ReadonlyPaths": null
        },
        "GraphDriver": {
            "Data": {
                "LowerDir": "/var/lib/docker/overlay2/52d7c9b2b6d6208efaaf43bb546057ea9e8f194da963579f2c941ed16b53181f-init/diff:/var/lib/docker/overlay2/04141875ac430a316ed3ee146eb9acbdf56f1b81ee9f06c20e9d9338b01df295/diff:/var/lib/docker/overlay2/b69a17be93be9fbce973cfec2655b7c057a5c30308af0591cbbe9ebebfb5e7d5/diff:/var/lib/docker/overlay2/4290a14f89b0616b79ce00e9c03df67dfa05d021bd389b727b22973f621c879b/diff:/var/lib/docker/overlay2/e114f2470325db385d8d8a6eae4736f0d10e50d51bb41c74923f62fe88464876/diff:/var/lib/docker/overlay2/264b5f1eab66ca3dc5b5f983fb908b6c035298a2d445bdbb89b073e6d814aa9d/diff",
                "MergedDir": "/var/lib/docker/overlay2/52d7c9b2b6d6208efaaf43bb546057ea9e8f194da963579f2c941ed16b53181f/merged",
                "UpperDir": "/var/lib/docker/overlay2/52d7c9b2b6d6208efaaf43bb546057ea9e8f194da963579f2c941ed16b53181f/diff",
                "WorkDir": "/var/lib/docker/overlay2/52d7c9b2b6d6208efaaf43bb546057ea9e8f194da963579f2c941ed16b53181f/work"
            },
            "Name": "overlay2"
        },
        "Mounts": [
            {
                "Type": "volume",
                "Name": "portainer_agent_data",
                "Source": "/var/lib/docker/volumes/portainer_agent_data/_data",
                "Destination": "/data",
                "Driver": "local",
                "Mode": "z",
                "RW": true,
                "Propagation": ""
            },
            {
                "Type": "bind",
                "Source": "/",
                "Destination": "/host",
                "Mode": "",
                "RW": true,
                "Propagation": "rslave"
            },
            {
                "Type": "bind",
                "Source": "/var/lib/docker/volumes",
                "Destination": "/var/lib/docker/volumes",
                "Mode": "",
                "RW": true,
                "Propagation": "rslave"
            },
            {
                "Type": "bind",
                "Source": "/var/run/docker.sock",
                "Destination": "/var/run/docker.sock",
                "Mode": "",
                "RW": true,
                "Propagation": "rprivate"
            }
        ],
        "Config": {
            "Hostname": "f2df8998de12",
            "Domainname": "",
            "User": "",
            "AttachStdin": false,
            "AttachStdout": false,
            "AttachStderr": false,
            "Tty": false,
            "OpenStdin": false,
            "StdinOnce": false,
            "Env": [
                "EDGE=1",
                "EDGE_ID=9bf750d3-979c-4c15-8852-f37fc4d927aa",
                "EDGE_KEY=aHR0cDovLzE5Mi4xNjguMTAxLjExOjkwMDB8MTkyLjE2OC4xMDEuMTE6ODAwMHxlNjpkMDo3ODpmZDpmZTpiOTpjNDplZjpjOTo1Mzo3ZTpkOTo2NTplMDpiNTpjYnw0",
                "CAP_HOST_MANAGEMENT=1",
                "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
            ],
            "Cmd": null,
            "Image": "portainer/agent",
            "Volumes": null,
            "WorkingDir": "/app",
            "Entrypoint": [
                "./agent"
            ],
            "OnBuild": null,
            "Labels": {}
        },
        "NetworkSettings": {
            "Bridge": "",
            "SandboxID": "edf92e2d4e9c15593d3d7d9d0be4daaaa188cfd6e7636ce4732ca6984068373e",
            "HairpinMode": false,
            "LinkLocalIPv6Address": "",
            "LinkLocalIPv6PrefixLen": 0,
            "Ports": {},
            "SandboxKey": "/var/run/docker/netns/edf92e2d4e9c",
            "SecondaryIPAddresses": null,
            "SecondaryIPv6Addresses": null,
            "EndpointID": "52bc3a7c711d9e83e4ce3cd67475e580afc2b45742f8723f3d8012c320d3bf98",
            "Gateway": "172.17.0.1",
            "GlobalIPv6Address": "",
            "GlobalIPv6PrefixLen": 0,
            "IPAddress": "172.17.0.2",
            "IPPrefixLen": 16,
            "IPv6Gateway": "",
            "MacAddress": "02:42:ac:11:00:02",
            "Networks": {
                "bridge": {
                    "IPAMConfig": null,
                    "Links": null,
                    "Aliases": null,
                    "NetworkID": "e0b2b0ee3cc6521e22c12b8f9e78c6652f5a403b0e5fc89153fd657dee311090",
                    "EndpointID": "52bc3a7c711d9e83e4ce3cd67475e580afc2b45742f8723f3d8012c320d3bf98",
                    "Gateway": "172.17.0.1",
                    "IPAddress": "172.17.0.2",
                    "IPPrefixLen": 16,
                    "IPv6Gateway": "",
                    "GlobalIPv6Address": "",
                    "GlobalIPv6PrefixLen": 0,
                    "MacAddress": "02:42:ac:11:00:02",
                    "DriverOpts": null
                }
            }
        }
    }
# docker inspect -f {{.NetworkSettings.IPAddress}} portainer_edge_03
172.17.0.2
Work Blog » 05_Docker镜像基础
分享到:
赞(1) 打赏

评论抢沙发

评论前必须登录!

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏