Deploying Countly
Introduction
Countly is a powerful, enterprise-grade open-source analytics platform designed for mobile and web applications. It provides comprehensive insights into user behavior, crash analytics, push notifications, and real-time data visualization. Deploying Countly on Klutch.sh gives you a scalable, production-ready analytics infrastructure with automated Docker deployments, persistent storage for your analytics data, and secure environment variable management.
This comprehensive guide walks you through deploying Countly on Klutch.sh using a Dockerfile, configuring MongoDB for data persistence, setting up persistent volumes, managing environment variables, and implementing production-ready best practices for enterprise analytics workloads.
Why Deploy Countly on Klutch.sh?
- Automated Docker Detection: Klutch.sh automatically detects your Dockerfile in the root directory - no manual configuration needed
- Persistent Storage: Built-in support for persistent volumes to ensure your analytics data survives deployments
- Secure Secrets Management: Environment variables are securely stored and never exposed in logs
- Scalable Infrastructure: Easily scale your Countly instance as your analytics needs grow
- Production-Ready: Deploy with confidence using industry-standard Docker containers
- HTTP/TCP Traffic Support: Flexible networking options for your application needs
Prerequisites
Before you begin deploying Countly on Klutch.sh, ensure you have:
- A Klutch.sh account
- A GitHub account with a repository for your Countly project
- Docker installed locally for testing (optional but recommended)
- Basic understanding of Docker, MongoDB, and analytics platforms
- A MongoDB instance (you can deploy MongoDB on Klutch.sh or use a managed service)
Installation and Setup
Step 1: Create Your Project Directory
First, create a new directory for your Countly deployment project and initialize a Git repository:
mkdir countly-klutchcd countly-klutchgit initThis directory will contain your Dockerfile and any configuration files needed for your Countly deployment.
Step 2: Create the Dockerfile
Create a Dockerfile in your project root directory. Klutch.sh will automatically detect this file and use it to build your container. Here’s a production-ready Dockerfile for Countly:
FROM countly/countly-server:latest
# Set working directoryWORKDIR /opt/countly
# Environment variables will be provided by Klutch.sh# These include MongoDB connection strings and API keys
# Create directories for persistent storageRUN mkdir -p /opt/countly/log \ /opt/countly/plugins \ /opt/countly/frontend/express/public/appimages \ /opt/countly/frontend/express/public/userimages
# Expose the default Countly portEXPOSE 6001
# Health check to ensure Countly is running properlyHEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \ CMD curl -f http://localhost:6001/ping || exit 1
# The base image already has a CMD defined# It starts Countly automaticallyKey Features of This Dockerfile:
- Uses the official Countly server image as the base
- Creates necessary directories for logs and uploaded assets
- Exposes port 6001 (Countly’s default HTTP port)
- Includes a health check for monitoring
- Leverages the base image’s startup command
Step 3: Create a Configuration File (Optional)
For advanced configurations, you can create a custom configuration file. Create a file named config.js (optional):
// config.js - Custom Countly configuration// This file can override default settingsmodule.exports = { mongodb: { host: process.env.COUNTLY_MONGODB_HOST || 'localhost', port: parseInt(process.env.COUNTLY_MONGODB_PORT || '27017'), db: process.env.COUNTLY_MONGODB_DB || 'countly', username: process.env.COUNTLY_MONGODB_USERNAME || '', password: process.env.COUNTLY_MONGODB_PASSWORD || '', max_pool_size: 500 }, api: { port: 6001, host: '0.0.0.0', max_sockets: 1024 }, frontend: { production: true }};If you create a custom config file, modify your Dockerfile to copy it:
# Add this line after the WORKDIR instructionCOPY config.js /opt/countly/api/config.jsStep 4: Create a MongoDB Connection Script (Optional)
For production deployments with external MongoDB, you might want to create a startup script that verifies the database connection. Create entrypoint.sh:
#!/bin/bashset -e
# Wait for MongoDB to be readyecho "Waiting for MongoDB to be ready..."until nc -z ${COUNTLY_MONGODB_HOST} ${COUNTLY_MONGODB_PORT}; do echo "MongoDB is unavailable - sleeping" sleep 2done
echo "MongoDB is ready - starting Countly"
# Start Countlyexec /opt/countly/bin/countly.sh startIf you create this script, update your Dockerfile:
# Add before EXPOSECOPY entrypoint.sh /opt/countly/entrypoint.shRUN chmod +x /opt/countly/entrypoint.sh
# Replace CMD with:CMD ["/opt/countly/entrypoint.sh"]Step 5: Test Locally with Docker (Optional)
Before deploying to Klutch.sh, you can test your Countly setup locally using Docker:
# Build the Docker imagedocker build -t my-countly .
# Run with a local MongoDB containerdocker network create countly-network
# Start MongoDBdocker run -d \ --name countly-mongo \ --network countly-network \ -e MONGO_INITDB_DATABASE=countly \ mongo:latest
# Run Countlydocker run -d \ --name countly-app \ --network countly-network \ -p 6001:6001 \ -e COUNTLY_MONGODB_HOST=countly-mongo \ -e COUNTLY_MONGODB_PORT=27017 \ -e COUNTLY_MONGODB_DB=countly \ my-countly
# Check logsdocker logs -f countly-app
# Access Countly at http://localhost:6001When you’re done testing:
# Stop and remove containersdocker stop countly-app countly-mongodocker rm countly-app countly-mongodocker network rm countly-networkStep 6: Push to GitHub
Commit your Dockerfile and any configuration files to your GitHub repository:
git add Dockerfile config.js entrypoint.shgit commit -m "Add Countly Dockerfile and configuration"git remote add origin https://github.com/yourusername/countly-klutch.gitgit branch -M maingit push -u origin mainEnvironment Variables Configuration
Countly requires several environment variables to function properly. These should be configured in the Klutch.sh dashboard under your app’s environment variables section.
Required Environment Variables
Configure these essential variables for your Countly deployment:
MongoDB Configuration:
COUNTLY_MONGODB_HOST=your-mongodb-host.klutch.shCOUNTLY_MONGODB_PORT=27017COUNTLY_MONGODB_DB=countlyCOUNTLY_MONGODB_USERNAME=countly_userCOUNTLY_MONGODB_PASSWORD=your_secure_passwordCountly Configuration:
COUNTLY_CONFIG_API_API_HOST=0.0.0.0COUNTLY_CONFIG_API_API_PORT=6001COUNTLY_CONFIG_FRONTEND_PRODUCTION=trueOptional Environment Variables
For enhanced functionality, consider adding these optional variables:
Email Configuration (for user notifications):
COUNTLY_CONFIG_EMAIL_EMAIL_HOST=smtp.gmail.comCOUNTLY_CONFIG_EMAIL_EMAIL_PORT=587COUNTLY_CONFIG_EMAIL_EMAIL_USER=your-email@gmail.comCOUNTLY_CONFIG_EMAIL_EMAIL_PASSWORD=your-app-passwordCOUNTLY_CONFIG_EMAIL_EMAIL_FROM=noreply@yourdomain.comSecurity and Performance:
COUNTLY_CONFIG_API_MAX_SOCKETS=1024COUNTLY_CONFIG_API_SESSION_SECRET=your-random-session-secret-hereCOUNTLY_CONFIG_MONGODB_MAX_POOL_SIZE=500Important Security Notes:
- Always use strong, unique passwords for production deployments
- Never commit sensitive credentials to your Git repository
- Use Klutch.sh’s environment variable management to securely store secrets
- Rotate credentials regularly and use different credentials for different environments
Persistent Storage Configuration
Countly generates and stores important data that must persist across container restarts and deployments. You need to configure persistent volumes for:
Critical Directories for Persistence
- Log Files (
/opt/countly/log) - Application logs for debugging and monitoring - Uploaded Files (
/opt/countly/frontend/express/public/appimages) - Application icons and images - User Assets (
/opt/countly/frontend/express/public/userimages) - User-uploaded profile images - Plugin Data (
/opt/countly/plugins) - Custom plugin configurations and data
Recommended Volume Configuration
When creating your app on Klutch.sh, attach persistent volumes with the following mount paths:
Primary Data Volume:
- Mount Path:
/opt/countly/log - Size: 5GB (adjust based on your analytics volume)
- Purpose: Store application logs
Assets Volume:
- Mount Path:
/opt/countly/frontend/express/public - Size: 10GB (adjust based on expected uploads)
- Purpose: Store uploaded images and user assets
Volume Size Recommendations
- Small deployment (< 100K events/day): 5GB for logs, 5GB for assets
- Medium deployment (100K - 1M events/day): 10GB for logs, 10GB for assets
- Large deployment (> 1M events/day): 20GB+ for logs, 20GB+ for assets
Note: MongoDB data should be stored in a separate database deployment with its own persistent storage. See the MongoDB deployment guide for details.
Deploying to Klutch.sh
Now that your Countly project is ready and pushed to GitHub, follow these steps to deploy it on Klutch.sh with persistent storage and proper configuration.
Deployment Steps
-
Log in to Klutch.sh
Navigate to klutch.sh/app and sign in to your account.
-
Create a New Project
Go to your dashboard and create a new project. Give it a meaningful name like “Countly Analytics Platform” to help organize your deployments.
-
Create a New App
Within your project, create a new app for Countly with the following configuration:
-
Select Your Repository
- Choose GitHub as your Git source
- Select the repository containing your Countly Dockerfile
- Choose the branch you want to deploy (typically
mainormaster)
-
Configure Traffic Type
- Traffic Type: Select HTTP (Countly serves a web interface on HTTP)
- Internal Port: Set to
6001(Countly’s default port)
Note: Klutch.sh automatically detects the Dockerfile in your repository root, so you don’t need to specify Docker as a deployment option.
-
Set Environment Variables
In the environment variables section, add all the MongoDB connection variables and Countly configuration variables listed in the “Environment Variables Configuration” section above. Ensure sensitive values like passwords are marked as secrets.
Critical Variables (minimum required):
COUNTLY_MONGODB_HOST- Your MongoDB host addressCOUNTLY_MONGODB_PORT- MongoDB port (typically 27017)COUNTLY_MONGODB_DB- Database name (typically “countly”)COUNTLY_MONGODB_USERNAME- MongoDB usernameCOUNTLY_MONGODB_PASSWORD- MongoDB password (mark as secret)
-
Attach Persistent Volumes
This is critical for data persistence. Add volumes for:
Log Volume:
- Mount Path:
/opt/countly/log - Size: 10GB (adjust based on your needs)
Assets Volume:
- Mount Path:
/opt/countly/frontend/express/public - Size: 10GB (adjust based on expected uploads)
- Mount Path:
-
Configure Compute Resources
Select appropriate compute resources based on your expected analytics load:
- Minimum: 1 CPU, 2GB RAM (for small-scale testing)
- Recommended: 2 CPU, 4GB RAM (for production with moderate traffic)
- High-Scale: 4+ CPU, 8GB+ RAM (for large-scale analytics)
-
Deploy Your Application
Click “Create” to start the deployment. Klutch.sh will:
- Automatically detect your Dockerfile in the repository root
- Build the Docker image with your configuration
- Attach the persistent volumes you specified
- Deploy the container with your environment variables
- Assign a URL for accessing your Countly instance
-
Access Your Countly Instance
Once deployment is complete, you’ll receive a URL like
example-app.klutch.sh. Navigate to this URL in your browser to access your Countly dashboard. On first access, you’ll be prompted to create an admin account.
MongoDB Database Setup
Countly requires MongoDB to store analytics data. You have two options for MongoDB:
Option 1: Deploy MongoDB on Klutch.sh (Recommended)
Deploy MongoDB as a separate app on Klutch.sh for better isolation and management:
- Create a new app in your Klutch.sh project
- Deploy MongoDB using a Dockerfile (see the MongoDB deployment guide)
- Configure TCP traffic type with internal port 27017
- Attach a persistent volume to
/data/db(minimum 20GB recommended) - Use the MongoDB app’s URL as
COUNTLY_MONGODB_HOSTin your Countly configuration
Example MongoDB Dockerfile for Klutch.sh:
FROM mongo:7.0
# Create data directoryRUN mkdir -p /data/db
# Expose MongoDB portEXPOSE 27017
# MongoDB will listen on all interfacesCMD ["mongod", "--bind_ip_all"]MongoDB Environment Variables:
MONGO_INITDB_ROOT_USERNAME=adminMONGO_INITDB_ROOT_PASSWORD=your-secure-passwordMONGO_INITDB_DATABASE=countlyOption 2: Use a Managed MongoDB Service
Alternatively, use a managed MongoDB service like:
When using a managed service, simply use their connection string in your Countly environment variables.
Getting Started with Countly
After deployment, follow these steps to start using Countly for analytics:
Initial Setup
-
Access Your Instance: Navigate to your Klutch.sh app URL (e.g.,
https://example-app.klutch.sh) -
Create Admin Account: On first access, you’ll see a setup wizard. Create your admin account with a strong password.
-
Create Your First Application: In the Countly dashboard, create an application to track. You’ll receive an App Key and API Key.
Integrate Countly SDK
Web Application Example (JavaScript):
// Initialize CountlyCountly.init({ app_key: "YOUR_APP_KEY", url: "https://example-app.klutch.sh", debug: false});
// Track page views automaticallyCountly.track_pageview();
// Track custom eventsCountly.add_event({ key: "button_click", count: 1, segmentation: { button_name: "signup", page: "homepage" }});Mobile Application Example (React Native):
import Countly from 'countly-sdk-react-native';
// InitializeCountly.init("https://example-app.klutch.sh", "YOUR_APP_KEY");
// Enable crash reportingCountly.enableCrashReporting();
// Track eventsCountly.recordEvent({ key: "purchase", count: 1, sum: 29.99, segmentation: { product: "premium_plan", currency: "USD" }});iOS Example (Swift):
import Countly
// Configure Countlylet config: CountlyConfig = CountlyConfig()config.appKey = "YOUR_APP_KEY"config.host = "https://example-app.klutch.sh"config.enableDebug = falseconfig.enableCrashReporting = true
// Start CountlyCountly.sharedInstance().start(with: config)
// Track eventsCountly.sharedInstance().recordEvent("user_action", segmentation: ["action": "signup", "source": "homepage"])Android Example (Kotlin):
import ly.count.android.sdk.Countly
// Initialize CountlyCountly.sharedInstance() .init(this, "https://example-app.klutch.sh", "YOUR_APP_KEY") .enableCrashReporting() .setLoggingEnabled(false)
// Track eventsval segmentation = HashMap<String, String>()segmentation["platform"] = "android"segmentation["version"] = "1.0"
Countly.sharedInstance().events() .recordEvent("app_opened", segmentation, 1)Common Analytics Use Cases
- User Behavior Tracking: Monitor how users navigate through your application
- Conversion Funnels: Track user journey from signup to conversion
- Crash Analytics: Automatically collect and analyze app crashes
- Push Notifications: Send targeted notifications to user segments
- Retention Analysis: Measure user retention over time
- Custom Dashboards: Create custom dashboards for specific metrics
Production Best Practices
Security Recommendations
Authentication and Access Control:
- Enable authentication for the Countly dashboard
- Use strong passwords and enable two-factor authentication (2FA)
- Limit admin access to trusted personnel only
- Regularly review user permissions and access logs
Database Security:
- Use strong MongoDB credentials
- Enable MongoDB authentication and authorization
- Restrict MongoDB network access to only the Countly app
- Regularly update MongoDB to patch security vulnerabilities
Network Security:
- Use HTTPS for all connections (Klutch.sh provides this automatically)
- Implement rate limiting to prevent abuse
- Consider using a Web Application Firewall (WAF)
- Monitor for unusual traffic patterns
Performance Optimization
Database Optimization:
- Ensure proper MongoDB indexes are created for frequently queried data
- Monitor MongoDB performance metrics (connection pool, query time)
- Configure appropriate MongoDB connection pool size (500+ for high traffic)
- Consider MongoDB sharding for very large datasets (millions of events/day)
Application Optimization:
- Allocate sufficient RAM for Countly (minimum 4GB for production)
- Monitor CPU usage and scale vertically if needed
- Use Countly’s data aggregation features to reduce storage requirements
- Implement data retention policies to automatically clean old data
Caching and CDN:
- Configure browser caching for static assets
- Use a CDN for the Countly SDK files
- Enable Countly’s internal caching mechanisms
Monitoring and Maintenance
Health Monitoring:
- Monitor container health checks and logs
- Set up alerts for high CPU/memory usage
- Track MongoDB connection status
- Monitor disk usage for persistent volumes
Regular Maintenance Tasks:
- Review and clean up old analytics data based on retention policy
- Perform regular MongoDB backups
- Update the Countly Docker image for security patches
- Review and optimize MongoDB queries and indexes
- Monitor and rotate logs to prevent disk space issues
Backup Strategy:
Implement a comprehensive backup strategy:
- MongoDB Backups: Schedule daily automated backups using
mongodump - Volume Snapshots: Create periodic snapshots of persistent volumes
- Configuration Backup: Keep copies of environment variables and configs
- Disaster Recovery Plan: Document recovery procedures and test regularly
# Example MongoDB backup script (run as a scheduled job)mongodump --host=mongodb-host \ --port=27017 \ --username=countly_user \ --password=your_password \ --db=countly \ --out=/backup/countly-$(date +%Y%m%d)Scaling Considerations
Vertical Scaling (Single Instance):
- Increase CPU and RAM allocation as analytics load grows
- Suitable for up to 1-2 million events per day
- Simpler to manage and maintain
Horizontal Scaling (Multiple Instances):
- For high-scale deployments (> 2 million events/day)
- Requires load balancer configuration
- May need session affinity for dashboard users
- MongoDB should be scaled independently
Database Scaling:
- MongoDB replica sets for high availability
- MongoDB sharding for very large datasets
- Consider MongoDB Atlas for automatic scaling
Troubleshooting
Common Issues and Solutions
Issue: Countly Dashboard Not Loading
- Check: Verify the container is running: Review logs in Klutch.sh dashboard
- Check: Confirm port 6001 is correctly configured as the internal port
- Check: Ensure HTTP traffic type is selected (not TCP)
- Solution: Restart the deployment if configuration was changed
Issue: Cannot Connect to MongoDB
- Check: Verify
COUNTLY_MONGODB_HOSTis correct - Check: Confirm MongoDB is running and accessible on port 27017
- Check: Validate MongoDB credentials are correct
- Solution: Test MongoDB connection using a MongoDB client:
Terminal window mongosh "mongodb://username:password@host:port/countly"
Issue: Analytics Data Not Appearing
- Check: Verify App Key and API Key are correctly configured in your SDK
- Check: Ensure Countly SDK is properly initialized in your application
- Check: Check browser console for JavaScript errors (web apps)
- Check: Review Countly logs for incoming event processing errors
- Solution: Enable debug mode in SDK to see detailed logging
Issue: High Memory Usage
- Cause: Insufficient memory allocation or memory leak
- Solution: Increase RAM allocation to at least 4GB
- Solution: Monitor MongoDB memory usage separately
- Solution: Implement data retention policies to limit database growth
- Solution: Restart the application periodically if memory leaks persist
Issue: Persistent Data Lost After Redeployment
- Cause: Persistent volumes not properly attached
- Check: Verify volume mount paths match:
/opt/countly/logand/opt/countly/frontend/express/public - Check: Confirm volumes have sufficient space allocated
- Solution: Re-attach volumes with correct paths before deploying
Issue: Slow Dashboard Loading
- Cause: Large dataset or insufficient database indexes
- Solution: Optimize MongoDB queries and ensure proper indexing
- Solution: Implement data aggregation and archival strategies
- Solution: Increase compute resources (CPU/RAM)
- Solution: Consider MongoDB performance tuning
Getting Help
If you encounter issues not covered here:
- Review Countly’s official documentation
- Check the Countly GitHub issues
- Consult Klutch.sh documentation
- Contact Klutch.sh support through the dashboard
Advanced Configuration
Custom Plugins
Countly supports custom plugins for extended functionality. To add custom plugins:
- Create a
pluginsdirectory in your project - Add your custom plugin code
- Update your Dockerfile to copy plugins:
COPY plugins /opt/countly/plugins- Configure plugin settings via environment variables
Email Notifications
Configure email settings for user notifications and alerts:
COUNTLY_CONFIG_EMAIL_EMAIL_HOST=smtp.gmail.comCOUNTLY_CONFIG_EMAIL_EMAIL_PORT=587COUNTLY_CONFIG_EMAIL_EMAIL_USE_TLS=trueCOUNTLY_CONFIG_EMAIL_EMAIL_USER=notifications@yourdomain.comCOUNTLY_CONFIG_EMAIL_EMAIL_PASSWORD=your-app-passwordCustom Domain Configuration
To use a custom domain with your Countly instance:
- Configure your custom domain in Klutch.sh (see custom domains guide)
- Update DNS records to point to your Klutch.sh app
- Klutch.sh will automatically handle SSL/TLS certificates
- Update your SDK configurations with the new domain
Data Retention Policies
Implement automated data retention to manage database growth:
Configure retention in Countly’s database settings or create a scheduled job to archive old data:
// Example data retention scriptconst retentionDays = 365; // Keep 1 year of dataconst cutoffDate = new Date();cutoffDate.setDate(cutoffDate.getDate() - retentionDays);
db.events.deleteMany({ timestamp: { $lt: cutoffDate }});Additional Resources
- Countly Official Website
- Countly Server GitHub Repository
- Countly Documentation
- Countly Docker Images
- Klutch.sh Volumes Guide
- Klutch.sh Deployments Guide
- MongoDB Deployment Guide
- Klutch.sh Quick Start Guide
Conclusion
Deploying Countly on Klutch.sh provides a robust, scalable analytics platform for tracking user behavior across web and mobile applications. With automated Docker detection, persistent storage support, and secure environment variable management, Klutch.sh simplifies the deployment process while maintaining production-grade reliability.
By following this comprehensive guide, you’ve learned how to:
- Create a production-ready Dockerfile for Countly
- Configure MongoDB for persistent analytics data storage
- Set up persistent volumes for logs and uploaded assets
- Manage environment variables securely
- Integrate Countly SDKs into your applications
- Implement best practices for security, performance, and monitoring
- Troubleshoot common deployment issues
Your Countly analytics platform is now ready to provide valuable insights into your users’ behavior, helping you make data-driven decisions to improve your applications. As your analytics needs grow, you can easily scale your Klutch.sh deployment to handle increasing traffic and data volume.