How to Filter Docker Containers for Pruning in Python

Simulate Docker's container prune by filtering a JSON list for exited containers older than a cutoff, returning pruned IDs and space freed.

Easy Python 3.9+ Aug 9, 2026 Automation & scripting 13 views 0 copies

Python code

49 lines
Python 3.9+
import json
from datetime import datetime, timedelta


def parse_docker_ps(json_output: str, older_than_hours: int = 24) -> list:
    containers = json.loads(json_output)
    cutoff = datetime.now() - timedelta(hours=older_than_hours)
    return [
        c for c in containers
        if datetime.fromisoformat(c["created_at"]) < cutoff
        and c["status"] == "exited"
    ]


def docker_prune_mock(container_json: str, older_than_hours: int = 24) -> dict:
    to_prune = parse_docker_ps(container_json, older_than_hours)
    return {
        "pruned": [c["id"][:12] for c in to_prune],
        "total_space_freed_mb": round(sum(c["size_mb"] for c in to_prune), 2),
        "containers_remaining": len(json.loads(container_json)) - len(to_prune),
    }


if __name__ == "__main__":
    mock_docker_ps = json.dumps([
        {
            "id": "a1b2c3d4e5f60718aabbccddeeff0011",
            "name": "old_app",
            "status": "exited",
            "created_at": (datetime.now() - timedelta(days=2)).isoformat(),
            "size_mb": 120.5,
        },
        {
            "id": "f6e5d4c3b2a10918ffeeddccbbaa0022",
            "name": "recent_worker",
            "status": "exited",
            "created_at": (datetime.now() - timedelta(hours=2)).isoformat(),
            "size_mb": 45.8,
        },
        {
            "id": "11223344556677889900aabbccddeeff",
            "name": "running_db",
            "status": "running",
            "created_at": (datetime.now() - timedelta(hours=30)).isoformat(),
            "size_mb": 890.1,
        },
    ])
    result = docker_prune_mock(mock_docker_ps, older_than_hours=24)
    print(result)

Output

stdout
{'pruned': ['a1b2c3d4e5f6'], 'total_space_freed_mb': 120.5, 'containers_remaining': 2}

How it works

The parse_docker_ps function uses datetime.now() minus a timedelta based on older_than_hours to compute the cutoff timestamp. It filters the parsed JSON list with a conditional that checks both the created_at string (converted via fromisoformat) and the status field. This mirrors Docker CLI's prune behavior of removing only stopped containers older than a threshold. The docker_prune_mock function then returns a summary dict with truncated IDs, summed sizes, and remaining count, mimicking a dry-run output for cleanup planning.

Common mistakes

  • Comparing `created_at` as a string instead of parsing it with `datetime.fromisoformat`
  • Including running containers in the prune list by forgetting to check the `status` field
  • Not rounding the total space when summing float size values
  • Assuming the JSON structure always has all fields, causing KeyError

Variations

  1. Use a generator expression with `sum` and `islice` to avoid building intermediate lists for large outputs
  2. Add a `dry_run` parameter that returns the same result without actually executing a prune command

Real-world use cases

  • Automating scheduled cleanup of Docker containers in CI/CD pipelines, saving disk space on build agents.
  • Building a monitoring script that alerts when accumulated stopped container space exceeds a threshold before cleanup.
  • Testing prune logic with mock JSON payloads in unit tests before wiring to a real Docker API.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Automation & scripting

Related tutorials and quizzes for this topic.