Master Docker Management with a Powerful Bash Automation Script
This article provides a comprehensive, enhanced Docker automation Bash script—docker‑manager.sh—covering container lifecycle commands, image cleanup, backup, network inspection, log viewing, and configuration export, along with step‑by‑step usage instructions and additional handy Docker commands for efficient container management.
Enhanced Docker Management Script
This script, docker-manager.sh, offers an all‑in‑one command‑line tool for routine Docker operations. It includes functions for listing containers, starting/stopping/restarting all containers, cleaning up unused resources, showing resource statistics, updating containers, backing up volumes, displaying network information, viewing logs, executing an interactive shell, exporting container configuration to JSON, and inspecting running processes.
#!/bin/bash
# Docker 管理脚本集合(增强版)
# 用法: ./docker-manager.sh [command] [options]
set -e
# 彩色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# 显示使用说明
usage() {
echo -e "${BLUE}Docker 管理脚本${NC}"
echo "用法: $0 [command]"
echo ""
echo "命令:"
echo " list 列出所有容器"
echo " start-all 启动所有容器"
echo " stop-all 停止所有容器"
echo " restart-all 重启所有容器"
echo " cleanup 清理无用镜像和容器"
echo " stats 显示容器资源使用情况"
echo " update [name] 更新指定容器(拉取新镜像并重启)"
echo " backup [path] 备份所有容器的数据卷(默认: ./backups)"
echo " network 显示网络信息"
echo " logs [name] 查看容器日志(默认显示所有容器日志)"
echo " exec [name] 进入容器交互式终端"
echo " export [name] 导出容器配置到 JSON"
echo " top [name] 查看容器内进程"
echo ""
}
# 检查 Docker 是否可用
check_docker() {
if ! command -v docker &>/dev/null; then
echo -e "${RED}错误:${NC} 未找到 Docker,请先安装 Docker"
exit 1
fi
}
# 列出容器
list_containers() {
echo -e "${YELLOW}正在运行的容器:${NC}"
docker ps --format "table {{.ID}} {{.Names}} {{.Image}} {{.Status}} {{.Ports}}"
echo -e "
${YELLOW}所有容器:${NC}"
docker ps -a --format "table {{.ID}} {{.Names}} {{.Image}} {{.Status}} {{.Ports}}"
}
# 启动所有容器
start_all_containers() {
containers=$(docker ps -aq)
if [ -z "$containers" ]; then
echo "没有容器可启动"
return
fi
echo "正在启动所有容器..."
docker start $containers
echo -e "${GREEN}所有容器已启动${NC}"
}
# 停止所有容器
stop_all_containers() {
containers=$(docker ps -q)
if [ -z "$containers" ]; then
echo "没有正在运行的容器"
return
fi
echo "正在停止所有容器..."
docker stop $containers
echo -e "${GREEN}所有容器已停止${NC}"
}
# 重启所有容器
restart_all_containers() {
containers=$(docker ps -q)
if [ -z "$containers" ]; then
echo "没有正在运行的容器"
return
fi
echo "正在重启所有容器..."
docker restart $containers
echo -e "${GREEN}所有容器已重启${NC}"
}
# 清理无用资源
cleanup_docker() {
echo "清理无用容器..."
docker container prune -f
echo "清理无用镜像..."
docker image prune -af
echo "清理无用网络..."
docker network prune -f
echo "清理无用卷..."
docker volume prune -f
echo -e "${GREEN}清理完成${NC}"
}
# 显示资源使用情况
show_stats() {
docker stats --no-stream
}
# 更新容器
update_container() {
if [ -z "$1" ]; then
echo "错误: 需要指定容器名称"
exit 1
fi
container_name=$1
echo "正在更新容器: $container_name"
image_name=$(docker inspect --format='{{.Config.Image}}' $container_name)
echo "拉取最新镜像: $image_name"
docker pull $image_name
echo "停止并删除容器: $container_name"
docker stop $container_name
docker rm $container_name
echo -e "${YELLOW}请手动重新运行容器,因为运行参数可能不同${NC}"
echo "示例: docker run -d --name $container_name [其他参数] $image_name"
}
# 备份数据卷
backup_volumes() {
backup_path=${1:-./backups}
mkdir -p $backup_path
echo "备份数据卷到: $backup_path"
for container in $(docker ps -aq); do
container_name=$(docker inspect --format='{{.Name}}' $container | sed 's/\///g')
volumes=$(docker inspect -f '{{range .Mounts}}{{if .Name}}{{.Name}} {{end}}{{end}}' $container_name)
if [ ! -z "$volumes" ]; then
echo "备份容器 $container_name 的数据卷..."
for volume in $volumes; do
echo "备份卷: $volume"
docker run --rm -v $volume:/source -v $backup_path:/backup alpine \
tar -czf /backup/${container_name}_${volume}_$(date +%Y%m%d_%H%M%S).tar.gz -C /source .
done
fi
done
echo -e "${GREEN}备份完成${NC}"
}
# 显示网络信息
show_network() {
echo "Docker 网络:"
docker network ls
echo -e "
容器网络详情:"
for network in $(docker network ls -q); do
echo "网络 $(docker network inspect -f '{{.Name}}' $network):"
docker network inspect -f '{{range .Containers}}{{.Name}} {{end}}' $network
echo ""
done
}
# 查看容器日志
view_logs() {
if [ -z "$1" ]; then
echo "显示所有容器日志 (Ctrl+C 退出)..."
docker-compose logs -f || docker logs -f $(docker ps -q)
else
container_name=$1
echo "显示容器 $container_name 日志 (Ctrl+C 退出)..."
docker logs -f $container_name
fi
}
# 进入容器
exec_container() {
if [ -z "$1" ]; then
echo "错误: 需要指定容器名称"
exit 1
fi
docker exec -it $1 /bin/bash || docker exec -it $1 sh
}
# 导出容器配置
export_container() {
if [ -z "$1" ]; then
echo "错误: 需要指定容器名称"
exit 1
fi
docker inspect $1 > ${1}_config.json
echo "容器配置已导出到 ${1}_config.json"
}
# 查看容器进程
top_container() {
if [ -z "$1" ]; then
echo "错误: 需要指定容器名称"
exit 1
fi
docker top $1
}
# 主程序入口
check_docker
case "${1:-}" in
list|ls) list_containers ;;
start-all) start_all_containers ;;
stop-all) stop_all_containers ;;
restart-all) restart_all_containers ;;
cleanup) cleanup_docker ;;
stats|st) show_stats ;;
update) update_container "$2" ;;
backup) backup_volumes "$2" ;;
network) show_network ;;
logs) view_logs "$2" ;;
exec) exec_container "$2" ;;
export) export_container "$2" ;;
top) top_container "$2" ;;
*) usage; exit 1 ;;
esac
exit 0How to Use the Script
Save the script as docker-manager.sh.
Make it executable: chmod +x docker-manager.sh.
Run it with the desired command, e.g., ./docker-manager.sh list.
Supported Commands
list / ls : List all containers (running and stopped).
start-all : Start every container.
stop-all : Stop every container.
restart-all : Restart every container.
cleanup : Remove unused images, containers, networks, and volumes.
stats / st : Show real‑time resource usage.
update [name] : Pull the latest image for a container and restart it.
backup [path] : Backup all container volumes (default ./backups).
network : Display Docker network information.
logs [name] : View logs for a specific container or all containers.
exec [name] : Open an interactive shell inside a container.
export [name] : Export a container's configuration to a JSON file.
top [name] : List processes running inside a container.
Additional Handy Docker Commands
# Real‑time container stats
docker stats
# Show image layer sizes
docker image ls --format "table {{.Repository}} {{.Tag}} {{.Size}}"
# Stop and delete all containers in one line
docker stop $(docker ps -aq) && docker rm $(docker ps -aq)
# Delete all unused images
docker image prune -a
# Show disk usage summary
docker system df
# Get container IP address
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name
# Execute a command inside a container
docker exec -it container_name /bin/bashWith this enhanced docker-manager.sh you can manage a Docker environment almost as easily as using a dedicated CLI tool.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Ray's Galactic Tech
Practice together, never alone. We cover programming languages, development tools, learning methods, and pitfall notes. We simplify complex topics, guiding you from beginner to advanced. Weekly practical content—let's grow together!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
