DEV Community

Kishore Suzil
Kishore Suzil

Posted on

1 1 1

Monitor Docker Logs in Real-Time with a Simple Bash Script

Step 1: Ensure Docker is Installed and Running

Make sure you have Docker installed and running on your system.

To check if Docker is installed, run:

docker --version
Enter fullscreen mode Exit fullscreen mode

To verify if Docker is running, use:

docker ps
Enter fullscreen mode Exit fullscreen mode

If Docker is not running, start it using:

sudo systemctl start docker
Enter fullscreen mode Exit fullscreen mode

Step 2: Create the Log Monitoring Script

Open a terminal and create a new script file:

vim monitor_docker_logs.sh
Enter fullscreen mode Exit fullscreen mode

Copy and paste the following script into the file:

#!/bin/bash

# Define log file
LOG_FILE="consolidated_logs.log"
ERROR_LOG_FILE="error_logs.log"

# Get list of all running containers
CONTAINERS=$(docker ps --format "{{.Names}}")

# Check if containers are running
if [ -z "$CONTAINERS" ]; then
    echo "No running containers found. Exiting..."
    exit 1
fi

# Clear previous log files
echo "" > $LOG_FILE
echo "" > $ERROR_LOG_FILE

# Collect logs from all running containers
echo "Collecting logs..."
for CONTAINER in $CONTAINERS; do
    echo "--- Logs from $CONTAINER ---" >> $LOG_FILE
    docker logs --tail 100 $CONTAINER >> $LOG_FILE 2>&1
    echo "\n" >> $LOG_FILE
done

echo "Logs consolidated in $LOG_FILE"

# Monitor logs for errors
echo "Scanning for errors..."
grep -i "error" $LOG_FILE > $ERROR_LOG_FILE

if [ -s $ERROR_LOG_FILE ]; then
    echo "Errors found! Check $ERROR_LOG_FILE for details."
else
    echo "No errors found."
fi

# Real-time monitoring (optional)
echo "Monitoring logs in real-time..."
tail -f $LOG_FILE
Enter fullscreen mode Exit fullscreen mode

Step 3: Grant Execute Permissions

Make the script executable by running:

chmod +x monitor_docker_logs.sh
Enter fullscreen mode Exit fullscreen mode

Step 4: Run the Script

Start the script by executing:

./monitor_docker_logs.sh
Enter fullscreen mode Exit fullscreen mode

Step 5: Check the Log Files

Once the script runs, it will generate two log files:

  • consolidated_logs.log → Contains all logs from running containers.
  • error_logs.log → Extracts error messages from the logs.

To view the logs, use:

cat consolidated_logs.log
Enter fullscreen mode Exit fullscreen mode

To check for errors, use:

cat error_logs.log
Enter fullscreen mode Exit fullscreen mode

Step 6: Keep Monitoring Logs in Real-Time (Optional)

To continuously monitor logs, use:

tail -f consolidated_logs.log
Enter fullscreen mode Exit fullscreen mode

Step 7: Stop the Script

If you want to stop real-time monitoring, press CTRL + C.


Top comments (0)