Creating a Python script to monitor resource utilization of Docker containers involves using Docker’s APIs and Python libraries to interact with them. This article provides a detailed guide on how to achieve this, along with Python code examples.
1. Introduction
Monitoring resource utilization in Docker containers is essential for maintaining the health and performance of applications. Python, with its powerful libraries and Docker’s API, makes this task straightforward.
2. Prerequisites
- Docker installed on your server.
- Python installed on your system (Python 3.x is recommended).
- Basic knowledge of Python programming and Docker.
3. Python Libraries
docker
: Python library to interact with the Docker Engine API.time
: To handle time-related tasks.
4. Installing the Docker Python Library
First, install the Docker library using pip:
pip install docker
5. Writing the Script
5.1 Importing Libraries
import docker
import time
5.2 Initializing Docker Client
client = docker.from_env()
5.3 Defining the Resource Monitoring Function
def monitor_container_resources(container_name, interval=5):
try:
container = client.containers.get(container_name)
except docker.errors.NotFound:
print(f"Container {container_name} not found.")
return
print(f"Monitoring resources for container: {container_name}")
while True:
stats = container.stats(stream=False)
cpu_usage = stats['cpu_stats']['cpu_usage']['total_usage']
mem_usage = stats['memory_stats']['usage']
net_io = stats['networks']['eth0']['rx_bytes']
print(f"CPU Usage: {cpu_usage}")
print(f"Memory Usage: {mem_usage} bytes")
print(f"Network IO: {net_io} bytes")
time.sleep(interval)
5.4 Main Function
def main():
container_name = input("Enter the container name to monitor: ")
monitor_container_resources(container_name)
if __name__ == "__main__":
main()
The script will display the CPU usage, memory usage, and network I/O for the specified Docker container at regular intervals.