- Posted on
- • Containers
Using Bash to monitor running Docker containers
- Author
-
-
- User
- Linux Bash
- Posts by this author
- Posts by this author
-
Using Bash to Monitor Running Docker Containers: A Comprehensive Guide
Docker has undoubtedly changed the development landscape by encapsulating applications in containers, leading to simpler deployments and scalability. However, managing and monitoring these containers to ensure they run smoothly can be a challenge. Linux Bash, with its powerful command-line utilities, serves as a crucial tool in the monitoring and management of Docker containers. This guide will walk you through different Bash commands and scripts you can use to monitor your running Docker containers effectively.
Understanding Docker Commands
Before diving into Bash scripts, it's essential to understand basic Docker commands that provide insights into container states.
docker ps
: This command lists all currently running containers.docker stats
: Displays a live stream of container(s) resource usage statistics.docker logs [container_id]
: Fetches the logs of a container. Useful for debugging.docker top [container_id]
: Shows running processes in a specific container.
Bash Scripts for Monitoring
Basic Monitoring Script
Let's start by creating a simple script that checks if all necessary Docker containers are up and running:
#!/bin/bash
# Define your containers
containers=("db" "web" "nginx")
# Check each container
for container in "${containers[@]}"; do
if ! docker ps | grep -q $container; then
echo "Container $container is not running!"
else
echo "Container $container is running."
fi
done
This script will iterate over a predefined list of container names and check if they appear in the list of running containers.
Monitoring CPU and Memory Usage
The following Bash script uses docker stats
command to check the CPU and memory usage of each running container. It will alert if the usage exceeds a given threshold:
#!/bin/bash
# Thresholds
max_cpu=80.0
max_mem=500000000 # 500MB
# Fetch stats from all running containers
docker stats --no-stream --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}" | while read name cpu mem; do
# Skip header or unwanted lines
if [[ "$name" == "NAME" || -z "$name" ]]; then
continue
fi
# Remove percentage sign and compare CPU
cpu=${cpu%.*}
if (( $(echo "$cpu > $max_cpu" | bc -l) )); then
echo "High CPU usage on $name: $cpu%"
fi
# Extract current memory usage in bytes
current_mem=$(echo $mem | awk '{print $1*1000000}')
if (( $(echo "$current_mem > $max_mem" | bc -l) )); then
echo "High memory usage on $name: $(echo $mem | awk '{print $1, $2}')"
endif
done
This script uses docker stats --no-stream
to fetch the resource usage data one time instead of continuously streaming. It processes the data using awk
and Bash built-in arithmetic.
Creating a Log Monitoring Script
Monitoring logs can help in understanding what actions took place in a container. Below is a simple script that tails the latest logs:
#!/bin/bash
# Check if the container name is provided
if [ -z "$1" ]; then
echo "Please specify a container name."
exit 1
fi
container_name=$1
# Tail logs
docker logs --tail 50 -f $container_name
This script accepts a container name as an argument and displays the last 50 lines of the container's logs, continuing to follow new logs.
Combining Everything into a Dashboard
For a more interactive monitoring session, you can combine these scripts in a simple text-based dashboard using watch
command:
watch -n 5 './monitoring_script.sh'
This command will rerun your monitoring script every 5 seconds, providing you a quasi-real-time dashboard in your terminal.
Conclusion
Monitoring Docker containers doesn't require complex software; often, straightforward Bash scripts can suffice for many use cases. These scripts provide a foundation upon which more complex monitoring solutions can be built. Whether you're managing a few containers on a local machine or numerous containers across multiple servers, mastering the use of Bash in conjunction with Docker commands can significantly streamline your monitoring process.
Further Reading
For further exploration on the topics covered in the guide, consider reading these additional resources:
Docker Official Documentation: For a deeper understanding of Docker commands and options Docker Docs
Advanced Bash-Scripting Guide: A comprehensive guide for scripting in Bash, including numerous examples and exercises tldp.org/LDP/abs
Prometheus and Grafana for Docker Monitoring: Learn how to use Prometheus and Grafana for more advanced monitoring of Docker containers Prometheus + Grafana
Blog on Monitoring Docker Containers Using ELK Stack: This blog provides a step-by-step process to use Elasticsearch, Logstash, and Kibana to monitor Docker ELK for Docker
Sysdig's Guide to Monitoring Docker Containers: Offers insights into various tools and techniques for effective container monitoring, including Sysdig’s own tools Sysdig Docker Monitoring