MYHOSPITALNOW.COM

Find Trusted Doctors & Hospitals

Discover healthcare providers, compare hospitals, and explore treatment options worldwide.

Free Treatment Quotes • Doctor Search • Hospital Comparison

Find Healthcare Options

www.myhospitalnow.com

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...]
Code language: CSS (css)

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}}"
Code language: JavaScript (javascript)

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
Code language: JavaScript (javascript)

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}}"
Code language: JavaScript (javascript)

Example Output:

CPU: 2.00%, Memory: 300MiB / 1GiB
Code language: HTTP (http)

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
Code language: JavaScript (javascript)

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
Code language: JavaScript (javascript)

Find Trusted Cardiac Hospitals

Compare heart hospitals by city and services โ€” all in one place.

Explore Hospitals
I'm Rajesh Kumar, a DevOps, SRE, DevSecOps, Cloud, and Platform Engineering expert passionate about sharing practical knowledge, real-world experiences, and industry best practices. I have worked at Cotocus and regularly write about technology, travel, investing, health, product reviews, and digital marketing through my various platforms. I publish technical articles at DevOps School, travel stories at Holiday Landmark, stock market insights at Stocks Mantra, health and fitness guidance at My Medic Plus, product reviews at TrueReviewNow, and SEO and digital marketing strategies at Wizbrand.

Related Posts

Debug for Docker Container

To debug a Docker container, check its state and logs first, then its network configuration, then test connectivity from another container on the same network. This page…

Read More

Install Jenkins with Docker: Persistent Setup, Port Mapping, and Logs

Learn how to run Jenkins in Docker with correct port mapping, persistent storage, and operational commands. This updated guide keeps the original workflow but adds modern, production-minded practices.

Read More

How to Access a Running Docker Container Shell: docker exec vs docker attach

Need a shell inside a running container that is already in detached mode? This updated guide shows the correct workflow, compares docker exec and docker attach, and explains when SSH does and does not make sense.

Read More

Install Atlassian Jira with Docker: Quick Start, Persistent Volumes, and Deployment Checks

This guide shows how to run Jira in Docker using the original one-line command, then improve it with persistent storage and repeatable deployment steps. It also includes a workflow diagram, command examples, and practical validation checks.

Read More

Install Sonatype Nexus with Docker: RM2/RM3 Commands, Validation Steps, and Important Caveats

A structured, production-minded rewrite of the original 2016 Docker setup for Sonatype Nexus Repository Manager 2 and 3. Includes command examples, a workflow diagram, and clear warnings about outdated tags/endpoints.

Read More

Top 5 DevOps Tools To Learn Before Writing Your Dissertation

Writing a technical dissertation is rarely just an exercise in reading sources and formatting chapters. On paper, that sounds like the job. In reality, students in computer…

Read More
Subscribe
Notify of
guest
0 Comments
Newest
Oldest Most Voted
0
Would love your thoughts, please comment.x
()
x