Build an AI Docker Compose Generator β Describe Your Stack, Get Config
Setting up Docker Compose for a new project takes time. You think about services, networks, volumes, environment variables, and dependencies. What if you could describe your stack and get a complete configuration?
In this tutorial, youβll build a Docker Compose generator that takes natural language descriptions and produces production-ready configurations. No API keys, no cloud calls, everything runs on your machine.
How It Works
- You describe your stack: βNode.js app with PostgreSQL and Redisβ
- AI generates docker-compose.yml with all services, networks, and volumes
- You get a working configuration you can run immediately
Prerequisites
- Ollama installed
- Python 3.10+
Step 1: Pull the model
ollama pull qwen2.5-coder:7b
Step 2: Create the generator
#!/usr/bin/env python3
"""AI Docker Compose generator using Ollama."""
import subprocess
import sys
import json
import urllib.request
OLLAMA_URL = "http://localhost:11434/api/generate"
MODEL = "qwen2.5-coder:7b"
PROMPT_TEMPLATE = """Generate a docker-compose.yml file based on this description.
Description: {description}
Requirements:
1. Use official Docker images where available
2. Include proper environment variables with placeholders
3. Set up volumes for data persistence
4. Configure networking between services
5. Add health checks where appropriate
6. Use proper resource limits
7. Include comments explaining each service
8. Add a .env.example file with required variables
9. Include a Makefile with common commands
10. Follow Docker Compose best practices
Output format:
- docker-compose.yml
- .env.example
- Makefile with helpful commands
Start with the docker-compose.yml:"""
def generate_docker_compose(description):
"""Generate docker-compose configuration from description."""
payload = json.dumps({
"model": MODEL,
"prompt": PROMPT_TEMPLATE.format(description=description),
"stream": False,
"options": {"temperature": 0.3, "num_predict": 3000}
}).encode()
req = urllib.request.Request(
OLLAMA_URL,
data=payload,
headers={"Content-Type": "application/json"}
)
with urllib.request.urlopen(req, timeout=120) as resp:
response = json.loads(resp.read())["response"].strip()
return response
def parse_sections(response):
"""Parse the AI response into sections."""
sections = {
"docker-compose.yml": "",
".env.example": "",
"Makefile": ""
}
current = None
lines = response.split("\n")
for line in lines:
if "docker-compose.yml" in line.lower() or "docker-compose:" in line.lower():
current = "docker-compose.yml"
elif ".env.example" in line.lower() or ".env" in line.lower():
current = ".env.example"
elif "makefile" in line.lower() or "make:" in line.lower():
current = "Makefile"
elif current:
sections[current] += line + "\n"
return sections
def save_files(sections, output_dir="."):
"""Save generated files."""
for filename, content in sections.items():
if content.strip():
filepath = f"{output_dir}/{filename}"
with open(filepath, "w") as f:
f.write(content.strip() + "\n")
print(f"Created: {filepath}")
if __name__ == "__main__":
description = input("Describe your application stack: ")
print("\nGenerating Docker Compose configuration...")
response = generate_docker_compose(description)
sections = parse_sections(response)
print("\n" + "=" * 60)
print("DOCKER-COMPOSE.YML")
print("=" * 60)
print(sections["docker-compose.yml"])
if sections[".env.example"].strip():
print("\n" + "=" * 60)
print(".ENV.EXAMPLE")
print("=" * 60)
print(sections[".env.example"])
if sections["Makefile"].strip():
print("\n" + "=" * 60)
print("MAKEFILE")
print("=" * 60)
print(sections["Makefile"])
save = input("\nSave files? (y/n): ").strip().lower()
if save == "y":
save_files(sections)
Step 3: Run it
python docker_compose_generator.py
Example Session
Describe your application stack: Node.js Express app with PostgreSQL, Redis, and Nginx reverse proxy
Generating Docker Compose configuration...
============================================================
DOCKER-COMPOSE.YML
============================================================
version: '3.8'
services:
# Node.js Application
app:
build: .
container_name: app
ports:
- "3000:3000"
environment:
- NODE_ENV=production
- DATABASE_URL=postgresql://postgres:password@postgres:5432/myapp
- REDIS_URL=redis://redis:6379
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_healthy
volumes:
- ./uploads:/app/uploads
restart: unless-stopped
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:3000/health"]
interval: 30s
timeout: 10s
retries: 3
# PostgreSQL Database
postgres:
image: postgres:16-alpine
container_name: postgres
environment:
- POSTGRES_USER=postgres
- POSTGRES_PASSWORD=password
- POSTGRES_DB=myapp
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
restart: unless-stopped
healthcheck:
test: ["CMD-SHELL", "pg_isready -U postgres"]
interval: 10s
timeout: 5s
retries: 5
# Redis Cache
redis:
image: redis:7-alpine
container_name: redis
ports:
- "6379:6379"
volumes:
- redis_data:/data
restart: unless-stopped
healthcheck:
test: ["CMD", "redis-cli", "ping"]
interval: 10s
timeout: 5s
retries: 5
# Nginx Reverse Proxy
nginx:
image: nginx:alpine
container_name: nginx
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx.conf:/etc/nginx/nginx.conf:ro
- ./ssl:/etc/nginx/ssl:ro
depends_on:
- app
restart: unless-stopped
volumes:
postgres_data:
redis_data:
networks:
default:
driver: bridge
Under the Hood
The AI understands common stack patterns:
- Web apps: Node.js, Python, Ruby with databases
- Microservices: Multiple services with inter-service communication
- Data pipelines: Workers, queues, and storage
- ML/AI stacks: GPUs, Jupyter, model serving
The generated configuration includes:
- Proper service dependencies with health checks
- Volume mounts for data persistence
- Environment variable placeholders
- Networking configuration
- Resource limits
Limitations
- Generated configs need testing before production
- Custom Dockerfiles need manual creation
- Complex networking may need adjustment
- Security defaults should be reviewed
Real-World Use Cases
New project setup. Instead of spending 30 minutes writing Docker configs, describe your stack and get a working setup in seconds. Focus on code, not infrastructure.
Client projects. When starting a new client project, quickly generate a Docker setup to get the team productive on day one.
Microservices architecture. Describe multiple services and their dependencies. The AI generates proper inter-service communication and networking.
Data pipelines. Generate configs for data processing workflows with workers, queues, and storage services.
Development environments. Create consistent development setups that match production configurations.
Tips for Better Configs
- Be specific about versions. βPostgreSQL 16β is better than βPostgreSQL.β
- Mention dependencies. βApp depends on database and cacheβ helps the AI generate proper depends_on.
- Include ports. βApp on port 3000, database on 5432β generates correct port mappings.
- Specify volumes. βPersist database dataβ adds named volumes automatically.
Variations
- Kubernetes: Generate k8s manifests instead
- Terraform: Generate infrastructure as code
- CI/CD: Generate GitHub Actions or GitLab CI configs
- Monitoring: Add Prometheus and Grafana services
My Take
This tool eliminates the boilerplate of Docker Compose setup. Instead of spending 30 minutes writing configs, you get a working setup in seconds. The AI captures the common patterns, and you customize the details.
Rating: 8.5/10 β Saves significant time on new projects. The generated configs are production-ready for most use cases.
Related Articles
- Ollama: How to Install and Run Local AI Models
- Best AI Models for Coding Locally
- LM Studio: How to Run Local LLMs
- How to Run DeepSeek V4 Locally
- Best AI Coding Tools in 2026
FAQ
How accurate is the generated configuration?
Very accurate for standard stacks (Node.js + databases, Python + Redis, etc.). The AI understands common patterns and generates appropriate configurations. For specialized setups, review and adjust.
Can I add custom services?
Yes. The generated config is a starting point. Add your custom services, networks, and volumes as needed.
Does it handle Docker Swarm?
The basic generator produces Docker Compose files. For Docker Swarm, you would need to add swarm-specific configurations.
Can I generate configs for existing projects?
Yes. Describe your existing stack and the AI will generate a compatible docker-compose.yml.
Related: Docker Compose Cheat Sheet Β· Docker Best Practices Β· Ollama Complete Guide