Deploying a Flagsmith App
Introduction
Flagsmith is a powerful open-source feature flag and remote configuration service that enables teams to manage feature releases, perform A/B testing, and control application configuration without deploying new code. Built with a Python/Django backend and React frontend, Flagsmith provides a comprehensive platform for feature management, user segmentation, and progressive rollouts.
Deploying Flagsmith on Klutch.sh gives you a fully managed, scalable platform with automatic Dockerfile detection, persistent storage for your PostgreSQL database, and secure environment variable management. This guide provides detailed instructions for deploying Flagsmith with production-ready PostgreSQL configuration, complete with sample Dockerfiles, environment setup, and best practices for running feature flags at scale.
Prerequisites
Before deploying Flagsmith on Klutch.sh, ensure you have:
- A Klutch.sh account (sign up here)
- A GitHub repository for your Flagsmith deployment configuration
- Basic familiarity with Docker and environment variables
- PostgreSQL database (can be deployed separately on Klutch.sh or use an external provider)
- Understanding of feature flags and remote configuration concepts
What is Flagsmith?
Flagsmith is an open-source feature flag and remote config service that allows you to:
- Manage Feature Flags: Toggle features on/off without deploying code
- Remote Configuration: Update application configuration in real-time
- User Segmentation: Target specific users or groups with different features
- A/B Testing: Run experiments and measure feature performance
- Multivariate Flags: Test multiple variations of features simultaneously
- Audit Trail: Track all changes to flags and configurations
Project Structure
A minimal repository layout for deploying Flagsmith on Klutch.sh:
flagsmith-deployment/├── Dockerfile├── docker-entrypoint.sh (optional)├── .env.example└── README.mdFor production deployments, you’ll also want to maintain separate PostgreSQL configuration and backup strategies.
Sample Dockerfile
Create a Dockerfile in the root of your repository. Klutch.sh will automatically detect and use it for deployment:
FROM flagsmith/flagsmith:latest
# Expose the default Flagsmith portEXPOSE 8000
# The official Flagsmith image includes the entrypoint# and runs migrations automaticallyFor a pinned, production-ready version:
FROM flagsmith/flagsmith:v2.86.0
# Install additional dependencies if needed# RUN apt-get update && apt-get install -y <packages>
# Copy custom configuration (optional)# COPY custom-settings.py /app/
WORKDIR /app
# Expose the Flagsmith API/UI portEXPOSE 8000
# The base image CMD starts the application# CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]Notes:
- Pin to a specific Flagsmith version tag (e.g.,
v2.86.0) for reproducible deployments - The official Flagsmith image runs as a non-root user for security
- Database migrations run automatically on container startup
- Port 8000 is the standard port for Flagsmith’s combined API and UI
PostgreSQL Database Setup
Flagsmith requires PostgreSQL for production use. You have two options:
Option 1: Deploy PostgreSQL on Klutch.sh
- Create a new app in your Klutch.sh project for PostgreSQL
- Use the official PostgreSQL Docker image in your repository
- Create a
Dockerfilefor PostgreSQL: - Attach a persistent volume to
/var/lib/postgresql/datato preserve your database - Set environment variables in Klutch.sh dashboard:
POSTGRES_DB=flagsmithPOSTGRES_USER=flagsmithPOSTGRES_PASSWORD=<secure-password>
- Configure the app to use TCP traffic in the Klutch.sh dashboard
- Set the internal port to
5432(PostgreSQL’s default port) - Note the internal hostname provided by Klutch.sh for database connections
- Connect to the database on port 8000 from other apps in your project (Klutch.sh routes external port 8000 to internal port 5432)
FROM postgres:15-alpine
# Expose PostgreSQL portEXPOSE 5432Option 2: Use External PostgreSQL
If you prefer a managed PostgreSQL service:
- Provision PostgreSQL from a provider like AWS RDS, Google Cloud SQL, or DigitalOcean
- Ensure network connectivity between Klutch.sh and your database
- Use SSL/TLS for secure database connections
- Note the connection credentials for the next step
Environment Variables Configuration
Configure the following environment variables in your Klutch.sh app settings:
Required Environment Variables
# Database Configuration# Note: Use port 8000 for connecting to PostgreSQL deployed on Klutch.sh (external port)# For external managed PostgreSQL, use port 5432 or the provider's specified portDATABASE_URL=postgresql://flagsmith:password@postgres-host:8000/flagsmith
# Django Secret Key (generate a secure random string)DJANGO_SECRET_KEY=your-super-secure-random-secret-key-here
# Application URLDJANGO_ALLOWED_HOSTS=example-app.klutch.sh,your-custom-domain.comOptional Environment Variables
# Enable Django debug mode (disable in production)# DJANGO_DEBUG=False
# Email Configuration (for user invitations and notifications)EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackendEMAIL_HOST=smtp.example.comEMAIL_PORT=587EMAIL_USE_TLS=TrueEMAIL_HOST_USER=your-email@example.comEMAIL_HOST_PASSWORD=your-email-password
# Analytics and TrackingENABLE_ANALYTICS=True
# Influx DB for analytics (optional)# INFLUXDB_URL=http://influxdb:8086# INFLUXDB_TOKEN=your-token# INFLUXDB_ORG=your-org# INFLUXDB_BUCKET=flagsmith
# API Rate Limiting# THROTTLE_ANONYMOUS_RATE=100/hour# THROTTLE_USER_RATE=500/hourSecurity Notes:
- Never commit secrets to your repository
- Use Klutch.sh’s secure environment variable storage
- Generate a strong
DJANGO_SECRET_KEYusing:python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())' - Restrict
DJANGO_ALLOWED_HOSTSto your actual domains
Persistent Storage Configuration
Flagsmith stores static files and media uploads that should persist across deployments. Configure persistent volumes in your Klutch.sh app settings:
Recommended Mount Points
For PostgreSQL (separate app):
- Mount Path:
/var/lib/postgresql/data - Volume Size: Start with 10GB, scale based on usage
For Flagsmith (if storing media/static files):
- Mount Path:
/app/staticfiles - Volume Size: 1-5GB
Volume Configuration Steps:
- In the Klutch.sh dashboard, navigate to your app settings
- Scroll to the “Volumes” section
- Add a new volume with the mount path
/var/lib/postgresql/data(for PostgreSQL) - Set the volume size (e.g., 10GB for starters)
- Save and redeploy your app
Deploying to Klutch.sh
Follow these steps to deploy Flagsmith on Klutch.sh:
Deployment Steps
-
Prepare Your Repository
- Create a new GitHub repository or fork an existing Flagsmith deployment repo
- Add your
Dockerfileto the repository root - Commit and push your changes to GitHub
-
Create the PostgreSQL App
- Log in to Klutch.sh dashboard
- Create a new app for PostgreSQL
- Connect your PostgreSQL repository (with Dockerfile)
- Select TCP traffic in the network configuration
- Add PostgreSQL environment variables (
POSTGRES_DB,POSTGRES_USER,POSTGRES_PASSWORD) - Attach a persistent volume to
/var/lib/postgresql/data(minimum 10GB) - Deploy the PostgreSQL app and note the internal hostname
-
Create the Flagsmith App
- Create a new app in your Klutch.sh project
- Connect your Flagsmith repository containing the Dockerfile
- Klutch.sh will automatically detect the Dockerfile in the root directory
-
Configure Network Settings
- Select HTTP traffic (Flagsmith serves HTTP traffic)
- Set the internal port to
8000(Flagsmith’s default port)
-
Set Environment Variables
- Add all required environment variables as listed above
- Use the PostgreSQL hostname from step 2 in your
DATABASE_URL - Mark sensitive values (passwords, secret keys) as secrets
-
Deploy and Verify
- Click “Create” to build and deploy your Flagsmith app
- Monitor the build logs for any errors
- Once deployed, access your app at the provided Klutch.sh URL
-
Initial Setup
- Navigate to your Flagsmith URL (e.g.,
https://example-app.klutch.sh) - Create your admin account
- Set up your first organization and project
- Navigate to your Flagsmith URL (e.g.,
Getting Started with Flagsmith
After deploying Flagsmith, follow these steps to create your first feature flag:
Create Your First Feature Flag
- Log in to your Flagsmith dashboard
- Create a new project or select your existing project
- Navigate to the “Features” section
- Click “Create Feature” and name it (e.g.,
new_dashboard) - Enable or disable the feature using the toggle
- Configure feature values, segments, or variations as needed
Sample Code: JavaScript SDK
import flagsmith from 'flagsmith';
// Initialize the Flagsmith clientflagsmith.init({ environmentID: 'your_environment_key_here', api: 'https://example-app.klutch.sh/api/v1/', onChange: (oldFlags, params) => { console.log('Flags updated:', flagsmith.getAllFlags()); },});
// Check if a feature is enabledif (flagsmith.hasFeature('new_dashboard')) { console.log('New dashboard is enabled!'); // Show new dashboard} else { console.log('Using old dashboard'); // Show old dashboard}
// Get a feature valueconst apiUrl = flagsmith.getValue('api_url');console.log('API URL:', apiUrl);
// Get feature for a specific userflagsmith.identify('user_123');flagsmith.setTrait('email', 'user@example.com');flagsmith.setTrait('plan', 'premium');Sample Code: Python SDK
from flagsmith import Flagsmith
# Initialize Flagsmithflagsmith = Flagsmith( environment_key="your_environment_key_here", api_url="https://example-app.klutch.sh/api/v1/")
# Get all flags for the environmentflags = flagsmith.get_environment_flags()
# Check if a feature is enabledif flags.is_feature_enabled('new_dashboard'): print("New dashboard is enabled!")else: print("Using old dashboard")
# Get a feature valueapi_url = flags.get_feature_value('api_url')print(f"API URL: {api_url}")
# Get flags for a specific useridentity_flags = flagsmith.get_identity_flags( identifier="user_123", traits={"email": "user@example.com", "plan": "premium"})
if identity_flags.is_feature_enabled('new_dashboard'): print("User has access to new dashboard")Sample Code: React Integration
import { FlagsmithProvider, useFlags } from 'flagsmith/react';
function App() { return ( <FlagsmithProvider options={{ environmentID: 'your_environment_key_here', api: 'https://example-app.klutch.sh/api/v1/', }} > <Dashboard /> </FlagsmithProvider> );}
function Dashboard() { const flags = useFlags(['new_dashboard', 'api_url']);
return ( <div> {flags.new_dashboard.enabled ? ( <NewDashboard apiUrl={flags.api_url.value} /> ) : ( <OldDashboard /> )} </div> );}Custom Domain Configuration
To use a custom domain with your Flagsmith deployment:
- Navigate to your app settings in the Klutch.sh dashboard
- Add your custom domain (e.g.,
flagsmith.yourdomain.com) - Update your DNS records to point to Klutch.sh (as shown in the dashboard)
- Klutch.sh automatically provisions and manages SSL/TLS certificates
- Update your
DJANGO_ALLOWED_HOSTSenvironment variable to include the custom domain - Update your SDK configurations to use the custom domain URL
For detailed instructions, see the Custom Domains guide.
Production Best Practices
Security
- Use strong, randomly generated passwords for database credentials
- Enable SSL/TLS for database connections
- Set
DJANGO_DEBUG=Falsein production - Restrict
DJANGO_ALLOWED_HOSTSto your actual domains only - Regularly rotate your
DJANGO_SECRET_KEYand database passwords - Enable two-factor authentication for admin accounts
- Use environment-specific API keys for different environments (dev, staging, prod)
Performance
- Configure database connection pooling for high-traffic applications
- Use read replicas for PostgreSQL if handling significant read traffic
- Enable caching with Redis or Memcached for improved response times
- Monitor database query performance and add indexes as needed
- Consider using a CDN for serving static assets
Monitoring
- Set up application monitoring and alerting
- Monitor database size and performance metrics
- Track API response times and error rates
- Set up logging aggregation for centralized log management
- Monitor disk usage on persistent volumes
- Set up health check endpoints
Backup Strategy
-
Database Backups
- Schedule regular PostgreSQL backups (daily at minimum)
- Test backup restoration procedures regularly
- Store backups in a separate location from production data
- Keep multiple backup versions (e.g., daily for 7 days, weekly for 4 weeks)
-
Configuration Backups
- Export feature flag configurations regularly
- Version control your Flagsmith project configurations
- Document all environment variable changes
-
Disaster Recovery
- Maintain a documented recovery procedure
- Test the full restoration process periodically
- Keep offline copies of critical credentials
Scaling Considerations
- Start with a single Flagsmith instance and scale horizontally as needed
- Use a load balancer for multiple Flagsmith instances
- Separate read and write database traffic with PostgreSQL replicas
- Consider using a managed PostgreSQL service for automatic scaling and backups
- Monitor CPU and memory usage; adjust instance sizes accordingly
- Cache frequently accessed flags on the client side to reduce API calls
Troubleshooting
Common Issues and Solutions
Issue: Database Connection Errors
- Verify
DATABASE_URLis correctly formatted - Ensure PostgreSQL is running and accessible
- Check that the database user has proper permissions
- For PostgreSQL deployed on Klutch.sh with TCP traffic, connect on port 8000 (external) which routes to port 5432 (internal)
- For external PostgreSQL, use the provider’s specified port (typically 5432)
- Test database connectivity:
psql $DATABASE_URL
Issue: Migrations Failed
- Check application logs for specific migration errors
- Ensure database user has CREATE TABLE permissions
- Try running migrations manually:
python manage.py migrate - Verify database is initialized with the correct schema
Issue: 502/503 Gateway Errors
- Verify the app is listening on
0.0.0.0:8000 - Check application logs for startup errors
- Ensure
DJANGO_ALLOWED_HOSTSincludes your domain - Verify environment variables are set correctly
- Check that the Dockerfile is in the repository root
Issue: Static Files Not Loading
- Ensure
STATIC_ROOTandSTATIC_URLare configured - Run
python manage.py collectstaticduring build - Verify persistent volume is mounted correctly
- Check file permissions on static directories
Issue: Feature Flags Not Updating
- Verify SDK is initialized with correct environment ID
- Check API URL is accessible from your application
- Ensure network connectivity between app and Flagsmith
- Review SDK polling interval settings
- Check for CORS configuration if accessing from browser
Monitoring and Maintenance
Health Checks
Flagsmith provides health check endpoints:
# Basic health checkcurl https://example-app.klutch.sh/health/
# Database health checkcurl https://example-app.klutch.sh/health/db/Log Monitoring
Monitor application logs for:
- Database connection issues
- Authentication failures
- API rate limit hits
- Unexpected errors or exceptions
- Performance degradation warnings
Regular Maintenance Tasks
-
Weekly Tasks
- Review application logs for errors
- Check disk usage on persistent volumes
- Monitor API response times
- Review active feature flags and clean up unused flags
-
Monthly Tasks
- Update Flagsmith to the latest stable version
- Review and optimize database indexes
- Audit user access and permissions
- Test backup restoration procedures
- Review and clean up old audit log entries
-
Quarterly Tasks
- Perform security audit and update dependencies
- Review and optimize infrastructure costs
- Test disaster recovery procedures
- Review and update documentation
Upgrading Flagsmith
To upgrade your Flagsmith deployment:
- Review the Flagsmith release notes for breaking changes
- Update the image tag in your
Dockerfile(e.g.,FROM flagsmith/flagsmith:v2.87.0) - Commit and push the changes to GitHub
- Create a backup of your PostgreSQL database before upgrading
- Deploy the updated version through Klutch.sh
- Monitor application logs during the upgrade
- Verify all features are working as expected after deployment
Advanced Configuration
Using Nixpacks Runtime Configuration
If you need to customize the build or start commands without using a Dockerfile, you can use Nixpacks with environment variables:
Changing the Start Command:
Set the following environment variable in Klutch.sh:
NIXPACKS_START_CMD=python manage.py runserver 0.0.0.0:8000Changing the Build Command:
NIXPACKS_BUILD_CMD=python manage.py collectstatic --noinput && python manage.py migrateInstalling Additional Packages:
NIXPACKS_PKGS=postgresql-client curlNote: For Flagsmith deployments, using a Dockerfile is recommended as it provides more control and reproducibility.
Integration Examples
Integrating with CI/CD
While Klutch.sh deploys directly from GitHub, you can use feature flags to control deployments:
// In your deployment scriptconst flagsmith = require('flagsmith-nodejs');
const fs = flagsmith.default();await fs.init({ environmentID: process.env.FLAGSMITH_ENV_ID, api: 'https://example-app.klutch.sh/api/v1/',});
const flags = await fs.getEnvironmentFlags();
if (flags.isFeatureEnabled('enable_new_deployment')) { console.log('Deploying new version...'); // Proceed with deployment} else { console.log('Deployment paused via feature flag'); process.exit(0);}Multi-Environment Setup
For managing multiple environments (dev, staging, production):
- Create separate environments in your Flagsmith project
- Deploy separate Flagsmith instances or use environment keys
- Use environment-specific SDK keys in your applications
- Promote flags from dev → staging → production
- Use Flagsmith’s webhooks to notify on flag changes
Resources and Further Reading
Official Documentation
- Flagsmith Official Documentation
- Flagsmith GitHub Repository
- Flagsmith Docker Image
- Flagsmith SDK Documentation
Klutch.sh Documentation
- Klutch.sh Quick Start Guide
- Persistent Volumes Guide
- Deployments Overview
- Networking Configuration
- Custom Domains Setup
Community Resources
Conclusion
Deploying Flagsmith on Klutch.sh provides a robust, scalable platform for managing feature flags and remote configuration. With automatic Dockerfile detection, persistent storage, and secure environment management, you can focus on building features rather than managing infrastructure.
This guide covered everything from initial setup to production best practices. For additional support or questions about deploying Flagsmith on Klutch.sh, consult the resources above or reach out to the Klutch.sh support team.
Start managing your feature flags with confidence on Klutch.sh today!