59 lines
2.0 KiB
Python
59 lines
2.0 KiB
Python
"""Example usage of DockerComposeManager to generate a docker-compose.yaml file."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import logging
|
|
|
|
from compose import DockerComposeManager
|
|
|
|
logging.basicConfig(level=logging.INFO)
|
|
logger: logging.Logger = logging.getLogger("docker-compose-example")
|
|
|
|
if __name__ == "__main__":
|
|
# Path to the compose file to generate
|
|
compose_path = "docker-compose.yaml"
|
|
|
|
# Using DockerComposeManager as a context manager
|
|
with DockerComposeManager(compose_path) as manager:
|
|
# Add top-level networks, volumes, configs, and secrets
|
|
manager.add_network("my_network")
|
|
manager.add_volume("db_data")
|
|
manager.add_config("my_config", config={"file": "./config.json"})
|
|
manager.add_secret("my_secret", config={"file": "./secret.txt"})
|
|
|
|
# Add a simple web service
|
|
manager.create_service(
|
|
name="web",
|
|
image="nginx:alpine",
|
|
ports=["8080:80"],
|
|
environment={"NGINX_HOST": "localhost"},
|
|
networks=["my_network"],
|
|
)
|
|
|
|
# Add a database service that depends on the web service
|
|
manager.create_service(
|
|
name="db",
|
|
image="postgres:15-alpine",
|
|
environment={
|
|
"POSTGRES_USER": "user",
|
|
"POSTGRES_PASSWORD": "password",
|
|
"POSTGRES_DB": "example_db",
|
|
},
|
|
ports=["5432:5432"],
|
|
volumes=["db_data:/var/lib/postgresql/data"],
|
|
networks=["my_network"],
|
|
depends_on={"web": {"condition": "service_started"}},
|
|
)
|
|
|
|
# Modify the web service
|
|
manager.modify_service("web", ports=["8081:80"])
|
|
|
|
# Add another service and then remove it
|
|
manager.create_service("temp_service", image="alpine:latest")
|
|
manager.remove_service("temp_service")
|
|
|
|
# Remove a network
|
|
manager.remove_network("my_network")
|
|
|
|
logger.info("docker-compose.yaml generated at %s", compose_path)
|