Deploying Tyk
Introduction
Tyk is a powerful open-source API gateway that helps organizations secure, manage, and monitor their APIs. Built with Go for high performance, Tyk provides enterprise-grade features including authentication, rate limiting, versioning, and detailed analytics while maintaining low latency and high throughput.
Unlike simpler reverse proxies, Tyk offers a complete API management solution with a dashboard for configuration, developer portal for API consumers, and extensive plugin system for customization. It supports REST, GraphQL, gRPC, and TCP APIs out of the box.
Key highlights of Tyk:
- High Performance: Written in Go with minimal overhead per request
- Authentication: JWT, OAuth2, API keys, OpenID Connect, and more
- Rate Limiting: Protect APIs with configurable rate limits and quotas
- Versioning: Manage multiple API versions simultaneously
- Analytics: Detailed request logs and usage statistics
- GraphQL Support: Native GraphQL federation and stitching
- Plugins: Extend functionality with custom middleware
- Developer Portal: Self-service API discovery and key management
- Kubernetes Native: Native Kubernetes Ingress controller
- Multi-Protocol: REST, GraphQL, gRPC, TCP, and WebSocket support
- Open Source: Licensed under MPL 2.0
This guide walks through deploying Tyk on Klutch.sh using Docker, configuring your APIs, and setting up authentication and rate limiting.
Why Deploy Tyk on Klutch.sh
Deploying Tyk on Klutch.sh provides several advantages for API management:
Simplified Deployment: Klutch.sh automatically detects your Dockerfile and builds Tyk without complex orchestration. Push to GitHub, and your API gateway deploys automatically.
Persistent Storage: Attach persistent volumes for your API definitions and analytics data. Your configurations survive container restarts and redeployments.
HTTPS by Default: Klutch.sh provides automatic SSL certificates for secure API traffic.
Scalable Resources: Allocate CPU and memory based on your traffic needs. Start small and scale as your API usage grows.
Always-On Gateway: Your API gateway remains accessible 24/7, ensuring consistent API availability.
Prerequisites
Before deploying Tyk on Klutch.sh, ensure you have:
- A Klutch.sh account
- A GitHub account with a repository for your Tyk configuration
- Basic familiarity with Docker and API gateway concepts
- Backend APIs you want to expose through Tyk
- (Optional) Redis for distributed deployments
- (Optional) A custom domain for your Tyk gateway
Understanding Tyk Architecture
Tyk consists of several components:
Tyk Gateway: The core API gateway that handles all incoming requests, applies policies, and routes to backends.
Tyk Dashboard (optional): Web interface for managing APIs, users, and viewing analytics.
Tyk Pump (optional): Moves analytics data from Redis to storage backends like MongoDB or PostgreSQL.
Redis: Required for distributed deployments, caching, and rate limiting state.
For simpler deployments, you can run Tyk Gateway standalone with file-based configuration.
Preparing Your Repository
To deploy Tyk on Klutch.sh, create a GitHub repository containing your Dockerfile and configuration.
Repository Structure
tyk-deploy/├── Dockerfile├── tyk.conf├── apps/│ └── sample-api.json└── .dockerignoreCreating the Dockerfile
Create a Dockerfile in the root of your repository:
FROM tykio/tyk-gateway:latest
# Copy configurationCOPY tyk.conf /opt/tyk-gateway/tyk.conf
# Copy API definitionsCOPY apps/ /opt/tyk-gateway/apps/
# Set environment variablesENV TYK_GW_SECRET=${TYK_SECRET}ENV TYK_GW_LISTENPORT=8080
# Create directoriesRUN mkdir -p /opt/tyk-gateway/middleware
# Expose the gateway portEXPOSE 8080
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=30s --retries=3 \ CMD curl -f http://localhost:8080/hello || exit 1Configuration File
Create tyk.conf for your Tyk Gateway configuration:
{ "listen_port": 8080, "secret": "${TYK_SECRET}", "template_path": "/opt/tyk-gateway/templates", "tyk_js_path": "/opt/tyk-gateway/js/tyk.js", "middleware_path": "/opt/tyk-gateway/middleware", "use_db_app_configs": false, "app_path": "/opt/tyk-gateway/apps", "storage": { "type": "redis", "host": "${REDIS_HOST}", "port": 6379, "username": "", "password": "${REDIS_PASSWORD}", "database": 0, "optimisation_max_idle": 2000, "optimisation_max_active": 4000 }, "enable_analytics": true, "analytics_config": { "type": "", "ignored_ips": [], "enable_detailed_recording": true, "enable_geo_ip": false, "normalise_urls": { "enabled": true, "normalise_uuids": true, "normalise_numbers": true, "custom_patterns": [] } }, "health_check": { "enable_health_checks": true, "health_check_value_timeouts": 60 }, "optimisations_use_async_session_write": true, "enable_non_transactional_rate_limiter": true, "enable_sentinel_rate_limiter": false, "allow_insecure_configs": true, "policies": { "policy_source": "file", "policy_record_name": "/opt/tyk-gateway/policies/policies.json" }, "hash_keys": true, "close_connections": false, "http_server_options": { "enable_websockets": true }, "allow_master_keys": false, "enable_bundle_downloader": true, "bundle_base_url": "", "global_session_lifetime": 100, "max_idle_connections_per_host": 500}Sample API Definition
Create apps/sample-api.json for a sample API configuration:
{ "name": "Sample API", "slug": "sample-api", "api_id": "sample-api-1", "org_id": "default", "use_keyless": true, "version_data": { "not_versioned": true, "versions": { "Default": { "name": "Default", "use_extended_paths": true } } }, "proxy": { "listen_path": "/sample/", "target_url": "https://httpbin.org", "strip_listen_path": true }, "active": true}Environment Variables Reference
| Variable | Required | Default | Description |
|---|---|---|---|
TYK_SECRET | Yes | - | Secret key for gateway administration |
REDIS_HOST | Yes | - | Redis server hostname |
REDIS_PASSWORD | No | - | Redis password if required |
TYK_GW_LISTENPORT | No | 8080 | Port for the gateway to listen on |
Deploying Tyk on Klutch.sh
Once your repository is prepared, follow these steps to deploy Tyk:
- Create a new app for Redis
- Use the official Redis Docker image
- Configure with password if needed
- Note the internal hostname
- Select HTTP as the traffic type
- Set the internal port to 8080 (Tyk default port)
- Detect your Dockerfile automatically
- Build the container image
- Attach the persistent volumes
- Start the Tyk container
- Provision an HTTPS certificate
Deploy Redis
Tyk requires Redis for rate limiting and caching. Deploy Redis on Klutch.sh:
Generate Your TYK_SECRET
Generate a secure secret key:
openssl rand -hex 32Save this key securely for the environment variables configuration.
Push Your Repository to GitHub
Initialize your repository and push to GitHub:
git initgit add Dockerfile tyk.conf apps/ .dockerignoregit commit -m "Initial Tyk deployment configuration"git remote add origin https://github.com/yourusername/tyk-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 “tyk” or “api-gateway”.
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 Tyk Dockerfile.
Configure HTTP Traffic
In the deployment settings:
Set Environment Variables
In the environment variables section, add the following:
| Variable | Value |
|---|---|
TYK_SECRET | Your generated secret from step 2 |
REDIS_HOST | Your Redis service hostname |
REDIS_PASSWORD | Your Redis password (if set) |
Attach Persistent Volumes
Persistent storage is essential for Tyk. Add the following volumes:
| Mount Path | Recommended Size | Purpose |
|---|---|---|
/opt/tyk-gateway/apps | 1 GB | API definitions |
/opt/tyk-gateway/middleware | 1 GB | Custom middleware and plugins |
Deploy Your Application
Click Deploy to start the build process. Klutch.sh will:
Access Tyk
Once deployment completes, access your Tyk gateway at https://your-app-name.klutch.sh. Test with the health endpoint at /hello.
Configuring APIs
API Definition Structure
Each API is defined in a JSON file in the apps/ directory:
{ "name": "My API", "slug": "my-api", "api_id": "unique-api-id", "org_id": "default", "use_keyless": false, "auth": { "auth_header_name": "Authorization" }, "version_data": { "not_versioned": false, "versions": { "v1": { "name": "v1" }, "v2": { "name": "v2" } }, "default_version": "v1" }, "proxy": { "listen_path": "/api/", "target_url": "http://backend-service:8080", "strip_listen_path": true }, "active": true}Key Configuration Options
Important API configuration fields:
- listen_path: URL path where API is accessible
- target_url: Backend service URL
- use_keyless: Whether authentication is required
- strip_listen_path: Remove listen_path when proxying
- version_data: API versioning configuration
Authentication
API Key Authentication
Configure API key authentication:
{ "use_keyless": false, "auth": { "auth_header_name": "x-api-key" }}JWT Authentication
Enable JWT validation:
{ "use_keyless": false, "enable_jwt": true, "jwt_signing_method": "rsa", "jwt_source": "header", "jwt_identity_base_field": "sub", "jwt_policy_field_name": "policy_id"}OAuth2
Configure OAuth2 authentication:
{ "use_oauth2": true, "oauth_meta": { "allowed_access_types": ["authorization_code", "refresh_token"], "allowed_authorize_types": ["code"], "auth_login_redirect": "https://auth.example.com/login" }}Rate Limiting
Global Rate Limits
Set rate limits in the API definition:
{ "global_rate_limit": { "rate": 1000, "per": 60 }, "disable_rate_limit": false}Per-Key Rate Limits
Configure rate limits in policies:
{ "rate": 100, "per": 60, "quota_max": 10000, "quota_renewal_rate": 86400}Request Transformation
Header Injection
Add headers to requests:
{ "version_data": { "versions": { "Default": { "extended_paths": { "transform_headers": [ { "path": "/", "method": "GET", "add_headers": { "X-Custom-Header": "value" }, "delete_headers": ["X-Remove-Me"] } ] } } } }}URL Rewriting
Rewrite request URLs:
{ "version_data": { "versions": { "Default": { "extended_paths": { "url_rewrites": [ { "path": "/old-path", "method": "GET", "match_pattern": "/old-path(.*)", "rewrite_to": "/new-path$1" } ] } } } }}Production Best Practices
Security Recommendations
- Strong Secrets: Use properly generated TYK_SECRET
- HTTPS Only: Klutch.sh provides this automatically
- Key Hashing: Enable hash_keys in configuration
- Rate Limiting: Always configure rate limits for protection
High Availability
- Redis Clustering: Use Redis Cluster for HA
- Multiple Gateway Instances: Deploy multiple gateway pods
- Health Checks: Configure proper health check endpoints
Performance Optimization
- Connection Pooling: Configure max connections appropriately
- Async Session Writes: Enable for better performance
- Analytics Sampling: Sample analytics for high-traffic APIs
Troubleshooting Common Issues
Gateway Not Starting
Symptoms: Container exits or health checks fail.
Solutions:
- Verify Redis connectivity
- Check TYK_SECRET is properly set
- Review configuration file syntax
- Check container logs for errors
API Not Accessible
Symptoms: 404 or 500 errors when calling APIs.
Solutions:
- Verify API definition is valid JSON
- Check listen_path configuration
- Verify backend service is reachable
- Review gateway logs
Rate Limiting Not Working
Symptoms: Rate limits not being enforced.
Solutions:
- Verify Redis connection
- Check rate limit configuration
- Ensure rate limiter is enabled in config
Additional Resources
- Tyk Official Website
- Tyk Documentation
- Tyk GitHub Repository
- Tyk Community Forum
- Klutch.sh Persistent Volumes
- Klutch.sh Deployments
Conclusion
Deploying Tyk on Klutch.sh gives you a powerful, enterprise-grade API gateway accessible from anywhere. The combination of Tyk’s comprehensive feature set and Klutch.sh’s deployment simplicity means you can focus on your APIs rather than infrastructure.
With built-in authentication, rate limiting, analytics, and support for multiple protocols, Tyk provides everything you need to secure and manage your API infrastructure. Your API configurations remain under your control, and your traffic flows through a high-performance gateway running on reliable infrastructure.