Generate a docker-compose.yml with mock services in Python
Build a docker-compose.yml string from a Python dict of service names and images, then write it to a file.
pip install pyyaml
Python code
27 linesimport yaml
from pathlib import Path
def generate_mock_compose(services: dict) -> str:
compose = {
"version": "3.9",
"services": {}
}
for name, image in services.items():
compose["services"][name] = {
"image": image,
"container_name": f"mock-{name}",
"restart": "unless-stopped"
}
return yaml.dump(compose, default_flow_style=False, sort_keys=False)
if __name__ == "__main__":
services = {
"web": "nginx:latest",
"db": "postgres:16",
"cache": "redis:7"
}
output = generate_mock_compose(services)
print(output)
Path("docker-compose.yml").write_text(output)
Output
version: '3.9'
services:
web:
image: nginx:latest
container_name: mock-web
restart: unless-stopped
db:
image: postgres:16
container_name: mock-db
restart: unless-stopped
cache:
image: redis:7
container_name: mock-cache
restart: unless-stopped
How it works
The function takes a simple dict mapping service names to Docker images and builds a nested dict that mirrors the docker-compose.yml structure. yaml.dump converts that dict into YAML text with default_flow_style=False to keep it block-style and human-readable. Setting sort_keys=False preserves the insertion order so services appear in the same order as in the input. The Path.write_text call saves the YAML to disk, and the file is ready to use with docker compose up.
Common mistakes
- Forgetting to quote the version number in the output — YAML 1.1 parses 3.9 as a float; use single quotes as shown.
- Overwriting an existing docker-compose.yml without a backup or check — consider adding a `Path.exists()` guard.
- Hardcoding the compose version when modern Docker supports `version` as optional and deprecated.
- Assuming `yaml` is installed — it's not in the standard library; you must `pip install pyyaml`.
Variations
- Use `yaml.safe_dump` instead of `yaml.dump` for safer output when handling untrusted containers.
- Add environment variables or ports to the service dict for a richer mock setup.
Real-world use cases
- Generating throwaway local environments for integration tests where real services can be replaced with mocks.
- Scripting the creation of a compose file from a configuration file or CI variables for reproducible deployments.
- Producing a template compose file that developers can edit before spinning up a group of related services.
Sponsored
More from Production deployment patterns
- Auto Rollback on Error Rate Exceeded in Python medium
- Automate Semantic Versioning with Conventional Commits in Python medium
- Design a Data Helper for Beginners in Python easy
- Docker healthcheck CMD mock in Python easy
- Generate a Mock Artifact Version Tag in Python easy
- How to Attach an SBOM to a Release in Python (Mock) easy
Keep learning
Related tutorials and quizzes for this topic.