Skip to content

Instantly share code, notes, and snippets.

@javimosch
Last active June 25, 2024 07:18
Show Gist options
  • Select an option

  • Save javimosch/4bc6363f63b4c445b946807920a42702 to your computer and use it in GitHub Desktop.

Select an option

Save javimosch/4bc6363f63b4c445b946807920a42702 to your computer and use it in GitHub Desktop.
A bash script that rotates Docker container logs when they exceed a specified size threshold (5MB by default), helping to prevent log files from growing indefinitely and causing disk space issues. #Docker #LogRotation #DevOps #Containerization #Linux #Scripting #/bash #Automation #LogManagement #SystemAdministration
#!/bin/bash
# Function to convert bytes to megabytes
bytes_to_mb() {
echo $(( $1 / 1024 / 1024 ))
}
# Set log rotation size threshold (in bytes)
MAX_SIZE=$((5 * 1024 * 1024)) # 5MB
echo "Starting Docker container log rotation script..."
echo "Log rotation threshold: 5MB"
# Get all running containers
containers=$(docker ps -q)
echo "Checking logs for $(echo "$containers" | wc -w) running containers..."
for container in $containers; do
echo "Processing container: $container"
# Get container name
container_name=$(docker inspect --format '{{.Name}}' "$container" | sed 's/\///')
echo "Container name: $container_name"
# Get log file path
log_file=$(docker inspect --format '{{.LogPath}}' "$container")
echo "Log file path: $log_file"
# Check if log file exists
if [ -f "$log_file" ]; then
# Get current log size
current_size=$(du -b "$log_file" | cut -f1)
current_size_mb=$(bytes_to_mb $current_size)
echo "Current log size: ${current_size_mb}MB"
# Check if log size exceeds threshold
if [ $current_size -gt $MAX_SIZE ]; then
echo "Log size exceeds threshold. Rotating log..."
# Rotate log
mv "$log_file" "${log_file}.old"
# Restart container to create new log file
docker restart "$container"
echo "Container ${container_name}|${container} log file was rotated from ${current_size_mb}MB"
else
echo "Log size is within threshold. No rotation needed."
fi
else
echo "Log file not found. Skipping..."
fi
echo "Finished processing container: $container"
echo "----------------------------------------"
done
echo "Docker container log rotation completed."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment