- Posted on
- • Scripting for DevOps
How to Create Bash Scripts for Container Management (Docker)
- Author
-
-
- User
- Linux Bash
- Posts by this author
- Posts by this author
-
How to Create Bash Scripts for Container Management (Docker)
Bash scripts are an excellent way to automate Docker container management tasks, such as building images, running containers, and cleaning up resources. Below is a comprehensive guide on creating Bash scripts for managing Docker containers.
1. Prerequisites
- Docker Installed: Ensure Docker is installed and the Docker daemon is running.
- Basic Bash Knowledge: Familiarity with Bash commands and syntax.
- Docker CLI Knowledge: Understanding Docker commands like
docker run
,docker ps
, anddocker stop
.
2. Common Use Cases for Bash Scripts with Docker
- Automating the build and deployment of Docker images.
- Managing container lifecycles (start, stop, restart).
- Cleaning up unused containers, images, and volumes.
- Managing container logs.
- Orchestrating multi-container applications with Docker Compose.
3. Basic Structure of a Docker Management Script
A typical Bash script for Docker management includes: 1. Variable Initialization: Define reusable variables for image names, container names, etc. 2. Functions: Group tasks into reusable functions. 3. Execution Flow: Define the script's main workflow.
4. Example Scripts
Example 1: Build and Run a Docker Container
This script builds a Docker image and runs it as a container:
#!/bin/bash
set -e # Exit immediately if a command exits with a non-zero status.
# Variables
IMAGE_NAME="my-app"
CONTAINER_NAME="my-app-container"
DOCKERFILE_PATH="./Dockerfile"
PORT=8080
# Build the Docker image
echo "Building Docker image: $IMAGE_NAME..."
docker build -t $IMAGE_NAME -f $DOCKERFILE_PATH .
# Check if the container is already running
if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then
echo "Stopping existing container: $CONTAINER_NAME..."
docker stop $CONTAINER_NAME
fi
# Remove any existing containers with the same name
if [ "$(docker ps -aq -f name=$CONTAINER_NAME)" ]; then
echo "Removing existing container: $CONTAINER_NAME..."
docker rm $CONTAINER_NAME
fi
# Run the container
echo "Running the container $CONTAINER_NAME on port $PORT..."
docker run -d --name $CONTAINER_NAME -p $PORT:80 $IMAGE_NAME
echo "Container $CONTAINER_NAME is running and accessible on port $PORT."
Example 2: Clean Up Docker Resources
This script cleans up stopped containers, dangling images, and unused volumes:
#!/bin/bash
set -e
echo "Cleaning up Docker resources..."
# Remove stopped containers
echo "Removing stopped containers..."
docker container prune -f
# Remove unused images
echo "Removing unused images..."
docker image prune -f
# Remove unused volumes
echo "Removing unused volumes..."
docker volume prune -f
# Remove unused networks
echo "Removing unused networks..."
docker network prune -f
echo "Docker cleanup completed successfully!"
Example 3: Restart All Containers
This script restarts all running Docker containers:
#!/bin/bash
set -e
echo "Restarting all running Docker containers..."
# Get all running containers
CONTAINERS=$(docker ps -q)
# Restart each container
if [ -z "$CONTAINERS" ]; then
echo "No running containers found."
else
for CONTAINER in $CONTAINERS; do
echo "Restarting container: $CONTAINER..."
docker restart $CONTAINER
done
echo "All containers restarted."
fi
Example 4: Docker Compose Automation
This script automates deployment using Docker Compose:
#!/bin/bash
set -e
COMPOSE_FILE="docker-compose.yml"
# Pull the latest images
echo "Pulling latest images..."
docker-compose -f $COMPOSE_FILE pull
# Bring up the services
echo "Starting services with Docker Compose..."
docker-compose -f $COMPOSE_FILE up -d
# Show the status of the services
echo "Services running:"
docker-compose -f $COMPOSE_FILE ps
5. Tips for Writing Effective Scripts
Use Environment Variables: Store reusable values like image names and ports in environment variables.
IMAGE_NAME=${IMAGE_NAME:-"default-image"} PORT=${PORT:-8080}
Error Handling: Use
trap
to catch errors and handle them gracefully.trap 'echo "Error occurred on line $LINENO"; exit 1' ERR
Logging: Redirect script output to a log file for debugging.
exec > >(tee -i script.log) 2>&1
Interactive Prompts: Prompt users for input when needed.
read -p "Enter the container name: " CONTAINER_NAME
Reusable Functions: Break the script into modular functions.
restart_container() { echo "Restarting container $1..." docker restart $1 }
6. Best Practices for Docker Management Scripts
- Idempotency: Ensure scripts can run multiple times without causing issues.
- Modular Design: Group tasks into reusable functions.
- Documentation: Add comments explaining each step of the script.
- Test Before Use: Test scripts in a non-production environment.
- Use Secure Secrets Management: Avoid hardcoding sensitive information like credentials.
7. Complete Example: All-in-One Management Script
#!/bin/bash
set -e
IMAGE_NAME="my-app"
CONTAINER_NAME="my-app-container"
PORT=8080
# Build Docker image
build_image() {
echo "Building Docker image: $IMAGE_NAME..."
docker build -t $IMAGE_NAME .
}
# Stop and remove container
stop_container() {
if [ "$(docker ps -q -f name=$CONTAINER_NAME)" ]; then
echo "Stopping container: $CONTAINER_NAME..."
docker stop $CONTAINER_NAME
fi
if [ "$(docker ps -aq -f name=$CONTAINER_NAME)" ]; then
echo "Removing container: $CONTAINER_NAME..."
docker rm $CONTAINER_NAME
fi
}
# Run container
run_container() {
echo "Running container: $CONTAINER_NAME..."
docker run -d --name $CONTAINER_NAME -p $PORT:80 $IMAGE_NAME
echo "Container is running on port $PORT."
}
# Clean up unused resources
clean_up() {
echo "Cleaning up unused resources..."
docker container prune -f
docker image prune -f
docker volume prune -f
}
# Main script flow
build_image
stop_container
run_container
clean_up
This script builds a Docker image, stops and removes any existing containers, runs a new container, and cleans up unused resources.