关注公众号「Linux 容器运维」,回复【对应关键词】(如 docker/k8s/linux/ 面试),即可获取完整版干货,复制到生产环境直接使用~ 更多内容已同步至【公众号官方合集】,点击公众号主页「合集」→「kubernetes」,即可查看全部最新内容,持续更新中~
说明:
- 默认行为:如果不指定任何参数,脚本将使用 Docker。
- 指定
-c参数时:脚本会切换为使用containerd导出镜像。
使用方法:
-
默认使用 Docker:
./export_images.sh -
使用
containerd导出镜像:./export_images.sh -c
脚本只做镜像到处使用,需要自己提前安装docker或者containerd 才可以使用这个脚本
#!/bin/bash
# 默认使用 Docker
use_containerd=false
# 处理命令行参数
while getopts "c" opt; do
case $opt in
c)
use_containerd=true
;;
*)
echo "Usage: $0 [-c] (Use containerd instead of Docker)"
exit 1
;;
esac
done
# 创建镜像存储目录
EXPORT_DIR="./exported_images"
mkdir -p "$EXPORT_DIR"
# 根据选择使用 Docker 或 containerd 拉取镜像
if $use_containerd; then
echo "使用 containerd 导出镜像"
# 列出所有镜像
images=$(crictl images | awk '{print $1 ":" $2}' | grep -v 'IMAGE')
# 逐个导出镜像
for image in $images; do
# 将镜像名称中的 ":" 替换为 "_"
sanitized_image_name=$(echo "$image" | tr '/' '-'|tr ':' '-')
exported_images="$EXPORT_DIR/${sanitized_image_name}.tar"
# 导出镜像
echo "正在导出镜像 $image 到 $exported_images ..."
ctr -n k8s.io i export "$exported_images" "$image"
if [ $? -eq 0 ]; then
echo "镜像 $image 导出成功!"
else
echo "镜像 $image 导出失败!"
fi
done
else
echo "使用 Docker 导出镜像"
# 列出所有镜像
images=$(docker images --format "{{.Repository}}:{{.Tag}}")
# 逐个导出镜像
for image in $images; do
# 将镜像名称中的 ":" 替换为 "_"
sanitized_image_name=$(echo "$image" | tr '/' '-'|tr ':' '-')
exported_images="$EXPORT_DIR/${sanitized_image_name}.tar"
# 导出镜像
echo "正在导出镜像 $image 到 $exported_images ..."
docker save -o "$exported_images" "$image"
if [ $? -eq 0 ]; then
echo "镜像 $image 导出成功!"
else
echo "镜像 $image 导出失败!"
fi
done
fi