Upgrade & Secure Your Future with DevOps, SRE, DevSecOps, MLOps!

We spend hours on Instagram and YouTube and waste money on coffee and fast food, but won’t spend 30 minutes a day learning skills to boost our careers.
Master in DevOps, SRE, DevSecOps & MLOps!

Learn from Guru Rajesh Kumar and double your salary in just one year.


Get Started Now!

Docker commands Guide – docker stats with examples

Here’s a complete tutorial on docker stats, covering what it does, a comprehensive list of examples, and use cases.


What is docker stats?

docker stats is a Docker command that provides real-time resource usage statistics for running containers, such as CPU, memory, network I/O, and block I/O. It’s useful for monitoring the performance of your containers and diagnosing resource-related issues.

Key Features:

  • Displays live resource usage for one or more containers.
  • Helps in performance monitoring and resource optimization.
  • Works similarly to the top command in Linux but is container-specific.
  • Supports customized output and filtering.

Basic Syntax

docker stats [OPTIONS] [CONTAINER...]

Options:

  • --all, -a: Show stats for all containers, not just running ones.
  • --format: Customize the output using Go templates.
  • --no-stream: Show only a single snapshot of stats, instead of continuous updates.
  • --no-trunc: Do not truncate output (show full container IDs and names).

Examples of docker stats

1. Show Real-Time Stats for All Running Containers

docker stats

Example Output:

CONTAINER ID   NAME        CPU %     MEM USAGE / LIMIT   MEM %     NET I/O   BLOCK I/O   PIDS
a1b2c3d4e5f6   my_app      2.50%     512MiB / 1GiB      50.00%    1.2kB/1kB  0B/0B       5
b2c3d4e5f67g   my_db       0.75%     256MiB / 512MiB    50.00%    5kB/5kB   0B/0B       3

2. Show Stats for a Specific Container

docker stats my_app

This displays live stats only for my_app.


3. Show a Single Snapshot of Stats

docker stats --no-stream

This displays container stats once and exits.


4. Show Stats for Multiple Containers

docker stats my_app my_db

Displays real-time stats for both my_app and my_db.


5. Show Stats for All Containers (Including Stopped)

docker stats --all

This includes stats for stopped containers, showing 0% CPU and memory usage for them.


6. Customize Output with --format

docker stats --format "table {{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"

Example Output:

NAME       CPU %     MEM USAGE
my_app     1.25%     512MiB / 1GiB
my_db      0.50%     256MiB / 512MiB

This formats the output to show only container name, CPU percentage, and memory usage.


7. Show Full Container IDs and Names

docker stats --no-trunc

Prevents truncation of container IDs and names.


8. Monitor Resource Usage in a Script

#!/bin/bash
while true; do
  docker stats --no-stream >> resource_usage.log
  sleep 60
done

This script logs resource usage for all containers every minute.


9. Monitor Specific Resource Usage for a Container

docker stats my_web_container --no-stream --format "CPU: {{.CPUPerc}}, Memory: {{.MemUsage}}"

Example Output:

CPU: 2.00%, Memory: 300MiB / 1GiB

10. Combine with Other Docker Commands

Restart a container if its memory usage exceeds a threshold:

if [[ $(docker stats my_app --no-stream --format "{{.MemPerc}}" | cut -d'%' -f1) > 80 ]]; then
  docker restart my_app
fi

This checks if the container’s memory usage is above 80% and restarts it if true.


Use Cases for docker stats

1. Performance Monitoring

  • Continuously monitor CPU, memory, and I/O usage for critical services.
  • Identify resource bottlenecks in multi-container environments.

2. Debugging Resource-Related Issues

  • Diagnose high memory or CPU usage that could cause containers to slow down or crash.
  • Example: Find containers with abnormal CPU spikes.

3. Capacity Planning

  • Use historical stats to plan resource allocation for your containers.
  • Example: Increase memory allocation for a database container if its usage frequently reaches the limit.

4. Automation and Scripting

  • Automate actions like scaling services, restarting containers, or triggering alerts based on resource thresholds.

5. Security and Incident Response

  • Monitor suspicious behavior in containers (e.g., unexpected CPU or network spikes).
  • Example: Detect a compromised container generating unusual network traffic.

6. CI/CD Pipelines

  • Use docker stats to monitor resource usage during builds and tests to avoid exceeding CI system limits.

List of Common docker stats Commands

CommandDescription
docker statsShow real-time stats for all running containers
docker stats my_containerShow stats for a specific container
docker stats --no-streamShow a single snapshot of stats
docker stats --allShow stats for all containers (including stopped)
docker stats --format "table {{.Name}} {{.CPUPerc}} {{.MemUsage}}"Customize output
docker stats --no-truncShow full container IDs and names

Best Practices for Using docker stats:

  1. Monitor resource usage regularly to prevent performance issues.
  2. Use --format for clarity in automation and scripts.
  3. Combine with alerting tools (like Prometheus or Grafana) for automated resource monitoring.
  4. Set resource limits (--memory, --cpus) for containers to avoid unexpected resource consumption.
  5. Analyze historical trends for capacity planning.

Common Errors and Solutions

  1. “No such container”
    → Ensure the container exists and is running. Use docker ps to verify.
  2. Stats show 0% CPU and memory usage
    → This is expected for paused or stopped containers. Use docker stats --all to confirm their status.
  3. Output is too large
    → Use --format to filter and display only the necessary fields.

Combining docker stats with Other Tools

  1. Monitor with Prometheus and Grafana for advanced visualization and alerting.
  2. Integrate with custom scripts for automated scaling or resource management.

Example: Logging Resource Usage

docker stats --no-stream --format "CPU: {{.CPUPerc}}, Mem: {{.MemUsage}}" >> usage.log

Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments

Certification Courses

DevOpsSchool has introduced a series of professional certification courses designed to enhance your skills and expertise in cutting-edge technologies and methodologies. Whether you are aiming to excel in development, security, or operations, these certifications provide a comprehensive learning experience. Explore the following programs:

DevOps Certification, SRE Certification, and DevSecOps Certification by DevOpsSchool

Explore our DevOps Certification, SRE Certification, and DevSecOps Certification programs at DevOpsSchool. Gain the expertise needed to excel in your career with hands-on training and globally recognized certifications.

0
Would love your thoughts, please comment.x
()
x