Container_automation
Chapter 40: Container Automation Scripts
Section titled “Chapter 40: Container Automation Scripts”Overview
Section titled “Overview”This chapter covers container automation scripts using Docker and Podman. These scripts are essential for DevOps engineers managing containerized applications.
Docker Basics
Section titled “Docker Basics”Common Docker Commands
Section titled “Common Docker Commands”# Container managementdocker ps # List running containersdocker ps -a # List all containersdocker run # Run a containerdocker start # Start a containerdocker stop # Stop a containerdocker rm # Remove a container
# Image managementdocker images # List imagesdocker pull # Pull an imagedocker rmi # Remove an imagedocker build # Build an image
# Logs and statsdocker logs # Container logsdocker stats # Container statsdocker exec # Execute command in containerContainer Management Scripts
Section titled “Container Management Scripts”List Containers
Section titled “List Containers”#!/usr/bin/env bash# list_containers.sh - List all containers
docker ps -a --format "table {{.ID}}\t{{.Names}}\t{{.Status}}\t{{.Image}}\t{{.Ports}}"Container Health Check
Section titled “Container Health Check”#!/usr/bin/env bash# check_container_health.sh - Check container health
set -euo pipefail
CONTAINER="${1:-}"
if [[ -z "$CONTAINER" ]]; then echo "Usage: $0 <container_name>" exit 1fi
# Check if container is runningif docker ps --format '{{.Names}}' | grep -q "^${CONTAINER}$"; then echo "Container $CONTAINER is running"
# Check health status health=$(docker inspect --format='{{.State.Health.Status}}' "$CONTAINER" 2>/dev/null || echo "none") echo "Health status: $health"
exit 0else echo "Container $CONTAINER is not running" exit 1fiDocker Compose Scripts
Section titled “Docker Compose Scripts”Start/Stop Services
Section titled “Start/Stop Services”#!/usr/bin/env bash# docker_services.sh - Manage docker-compose services
set -euo pipefail
COMPOSE_FILE="${COMPOSE_FILE:-docker-compose.yml}"ACTION="${1:-up}"
case "$ACTION" in up) echo "Starting services..." docker-compose -f "$COMPOSE_FILE" up -d ;; down) echo "Stopping services..." docker-compose -f "$COMPOSE_FILE" down ;; restart) echo "Restarting services..." docker-compose -f "$COMPOSE_FILE" restart ;; logs) echo "Showing logs..." docker-compose -f "$COMPOSE_FILE" logs -f ;; *) echo "Usage: $0 {up|down|restart|logs}" exit 1 ;;esacContainer Monitoring
Section titled “Container Monitoring”Resource Usage
Section titled “Resource Usage”#!/usr/bin/env bash# container_stats.sh - Show container resource usage
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}\t{{.NetIO}}\t{{.BlockIO}}"Container Logs
Section titled “Container Logs”#!/usr/bin/env bash# container_logs.sh - View container logs
set -euo pipefail
CONTAINER="${1:-}"LINES="${2:-100}"
if [[ -z "$CONTAINER" ]]; then echo "Usage: $0 <container> [lines]" exit 1fi
docker logs --tail "$LINES" -f "$CONTAINER"Image Management
Section titled “Image Management”Cleanup Images
Section titled “Cleanup Images”#!/usr/bin/env bash# cleanup_images.sh - Clean up unused Docker images
set -euo pipefail
echo "Cleaning up Docker resources..."
# Remove stopped containersecho "Removing stopped containers..."docker container prune -f
# Remove unused imagesecho "Removing unused images..."docker image prune -a -f
# Remove unused volumesecho "Removing unused volumes..."docker volume prune -f
# Remove unused networksecho "Removing unused networks..."docker network prune -f
echo "Cleanup complete"Build and Tag
Section titled “Build and Tag”#!/usr/bin/env bash# build_image.sh - Build and tag Docker image
set -euo pipefail
IMAGE_NAME="${1:-}"TAG="${2:-latest}"DOCKERFILE="${3:-Dockerfile}"CONTEXT="${4:-.}"
if [[ -z "$IMAGE_NAME" ]]; then echo "Usage: $0 <image_name> [tag] [dockerfile] [context]" exit 1fi
echo "Building image: $IMAGE_NAME:$TAG"
docker build \ -t "$IMAGE_NAME:$TAG" \ -f "$DOCKERFILE" \ "$CONTEXT"
echo "Image built successfully"Docker Registry
Section titled “Docker Registry”Push to Registry
Section titled “Push to Registry”#!/usr/bin/env bash# push_image.sh - Push image to registry
set -euo pipefail
IMAGE="${1:-}"REGISTRY="${REGISTRY:-docker.io}"
if [[ -z "$IMAGE" ]]; then echo "Usage: $0 <image> [registry]" exit 1fi
echo "Pushing $IMAGE to $REGISTRY..."
docker tag "$IMAGE" "$REGISTRY/$IMAGE"docker push "$REGISTRY/$IMAGE"
echo "Image pushed successfully"Pull Latest
Section titled “Pull Latest”#!/usr/bin/env bash# pull_latest.sh - Pull latest image
set -euo pipefail
IMAGE="${1:-}"
if [[ -z "$IMAGE" ]]; then echo "Usage: $0 <image>" exit 1fi
echo "Pulling latest $IMAGE..."
docker pull "$IMAGE"
echo "Image pulled successfully"Backup and Restore Containers
Section titled “Backup and Restore Containers”Backup Container
Section titled “Backup Container”#!/usr/bin/env bash# backup_container.sh - Backup container data
set -euo pipefail
CONTAINER="${1:-}"BACKUP_DIR="${2:-/tmp/container_backups}"
if [[ -z "$CONTAINER" ]]; then echo "Usage: $0 <container> [backup_dir]" exit 1fi
mkdir -p "$BACKUP_DIR"
timestamp=$(date +%Y%m%d_%H%M%S)backup_file="$BACKUP_DIR/${CONTAINER}_${timestamp}.tar.gz"
echo "Backing up container $CONTAINER..."
docker export "$CONTAINER" | gzip > "$backup_file"
echo "Backup created: $backup_file"Multi-Container Management
Section titled “Multi-Container Management”Deploy Stack
Section titled “Deploy Stack”#!/usr/bin/env bash# deploy_stack.sh - Deploy Docker stack
set -euo pipefail
STACK_NAME="${1:-myapp}"COMPOSE_FILE="${2:-docker-compose.yml}"
echo "Deploying stack: $STACK_NAME"
docker stack deploy -c "$COMPOSE_FILE" "$STACK_NAME"
echo "Stack deployed successfully"docker stack ps "$STACK_NAME"Health Checks
Section titled “Health Checks”Container Health Monitor
Section titled “Container Health Monitor”#!/usr/bin/env bash# monitor_containers.sh - Monitor container health
set -euo pipefail
ALERT_EMAIL="${ALERT_EMAIL:-admin@example.com}"
check_containers() { local unhealthy=0
for container in $(docker ps --format '{{.Names}}'); do health=$(docker inspect --format='{{.State.Health.Status}}' "$container" 2>/dev/null || echo "none")
if [[ "$health" == "unhealthy" ]]; then echo "ALERT: $container is unhealthy" ((unhealthy++)) fi done
if [[ $unhealthy -gt 0 ]]; then echo "Sending alert..." # Send alert email echo "$unhealthy containers are unhealthy" | mail -s "Container Alert" "$ALERT_EMAIL" return 1 fi
echo "All containers healthy" return 0}
check_containersSummary
Section titled “Summary”In this chapter, you learned:
- ✅ Docker basics and common commands
- ✅ Container management scripts
- ✅ Docker Compose automation
- ✅ Container monitoring
- ✅ Image management and cleanup
- ✅ Docker registry operations
- ✅ Container backup and restore
- ✅ Multi-container deployment
- ✅ Health check monitoring
Next Steps
Section titled “Next Steps”Continue to the next chapter to learn about Coprocesses.
Previous Chapter: Network Diagnostics Scripts Next Chapter: Coprocesses