---
title: "Dockerfile"
description: "Dockerfile best practices for TraceRTM"
keywords: [dockerfile, docker, containers, build]
---

# Dockerfile

Dockerfile best practices and examples for TraceRTM.

## Multi-Stage Build

### Optimized Dockerfile

```dockerfile
# Stage 1: Build dependencies
FROM python:3.12-slim as builder

WORKDIR /app

# Install build dependencies
RUN apt-get update && apt-get install -y \
    gcc \
    g++ \
    && rm -rf /var/lib/apt/lists/*

# Copy requirements and install
COPY requirements.txt .
RUN pip install --user --no-cache-dir -r requirements.txt

# Stage 2: Runtime
FROM python:3.12-slim

WORKDIR /app

# Copy Python dependencies from builder
COPY --from=builder /root/.local /root/.local

# Copy application code
COPY . .

# Make sure scripts are executable
RUN chmod +x /app/scripts/*.sh || true

# Set PATH to include local Python packages
ENV PATH=/root/.local/bin:$PATH

# Create non-root user
RUN useradd -m -u 1000 appuser && \
    chown -R appuser:appuser /app
USER appuser

# Expose port
EXPOSE 8000

# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \
  CMD curl -f http://localhost:8000/health || exit 1

# Run application
CMD ["uvicorn", "tracertm.api.main:app", "--host", "0.0.0.0", "--port", "8000"]
```

## Best Practices

### 1. Use Multi-Stage Builds

```dockerfile
# Reduces final image size
FROM builder as builder
# ... build steps

FROM runtime
COPY --from=builder /app/dist /app
```

### 2. Layer Caching

```dockerfile
# Copy requirements first (changes less frequently)
COPY requirements.txt .
RUN pip install -r requirements.txt

# Copy code last (changes frequently)
COPY . .
```

### 3. Minimize Layers

```dockerfile
# Bad - multiple RUN commands
RUN apt-get update
RUN apt-get install -y package1
RUN apt-get install -y package2

# Good - single RUN command
RUN apt-get update && \
    apt-get install -y package1 package2 && \
    rm -rf /var/lib/apt/lists/*
```

### 4. Use .dockerignore

```dockerignore
# .dockerignore
.git
.gitignore
.env
*.pyc
__pycache__
.pytest_cache
.coverage
node_modules
*.md
```

### 5. Non-Root User

```dockerfile
# Create and use non-root user
RUN useradd -m -u 1000 appuser
USER appuser
```

## Production Dockerfile

```dockerfile
FROM python:3.12-slim

WORKDIR /app

# Install runtime dependencies only
RUN apt-get update && apt-get install -y \
    curl \
    && rm -rf /var/lib/apt/lists/*

# Copy requirements and install
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application
COPY . .

# Set environment
ENV PYTHONUNBUFFERED=1
ENV PYTHONDONTWRITEBYTECODE=1

# Health check
HEALTHCHECK CMD curl -f http://localhost:8000/health || exit 1

# Run
CMD ["uvicorn", "tracertm.api.main:app", "--host", "0.0.0.0", "--port", "8000"]
```

## Related Documentation

- [Docker Deployment](./01-docker-deployment) - Docker deployment
- [Image Optimization](./01b-image-optimization) - Optimize images
