Docker-05-容器导入导出需求分析实施Tip

「这是我参与11月更文挑战的第6天,活动详情查看:2021最后一次更文挑战」。

容器的简单操作相信你已经掌握了,现在有一个需求,我们希望能够在 ubuntu 的容器中搭建 python 运行环境,并且要将这个镜像保存下来,方便给新同事直接使用。

需求分析

  1. 启动 ubuntu 容器
  2. 安装 python 并测试
  3. 容器导出为镜像包
  4. 使用导出的镜像包创建容器并测试
  5. 发布

实施

启动容器

root@phyger-VirtualBox:~# docker run --name ubuntu_py --net host -it ubuntu /bin/bash
root@phyger-VirtualBox:/#
复制代码

注意参数:

  • --name ubuntu_py:指定容器名称

  • --net host:指定容器网络类型(后续详解)

安装 python

1、将本地/etc/apt/sources.list 拷贝到容器中。

docker cp /etc/apt/sources.list 1cdae865d767:/etc/apt/
复制代码

后续操作都是在容器内进行。

2、获取软件列表 apt-get update

root@phyger-VirtualBox:/# apt-get update
Get:1 http://mirrors.tuna.tsinghua.edu.cn/ubuntu bionic-updates InRelease [88.7 kB]
Get:2 后续省略
复制代码

3、安装 python

root@phyger-VirtualBox:/# apt-get install python3.8
Reading package lists... Done
Building dependency tree
Reading state information... Done
后续省略
复制代码

4、测试

root@phyger-VirtualBox:/# python
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
复制代码

容器中 python 安装成功。

导出容器为镜像

命令:docker export <containerID> xxx.tar

root@phyger-VirtualBox:/home/phyger# docker ps
CONTAINER ID        IMAGE               COMMAND             CREATED             STATUS              PORTS               NAMES
1cdae865d767        ubuntu              "/bin/bash"         22 minutes ago      Up 22 minutes                           ubuntu_py
root@phyger-VirtualBox:/home/phyger# docker export 1cdae865d767 > ubuntu_py.tar
root@phyger-VirtualBox:/home/phyger# ls | grep *.tar
ubuntu_py.tar
root@phyger-VirtualBox:/home/phyger#
复制代码

导入镜像

命令:docker import xxx.tar name:version

root@phyger-VirtualBox:/home/phyger# docker import ubuntu_py.tar my_ubuntu:v5
sha256:0383424243326866c32cfbce134ee2cd63321254c1a13c4715ea1dc2b1970f7a
root@phyger-VirtualBox:/home/phyger# docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
my_ubuntu           v5                  038342424332        11 seconds ago      141MB
alpine              latest              a24bb4013296        2 weeks ago         5.57MB
ubuntu              latest              1d622ef86b13        8 weeks ago         73.9MB
hello-world         latest              bf756fb1ae65        5 months ago        13.3kB
root@phyger-VirtualBox:/home/phyger#
复制代码

my_ubuntu:v5 镜像导入成功,镜像从之前的 73.9MB 变为了 141MB

使用新镜像创建虚机并测试:

root@phyger-VirtualBox:/home/phyger# docker run -it --name test_py my_ubuntu:v5 /bin/bash
root@8dfd0b202d7e:/# python
Python 3.8.0 (default, Oct 28 2019, 16:14:01)
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
复制代码

到此,这个需求完成,我们只需要将 ubuntu_py.tar 保存到版本仓库即可。

Tip

有些同学可能对镜像的导入导出和保存加载有所混淆,镜像的导入导出(export、import)是针对容器的操作,即将某一时刻的某状态的容器保存为一个镜像,在其他地方导入后可以拉起一个和此刻状态一致的容器,类似快照。而镜像的保存和加载(save、load)是针对镜像的操作,即镜像的复制,类似拷贝粘贴。