前言
由于国内无法访问 dockerhub,而且国内的 docker 镜像源全部下线。导致我们使用 docker 非常困难。之前都是通过 docker pull 拉取想要的基础镜像,然后加入一些自己需要的配置或软件,就形成了自己的镜像,但是最底层的基础镜像怎么来的呢。正好借此机会研究下如何从零构建镜像。调研后,发现所谓的基础镜像,就是在空镜像(scratch)上叠加一套根文件系统(rootfs)。各Linux发行版的基础镜像就可以作为 rootfs。接下来我们将 ubuntu-base 作为 rootfs,通过 podman 构建自己的基础镜像(Podman 和 Docker 的用法基本一致)。
核心原理
scratch是空镜像,需手动添加 Ubuntu 根文件系统(rootfs) 作为基础层;- 通过
ADD指令将 Ubuntu 官方 rootfs 压缩包解压到镜像根目录;
安装 podman
下载 ubuntu-base 镜像
Ubuntu官方站点:cdimage.ubuntu.com/ubuntu-base…
华为镜像源:mirrors.huaweicloud.com/ubuntu-cdim…
Dockerfile
# 从 scratch 构建
FROM scratch
# 添加 ubuntu 根文件系统
ADD ubuntu-base-22.04-base-amd64.tar.gz /
# 更换软件源 & 更新软件
RUN sed -i "s@http://.*archive.ubuntu.com@http://mirrors.huaweicloud.com@g" /etc/apt/sources.list; \
sed -i "s@http://.*security.ubuntu.com@http://mirrors.huaweicloud.com@g" /etc/apt/sources.list; \
apt update -y;
# 容器启动命令
CMD ["bash"]
目录结构
<WORK_DIR>
└─ Containerfile # Podman 构建容器镜像的指令文件,语法与 Dockerfile 完全兼容。也可以用 Dockerfile
└─ ubuntu-base-22.04-base-amd64.tar.gz # ubuntu rootfs 压缩包
构建基础镜像
# 构建
podman build -t ubuntu:22.04 .
# 测试
podman run --rm ubuntu:22.04 cat /etc/os-release
# 查看操作系统信息
podman run --rm ubuntu:22.04 cat /etc/os-release
# 使用 bash(通过 exit 命令退出)
podman run --rm -it ubuntu:22.04 bash
构建 nginx 镜像
Dockerfile:
FROM ubuntu:22.04
EXPOSE 80
# 安装 nginx
RUN apt-get install nginx -y;
# 容器启动命令
CMD ["nginx", "-g", "daemon off;"]
构建:
podman build -t nginx -f ./Containerfile_nginx .
运行:
podman run --name nginx -p 80:80 -d nginx
构建 redis 镜像
Dockerfile:
FROM ubuntu:22.04
# 安装 redis
RUN echo "vm.overcommit_memory = 1" >> /etc/sysctl.conf; \
apt-get install redis -y;
EXPOSE 6379
# 容器启动命令
CMD ["redis-server"]
构建:
podman build -t redis -f ./Containerfile_redis .
运行:
podman run --name redis -d redis
总结
通过 scratch + Ubuntu-base 的方式我们构建了自己的 ubuntu 基础镜像,之后我们可以基于该基础镜像,构建各种应用镜像了。