Deploying Traefik
Introduction
Traefik is a modern, cloud-native reverse proxy and load balancer designed for microservices architectures. It automatically discovers services and configures itself dynamically, eliminating the need for manual configuration files and service restarts when your infrastructure changes.
Built with Go for high performance and low resource usage, Traefik integrates seamlessly with container orchestration platforms, service discovery systems, and cloud providers. It handles SSL certificate management automatically through Let’s Encrypt and provides sophisticated routing capabilities with middleware for authentication, rate limiting, and more.
Key highlights of Traefik:
- Auto-Discovery: Automatically detects and configures routes for services from Docker, Kubernetes, and other providers
- Dynamic Configuration: Updates routing rules without restarts as services come and go
- Let’s Encrypt Integration: Automatically obtains and renews SSL/TLS certificates
- Middleware System: Built-in support for authentication, rate limiting, headers, redirects, and more
- Dashboard: Real-time visibility into routers, services, and middleware through a web UI
- HTTP/2 and gRPC: Native support for modern protocols
- Metrics and Tracing: Prometheus, Datadog, and distributed tracing integration
- WebSocket Support: Full support for WebSocket connections
- Load Balancing: Multiple algorithms including round-robin, weighted, and sticky sessions
- Open Source: Licensed under MIT with enterprise features available
This guide walks through deploying Traefik on Klutch.sh using Docker, configuring it as a reverse proxy, and setting up routing for your applications.
Why Deploy Traefik on Klutch.sh
Deploying Traefik on Klutch.sh provides several advantages for managing your application traffic:
Simplified Deployment: Klutch.sh automatically detects your Dockerfile and builds Traefik without complex orchestration. Push to GitHub, and your reverse proxy deploys automatically.
Persistent Storage: Attach persistent volumes for SSL certificates and configuration. Your Let’s Encrypt certificates survive redeployments without needing to request new ones.
HTTPS by Default: While Traefik can manage its own certificates, Klutch.sh also provides automatic SSL for the Traefik dashboard itself.
GitHub Integration: Connect your configuration repository directly from GitHub. Updates trigger automatic redeployments.
Environment Variable Management: Securely store sensitive configuration like API keys and dashboard credentials through Klutch.sh’s environment variable system.
Scalable Resources: Allocate CPU and memory based on your traffic needs. Start small and scale as your services grow.
Prerequisites
Before deploying Traefik on Klutch.sh, ensure you have:
- A Klutch.sh account
- A GitHub account with a repository for your Traefik configuration
- Basic familiarity with Docker and reverse proxy concepts
- (Optional) A custom domain for your Traefik dashboard
Understanding Traefik Architecture
Traefik uses a modular architecture built around several key concepts:
Entrypoints: Network entry points where Traefik listens for incoming traffic (e.g., ports 80, 443).
Routers: Rules that determine which requests go to which services based on host, path, headers, and more.
Services: Definitions of where traffic should be sent, including load balancing configuration.
Middleware: Transformations applied to requests before they reach services (authentication, rate limiting, etc.).
Providers: Sources of dynamic configuration like Docker, Kubernetes, or file-based configuration.
Preparing Your Repository
To deploy Traefik on Klutch.sh, create a GitHub repository containing your Dockerfile and configuration.
Repository Structure
traefik-deploy/├── Dockerfile├── traefik.yml├── dynamic/│ └── config.yml└── .dockerignoreCreating the Dockerfile
Create a Dockerfile in the root of your repository:
FROM traefik:v3.0
# Copy static configurationCOPY traefik.yml /etc/traefik/traefik.yml
# Copy dynamic configurationCOPY dynamic/ /etc/traefik/dynamic/
# Create directory for Let's Encrypt certificatesRUN mkdir -p /letsencrypt
# Expose portsEXPOSE 80 443 8080
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=10s --retries=3 \ CMD traefik healthcheck || exit 1Creating the Static Configuration
Create traefik.yml for the static configuration:
# API and Dashboardapi: dashboard: true insecure: false
# EntrypointsentryPoints: web: address: ":80" http: redirections: entryPoint: to: websecure scheme: https websecure: address: ":443" traefik: address: ":8080"
# Providersproviders: file: directory: /etc/traefik/dynamic watch: true
# Certificate ResolverscertificatesResolvers: letsencrypt: acme: email: ${ACME_EMAIL} storage: /letsencrypt/acme.json httpChallenge: entryPoint: web
# Logginglog: level: INFO format: json
# Access logsaccessLog: format: jsonCreating Dynamic Configuration
Create dynamic/config.yml for dynamic routing rules:
# HTTP Routershttp: routers: dashboard: rule: "Host(`traefik.example.com`)" service: api@internal entryPoints: - websecure tls: certResolver: letsencrypt middlewares: - auth
# Middleware middlewares: auth: basicAuth: users: - "${DASHBOARD_USER}:${DASHBOARD_PASSWORD_HASH}"
security-headers: headers: stsSeconds: 31536000 stsIncludeSubdomains: true stsPreload: true contentTypeNosniff: true browserXssFilter: true referrerPolicy: "strict-origin-when-cross-origin"Environment Variables Reference
| Variable | Required | Default | Description |
|---|---|---|---|
ACME_EMAIL | Yes | - | Email address for Let’s Encrypt certificate notifications |
DASHBOARD_USER | No | - | Username for dashboard access |
DASHBOARD_PASSWORD_HASH | No | - | Bcrypt hash of dashboard password. Generate with htpasswd -nb user password |
LOG_LEVEL | No | INFO | Logging verbosity (DEBUG, INFO, WARN, ERROR) |
Deploying Traefik on Klutch.sh
Once your repository is prepared, follow these steps to deploy Traefik:
- Select HTTP as the traffic type
- Set the internal port to 8080 (Traefik dashboard port)
- Detect your Dockerfile automatically
- Build the container image
- Attach the persistent volumes
- Start the Traefik container
- Provision an HTTPS certificate
Generate Dashboard Credentials
Before deployment, create credentials for the Traefik dashboard:
htpasswd -nb admin your-secure-passwordThis outputs a string like admin:$apr1$... that you’ll use for DASHBOARD_PASSWORD_HASH.
Push Your Repository to GitHub
Initialize your repository and push to GitHub:
git initgit add Dockerfile traefik.yml dynamic/ .dockerignoregit commit -m "Initial Traefik deployment configuration"git remote add origin https://github.com/yourusername/traefik-deploy.gitgit push -u origin mainCreate a New Project on Klutch.sh
Navigate to the Klutch.sh dashboard and create a new project. Give it a descriptive name like “traefik” or “reverse-proxy”.
Create a New App
Within your project, create a new app. Connect your GitHub account if you haven’t already, then select the repository containing your Traefik Dockerfile.
Configure HTTP Traffic
Traefik exposes multiple ports. In the deployment settings:
Note: For full reverse proxy functionality with custom domains, you may need additional port configuration.
Set Environment Variables
In the environment variables section, add the following:
| Variable | Value |
|---|---|
ACME_EMAIL | your-email@example.com |
DASHBOARD_USER | admin |
DASHBOARD_PASSWORD_HASH | The hash generated in step 1 |
Attach Persistent Volumes
Persistent storage is essential for Traefik. Add the following volumes:
| Mount Path | Recommended Size | Purpose |
|---|---|---|
/letsencrypt | 100 MB | Let’s Encrypt certificates and ACME state |
/etc/traefik/dynamic | 100 MB | Dynamic configuration files (if using file provider) |
Deploy Your Application
Click Deploy to start the build process. Klutch.sh will:
Access Traefik Dashboard
Once deployment completes, access your Traefik dashboard at https://your-app-name.klutch.sh. Log in with the credentials you created.
Understanding the Dashboard
Overview Panel
The Traefik dashboard provides visibility into:
- Routers: All configured routing rules and their status
- Services: Backend services and their health
- Middlewares: Active middleware chains
- Entrypoints: Listening ports and their configuration
Monitoring Traffic
Use the dashboard to:
- View active connections and request rates
- Check certificate status and expiration
- Debug routing issues
- Monitor service health
Configuring Routes
Adding Application Routes
To route traffic to your applications, add entries to your dynamic configuration:
http: routers: my-app: rule: "Host(`app.example.com`)" service: my-app-service entryPoints: - websecure tls: certResolver: letsencrypt
services: my-app-service: loadBalancer: servers: - url: "http://internal-app:8080"Path-Based Routing
Route based on URL paths:
http: routers: api: rule: "Host(`example.com`) && PathPrefix(`/api`)" service: api-service entryPoints: - websecureLoad Balancing
Configure multiple backends for high availability:
http: services: balanced-service: loadBalancer: servers: - url: "http://app1:8080" - url: "http://app2:8080" - url: "http://app3:8080" healthCheck: path: /health interval: 10sMiddleware Configuration
Rate Limiting
Protect your services from abuse:
http: middlewares: rate-limit: rateLimit: average: 100 burst: 50Authentication
Add basic authentication to routes:
http: middlewares: auth: basicAuth: users: - "user:$apr1$..."CORS Headers
Configure cross-origin resource sharing:
http: middlewares: cors: headers: accessControlAllowMethods: - GET - POST - OPTIONS accessControlAllowOriginList: - "https://example.com"Production Best Practices
Security Recommendations
- Dashboard Protection: Always protect the dashboard with authentication
- HTTPS Everywhere: Redirect all HTTP traffic to HTTPS
- Security Headers: Use middleware to add security headers to responses
- Rate Limiting: Implement rate limiting on public endpoints
Certificate Management
- Persistent Storage: Always use persistent volumes for
/letsencrypt - Email Notifications: Configure a valid email for certificate expiration warnings
- Certificate Monitoring: Monitor certificate status through the dashboard
High Availability
For production deployments:
- Configure health checks for all backend services
- Use multiple backend instances with load balancing
- Set appropriate timeouts and retry policies
Troubleshooting Common Issues
Certificate Issues
Symptoms: HTTPS not working or certificate errors.
Solutions:
- Verify ACME_EMAIL is set correctly
- Check that port 80 is accessible for HTTP challenge
- Review Traefik logs for Let’s Encrypt errors
- Ensure the
/letsencryptvolume is persistent
Routes Not Working
Symptoms: Requests returning 404 or not routing correctly.
Solutions:
- Check router rules in the dashboard
- Verify service URLs are correct and reachable
- Review entrypoint configuration
- Check for conflicting router priorities
Dashboard Not Accessible
Symptoms: Cannot access the Traefik dashboard.
Solutions:
- Verify port 8080 is exposed and mapped correctly
- Check authentication credentials
- Review API configuration in traefik.yml
Additional Resources
- Traefik Official Website
- Traefik Documentation
- Traefik GitHub Repository
- Traefik Community Forum
- Klutch.sh Persistent Volumes
- Klutch.sh Deployments
Conclusion
Deploying Traefik on Klutch.sh gives you a powerful, flexible reverse proxy with automatic SSL certificate management and dynamic routing. The combination of Traefik’s cloud-native design and Klutch.sh’s deployment simplicity means you can focus on building your applications rather than managing infrastructure.
With its comprehensive middleware system, load balancing capabilities, and excellent observability through the dashboard, Traefik provides everything you need to route and secure traffic to your microservices. Whether you’re running a single application or a complex multi-service architecture, Traefik scales with your needs.