Docker Compose (Legacy Python Library)

1.29.2 · abandoned · verified Sat Apr 11

The `docker-compose` PyPI package (version 1.x) is the legacy Python library and CLI for defining and running multi-container Docker applications. This specific package is no longer actively maintained, having been superseded by the Go-based Docker Compose CLI (available as `docker compose`). It offers a programmatic interface for interacting with Compose projects, though its API was never officially stable.

Warnings

Install

Imports

Quickstart

Demonstrates how to programmatically define, start, and stop a Docker Compose project using the legacy Python library. This example dynamically creates a `docker-compose.yml` file and uses `get_project` to manage it. Requires Docker daemon to be running.

import os
import tempfile
from pathlib import Path
from compose.cli.command import get_project # This is often used to load a project

# Create a dummy docker-compose.yml for demonstration
compose_content = """
version: '3.8'
services:
  web:
    image: nginxdemos/hello:latest
    ports:
      - "8080:80"
"""

# Use a temporary directory for the project context
with tempfile.TemporaryDirectory() as tmpdir:
    project_path = Path(tmpdir)
    compose_file = project_path / "docker-compose.yml"
    compose_file.write_text(compose_content)

    print(f"Created temporary docker-compose.yml at: {compose_file}")

    try:
        # Set a project name; otherwise, it might infer from directory name
        os.environ['COMPOSE_PROJECT_NAME'] = project_path.name
        # get_project mimics the CLI's way of loading a project
        project = get_project(project_path, [str(compose_file)])

        print(f"Starting project '{project.name}'...")
        project.up() # Starts services
        print("Project started. Check http://localhost:8080 (if Docker is running and port is free)")

        print("Listing services...")
        for service in project.services:
            print(f"- Service: {service.name}")

        print("Stopping and removing project...")
        project.down(remove_volumes=True) # Stops and removes containers, networks, volumes
        print("Project removed.")

    except Exception as e:
        print(f"An error occurred: {e}")
        print("Ensure Docker is running and the 'docker-compose' Python library is installed.")

view raw JSON →