Refactor DockerComposeManager usage in basic_example and enhance error handling for service, network, config, and secret management
This commit is contained in:
@ -6,38 +6,53 @@ import logging
|
||||
|
||||
from compose import DockerComposeManager
|
||||
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
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"
|
||||
|
||||
# Create a DockerComposeManager instance
|
||||
manager = DockerComposeManager(compose_path)
|
||||
# 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"},
|
||||
)
|
||||
# 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
|
||||
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"],
|
||||
)
|
||||
# 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"}},
|
||||
)
|
||||
|
||||
# Save the compose file
|
||||
manager.save()
|
||||
# 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)
|
||||
|
Reference in New Issue
Block a user