备份容器
前提条件
容器没有挂载磁盘,即所有数据都是保存在容器内部
创建备份脚本
nona backup_docker_container.sh
#!/bin/bash
# 检查是否提供了容器名称参数
if [ -z "$1" ]; then
echo "Usage: $0 <container_name>"
exit 1
fi
# 获取容器名称参数
container_name="$1"
# 获取当前日期和时间(格式为 YYYY-MM-DD_HH-MM-SS)
current_date=$(date "+%Y-%m-%d_%H-%M-%S")
# 定义输出文件路径
output_file="./container_backup_${container_name}_${current_date}.tar"
# 检查容器是否存在
if ! docker inspect "$container_name" > /dev/null 2>&1; then
echo "Error: Container '$container_name' does not exist."
exit 1
fi
# 导出容器
docker export "$container_name" > "$output_file"
# 检查是否成功导出
if [ $? -eq 0 ]; then
echo "Container backup successful: $output_file"
else
echo "Container backup failed"
exit 1
fi
运行备份
chmod +x backup_docker_container.sh
./backup_docker_container.sh gitlab
输出文件如:container_backup_gitlab_2025-03-13_09-11-29.tar
恢复备份
创建恢复脚本
nano restore_docker_container.sh
#!/bin/bash
tar_file_path="$1"
image_name="$2"
image_tag=$(date "+%Y-%m-%d_%H-%M-%S")
docker import "$tar_file_path" "${image_name}:${image_tag}"
if [ $? -ne 0 ]; then
echo "Error: Failed to import tar file."
exit 1
fi
echo "Image imported successfully: ${image_name}:${image_tag}"
echo "Then you should run container like this: "
echo "docker run -d --name container_name -p 3000:3000 -p 2222:22 ${image_name}:${image_tag}"
运行恢复脚本
chmod +x restore_docker_container.sh
./restore_docker_container.sh container_backup_gitlab_2025-03-13_09-11-29.tar image_name