Skip to content

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.md

For 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 port
EXPOSE 8000
# The official Flagsmith image includes the entrypoint
# and runs migrations automatically

For 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 port
EXPOSE 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

    1. Create a new app in your Klutch.sh project for PostgreSQL
    2. Use the official PostgreSQL Docker image in your repository
    3. Create a Dockerfile for PostgreSQL:
    FROM postgres:15-alpine
    # Expose PostgreSQL port
    EXPOSE 5432
    1. Attach a persistent volume to /var/lib/postgresql/data to preserve your database
    2. Set environment variables in Klutch.sh dashboard:
      • POSTGRES_DB=flagsmith
      • POSTGRES_USER=flagsmith
      • POSTGRES_PASSWORD=<secure-password>
    3. Configure the app to use TCP traffic in the Klutch.sh dashboard
    4. Set the internal port to 5432 (PostgreSQL’s default port)
    5. Note the internal hostname provided by Klutch.sh for database connections
    6. Connect to the database on port 8000 from other apps in your project (Klutch.sh routes external port 8000 to internal port 5432)

Option 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

Terminal window
# 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 port
DATABASE_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 URL
DJANGO_ALLOWED_HOSTS=example-app.klutch.sh,your-custom-domain.com

Optional Environment Variables

Terminal window
# Enable Django debug mode (disable in production)
# DJANGO_DEBUG=False
# Email Configuration (for user invitations and notifications)
EMAIL_BACKEND=django.core.mail.backends.smtp.EmailBackend
EMAIL_HOST=smtp.example.com
EMAIL_PORT=587
EMAIL_USE_TLS=True
EMAIL_HOST_USER=your-email@example.com
EMAIL_HOST_PASSWORD=your-email-password
# Analytics and Tracking
ENABLE_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/hour

Security Notes:

  • Never commit secrets to your repository
  • Use Klutch.sh’s secure environment variable storage
  • Generate a strong DJANGO_SECRET_KEY using: python -c 'from django.core.management.utils import get_random_secret_key; print(get_random_secret_key())'
  • Restrict DJANGO_ALLOWED_HOSTS to 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:

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:

    1. In the Klutch.sh dashboard, navigate to your app settings
    2. Scroll to the “Volumes” section
    3. Add a new volume with the mount path /var/lib/postgresql/data (for PostgreSQL)
    4. Set the volume size (e.g., 10GB for starters)
    5. Save and redeploy your app

Deploying to Klutch.sh

Follow these steps to deploy Flagsmith on Klutch.sh:

Deployment Steps

    1. Prepare Your Repository

      • Create a new GitHub repository or fork an existing Flagsmith deployment repo
      • Add your Dockerfile to the repository root
      • Commit and push your changes to GitHub
    2. 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
    3. 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
    4. Configure Network Settings

      • Select HTTP traffic (Flagsmith serves HTTP traffic)
      • Set the internal port to 8000 (Flagsmith’s default port)
    5. 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
    6. 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
    7. 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

Getting Started with Flagsmith

After deploying Flagsmith, follow these steps to create your first feature flag:

Create Your First Feature Flag

    1. Log in to your Flagsmith dashboard
    2. Create a new project or select your existing project
    3. Navigate to the “Features” section
    4. Click “Create Feature” and name it (e.g., new_dashboard)
    5. Enable or disable the feature using the toggle
    6. Configure feature values, segments, or variations as needed

Sample Code: JavaScript SDK

import flagsmith from 'flagsmith';
// Initialize the Flagsmith client
flagsmith.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 enabled
if (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 value
const apiUrl = flagsmith.getValue('api_url');
console.log('API URL:', apiUrl);
// Get feature for a specific user
flagsmith.identify('user_123');
flagsmith.setTrait('email', 'user@example.com');
flagsmith.setTrait('plan', 'premium');

Sample Code: Python SDK

from flagsmith import Flagsmith
# Initialize Flagsmith
flagsmith = Flagsmith(
environment_key="your_environment_key_here",
api_url="https://example-app.klutch.sh/api/v1/"
)
# Get all flags for the environment
flags = flagsmith.get_environment_flags()
# Check if a feature is enabled
if flags.is_feature_enabled('new_dashboard'):
print("New dashboard is enabled!")
else:
print("Using old dashboard")
# Get a feature value
api_url = flags.get_feature_value('api_url')
print(f"API URL: {api_url}")
# Get flags for a specific user
identity_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:

    1. Navigate to your app settings in the Klutch.sh dashboard
    2. Add your custom domain (e.g., flagsmith.yourdomain.com)
    3. Update your DNS records to point to Klutch.sh (as shown in the dashboard)
    4. Klutch.sh automatically provisions and manages SSL/TLS certificates
    5. Update your DJANGO_ALLOWED_HOSTS environment variable to include the custom domain
    6. 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=False in production
  • Restrict DJANGO_ALLOWED_HOSTS to your actual domains only
  • Regularly rotate your DJANGO_SECRET_KEY and 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

    1. 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)
    2. Configuration Backups

      • Export feature flag configurations regularly
      • Version control your Flagsmith project configurations
      • Document all environment variable changes
    3. 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_URL is 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_HOSTS includes your domain
  • Verify environment variables are set correctly
  • Check that the Dockerfile is in the repository root

Issue: Static Files Not Loading

  • Ensure STATIC_ROOT and STATIC_URL are configured
  • Run python manage.py collectstatic during 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:

Terminal window
# Basic health check
curl https://example-app.klutch.sh/health/
# Database health check
curl 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

    1. 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
    2. 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
    3. 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:

    1. Review the Flagsmith release notes for breaking changes
    2. Update the image tag in your Dockerfile (e.g., FROM flagsmith/flagsmith:v2.87.0)
    3. Commit and push the changes to GitHub
    4. Create a backup of your PostgreSQL database before upgrading
    5. Deploy the updated version through Klutch.sh
    6. Monitor application logs during the upgrade
    7. 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:

Terminal window
NIXPACKS_START_CMD=python manage.py runserver 0.0.0.0:8000

Changing the Build Command:

Terminal window
NIXPACKS_BUILD_CMD=python manage.py collectstatic --noinput && python manage.py migrate

Installing Additional Packages:

Terminal window
NIXPACKS_PKGS=postgresql-client curl

Note: 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 script
const 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):

    1. Create separate environments in your Flagsmith project
    2. Deploy separate Flagsmith instances or use environment keys
    3. Use environment-specific SDK keys in your applications
    4. Promote flags from dev → staging → production
    5. Use Flagsmith’s webhooks to notify on flag changes

Resources and Further Reading

Official Documentation

Klutch.sh Documentation

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!