根据容器制作镜像

目标任务

制作一个含有git的centos镜像(由centos镜像生成的容器原本不含有git)。

拉取centos镜像

  1. docker pull centos

结果:

  1. [root@localhost /]# docker pull centos
  2. Using default tag: latest
  3. latest: Pulling from library/centos
  4. 7a0437f04f83: Pull complete
  5. Digest: sha256:5528e8b1b1719d34604c87e11dcd1c0a20bedf46e83b5632cdeac91b8c04efc1
  6. Status: Downloaded newer image for centos:latest
  7. docker.io/library/centos:latest

查看镜像

  1. docker images

结果:

  1. [root@localhost /]# docker images
  2. REPOSITORY TAG IMAGE ID CREATED SIZE
  3. centos latest 300e315adb2f 2 months ago 209MB // 拉取到的centos镜像

利用centos镜像启动一个容器

  1. docker run -it centos:latest /bin/bash

如果启动容器成功,则会进入一个新环境。
如下,可以看出前面命令行形式发生了改变:

  1. [root@localhost /]# docker run -it centos /bin/bash
  2. [root@f395c3935267 /]# git version // 这一行前面[]内发生了改变,说明进入了新环境
  3. bash: git: command not found // 此时新环境中并没有git

在新环境中安装git并退出环境

  1. [root@f395c3935267 /]# yum install git -y // 安装git
  2. [root@f395c3935267 /]# git version // 此时新环境git安装好了
  3. git version 2.27.0
  4. [root@f395c3935267 /]# exit // 退出新环境
  5. exit

查看容器

  1. docker ps -a

结果:

  1. [root@localhost /]# docker ps -a
  2. CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
  3. f395c3935267 centos "/bin/bash" 6 minutes ago Exited (130) 29 seconds ago magical_almeida

可以看到一个已退出的容器。

将容器转为镜像

  1. docker commit -m "centos with git" -a "ys" f395c3935267 ys/centos:v1
  • -m:指定说明信息
  • -a:指定作者
  • f395c3935267:代表容器id,这里就是刚装了git的centos镜像的容器的id。
  • ys/centos:v1:指定镜像的作者、仓库名和tag信息。

此时再查看此时docker中已有的镜像:

  1. [root@localhost /]# docker images
  2. REPOSITORY TAG IMAGE ID CREATED SIZE
  3. ys/centos v1 9f2192566d0d 8 seconds ago 328MB
  4. centos latest 300e315adb2f 2 months ago 209MB

发现已经有我们刚制作的镜像了。

验证

  1. [root@localhost /]# docker run -it ys/centos:v1 /bin/bash
  2. [root@f757e78b8460 /]# git version
  3. git version 2.27.0

用刚制作好的镜像生成容器运行,发现自带git,完成目标任务。

根据镜像制作镜像

目标任务

和上面一样,制作一个含有git的centos镜像。(原生centos镜像生成的容器中并无git)

建立Dockerfile文件

  1. # 说明制作的镜像以哪个镜像为基础
  2. FROM centos:latest
  3. # 构建者的基本信息
  4. MAINTAINER yushang
  5. # 在制作这个镜像时需要执行的操作
  6. RUN yum update
  7. RUN yum install -y git
  8. # 拷贝本地文件到镜像中
  9. COPY ./* /usr/share/gitdir/

构建镜像

  1. docker build -t="yushang/centos:gitdir" .
  • -t:制定新镜像的仓库名、镜像名、版本号tag等
  • .:在当前目录下寻找Dockerfile文件

查看镜像

  1. [root@localhost ~]# docker images
  2. REPOSITORY TAG IMAGE ID CREATED SIZE
  3. yushang/centos gitdir 752522b80efe 22 seconds ago 328MB

验证镜像

通过新生成的镜像启动一个容器:

  1. [root@localhost ~]# docker run -it 752522b80efe /bin/bash
  2. [root@4f59c56f15d3 /]# git version // 验证出制作的镜像生成的容器含有git
  3. git version 2.27.0

可以看出新制作的镜像含有git,目标任务完成。