Running trading applications in Docker brings consistency, isolation, and easy deployment. Here's a practical guide.
Why Docker for Trading?
- Consistent environment — same setup on dev laptop and server
- Isolation — each bot gets its own container
- Easy deployment — push to server with one command
- Resource control — limit CPU/memory per bot
- Quick recovery — restart failed containers automatically
Basic Trading Bot Dockerfile
FROM python:3.12-slim
WORKDIR /app
# Install dependencies first (cache layer)
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY . .
# Non-root user for security
RUN useradd -m trader
USER trader
# Health check
HEALTHCHECK --interval=30s --timeout=10s \
CMD python healthcheck.py || exit 1
CMD ["python", "bot.py"]
Docker Compose for Multi-Bot Setup
version: '3.8'
services:
data-feed:
build: ./data-feed
restart: unless-stopped
environment:
- API_KEY=${MARKET_DATA_KEY}
volumes:
- market-data:/data
deploy:
resources:
limits:
memory: 512M
strategy-1:
build: ./strategies/momentum
restart: unless-stopped
depends_on:
- data-feed
environment:
- STRATEGY_CONFIG=/config/momentum.json
volumes:
- market-data:/data:ro
- ./configs:/config:ro
- strategy1-logs:/logs
strategy-2:
build: ./strategies/mean-reversion
restart: unless-stopped
depends_on:
- data-feed
volumes:
- market-data:/data:ro
- strategy2-logs:/logs
monitor:
build: ./monitor
ports:
- "8080:8080"
volumes:
- strategy1-logs:/logs/s1:ro
- strategy2-logs:/logs/s2:ro
volumes:
market-data:
strategy1-logs:
strategy2-logs:
Configuration Management
# config.py - environment-based configuration
import os
class Config:
API_KEY = os.environ.get('API_KEY')
DB_PATH = os.environ.get('DB_PATH', '/data/trades.db')
LOG_LEVEL = os.environ.get('LOG_LEVEL', 'INFO')
MAX_RISK = float(os.environ.get('MAX_RISK', '0.01'))
PAPER_MODE = os.environ.get('PAPER_MODE', 'true').lower() == 'true'
Never hardcode API keys or credentials. Always use environment variables or Docker secrets.
Health Monitoring
# healthcheck.py
import sys
import json
from datetime import datetime, timedelta
def check_health():
try:
# Check last heartbeat
with open('/tmp/heartbeat.json') as f:
data = json.load(f)
last_beat = datetime.fromisoformat(data['timestamp'])
if datetime.now() - last_beat > timedelta(minutes=5):
print("Heartbeat stale")
sys.exit(1)
# Check data feed connection
if not data.get('feed_connected'):
print("Data feed disconnected")
sys.exit(1)
sys.exit(0)
except Exception as e:
print(f"Health check failed: {e}")
sys.exit(1)
check_health()
Logging Best Practices
import logging
import json
from datetime import datetime
class JsonFormatter(logging.Formatter):
def format(self, record):
log_entry = {
'timestamp': datetime.utcnow().isoformat(),
'level': record.levelname,
'message': record.getMessage(),
'module': record.module,
}
if hasattr(record, 'trade_data'):
log_entry['trade'] = record.trade_data
return json.dumps(log_entry)
# Setup
handler = logging.FileHandler('/logs/bot.log')
handler.setFormatter(JsonFormatter())
logger = logging.getLogger('trading')
logger.addHandler(handler)
Backup Strategy
# Add to docker-compose.yml
backup:
image: alpine
volumes:
- market-data:/data:ro
- ./backups:/backups
command: >
sh -c "while true; do
tar czf /backups/data-$$(date +%Y%m%d).tar.gz /data;
find /backups -mtime +7 -delete;
sleep 86400;
done"
Deployment Workflow
# Build and deploy
docker compose build
docker compose up -d
# Check status
docker compose ps
docker compose logs -f strategy-1
# Update one service without downtime
docker compose up -d --build strategy-1
# Scale strategies
docker compose up -d --scale strategy-1=2
Security Checklist
- Never run containers as root
- Use read-only volumes where possible
- Keep base images updated
- Scan images for vulnerabilities
- Use Docker secrets for sensitive data
- Restrict network access between containers
Docker is the standard for deploying trading infrastructure. Whether you run a personal setup or scale across multiple strategies and accounts, containerization keeps everything manageable. For more on trading infrastructure and firm comparisons, visit propfirmkey.com.
Do you run your trading systems in Docker? What's your deployment setup?
Top comments (0)