Skip to content

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:

Terminal window
mkdir countly-klutch
cd countly-klutch
git init

This 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 directory
WORKDIR /opt/countly
# Environment variables will be provided by Klutch.sh
# These include MongoDB connection strings and API keys
# Create directories for persistent storage
RUN mkdir -p /opt/countly/log \
/opt/countly/plugins \
/opt/countly/frontend/express/public/appimages \
/opt/countly/frontend/express/public/userimages
# Expose the default Countly port
EXPOSE 6001
# Health check to ensure Countly is running properly
HEALTHCHECK --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 automatically

Key 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 settings
module.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 instruction
COPY config.js /opt/countly/api/config.js

Step 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/bash
set -e
# Wait for MongoDB to be ready
echo "Waiting for MongoDB to be ready..."
until nc -z ${COUNTLY_MONGODB_HOST} ${COUNTLY_MONGODB_PORT}; do
echo "MongoDB is unavailable - sleeping"
sleep 2
done
echo "MongoDB is ready - starting Countly"
# Start Countly
exec /opt/countly/bin/countly.sh start

If you create this script, update your Dockerfile:

# Add before EXPOSE
COPY entrypoint.sh /opt/countly/entrypoint.sh
RUN 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:

Terminal window
# Build the Docker image
docker build -t my-countly .
# Run with a local MongoDB container
docker network create countly-network
# Start MongoDB
docker run -d \
--name countly-mongo \
--network countly-network \
-e MONGO_INITDB_DATABASE=countly \
mongo:latest
# Run Countly
docker 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 logs
docker logs -f countly-app
# Access Countly at http://localhost:6001

When you’re done testing:

Terminal window
# Stop and remove containers
docker stop countly-app countly-mongo
docker rm countly-app countly-mongo
docker network rm countly-network

Step 6: Push to GitHub

Commit your Dockerfile and any configuration files to your GitHub repository:

Terminal window
git add Dockerfile config.js entrypoint.sh
git commit -m "Add Countly Dockerfile and configuration"
git remote add origin https://github.com/yourusername/countly-klutch.git
git branch -M main
git push -u origin main

Environment 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.sh
COUNTLY_MONGODB_PORT=27017
COUNTLY_MONGODB_DB=countly
COUNTLY_MONGODB_USERNAME=countly_user
COUNTLY_MONGODB_PASSWORD=your_secure_password

Countly Configuration:

COUNTLY_CONFIG_API_API_HOST=0.0.0.0
COUNTLY_CONFIG_API_API_PORT=6001
COUNTLY_CONFIG_FRONTEND_PRODUCTION=true

Optional Environment Variables

For enhanced functionality, consider adding these optional variables:

Email Configuration (for user notifications):

COUNTLY_CONFIG_EMAIL_EMAIL_HOST=smtp.gmail.com
COUNTLY_CONFIG_EMAIL_EMAIL_PORT=587
COUNTLY_CONFIG_EMAIL_EMAIL_USER=your-email@gmail.com
COUNTLY_CONFIG_EMAIL_EMAIL_PASSWORD=your-app-password
COUNTLY_CONFIG_EMAIL_EMAIL_FROM=noreply@yourdomain.com

Security and Performance:

COUNTLY_CONFIG_API_MAX_SOCKETS=1024
COUNTLY_CONFIG_API_SESSION_SECRET=your-random-session-secret-here
COUNTLY_CONFIG_MONGODB_MAX_POOL_SIZE=500

Important 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

  1. Log Files (/opt/countly/log) - Application logs for debugging and monitoring
  2. Uploaded Files (/opt/countly/frontend/express/public/appimages) - Application icons and images
  3. User Assets (/opt/countly/frontend/express/public/userimages) - User-uploaded profile images
  4. Plugin Data (/opt/countly/plugins) - Custom plugin configurations and data

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

    1. Log in to Klutch.sh

      Navigate to klutch.sh/app and sign in to your account.

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

    3. Create a New App

      Within your project, create a new app for Countly with the following configuration:

    4. Select Your Repository

      • Choose GitHub as your Git source
      • Select the repository containing your Countly Dockerfile
      • Choose the branch you want to deploy (typically main or master)
    5. 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.

    6. 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 address
      • COUNTLY_MONGODB_PORT - MongoDB port (typically 27017)
      • COUNTLY_MONGODB_DB - Database name (typically “countly”)
      • COUNTLY_MONGODB_USERNAME - MongoDB username
      • COUNTLY_MONGODB_PASSWORD - MongoDB password (mark as secret)
    7. 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)
    8. 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)
    9. 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
    10. 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:

Deploy MongoDB as a separate app on Klutch.sh for better isolation and management:

  1. Create a new app in your Klutch.sh project
  2. Deploy MongoDB using a Dockerfile (see the MongoDB deployment guide)
  3. Configure TCP traffic type with internal port 27017
  4. Attach a persistent volume to /data/db (minimum 20GB recommended)
  5. Use the MongoDB app’s URL as COUNTLY_MONGODB_HOST in your Countly configuration

Example MongoDB Dockerfile for Klutch.sh:

FROM mongo:7.0
# Create data directory
RUN mkdir -p /data/db
# Expose MongoDB port
EXPOSE 27017
# MongoDB will listen on all interfaces
CMD ["mongod", "--bind_ip_all"]

MongoDB Environment Variables:

MONGO_INITDB_ROOT_USERNAME=admin
MONGO_INITDB_ROOT_PASSWORD=your-secure-password
MONGO_INITDB_DATABASE=countly

Option 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

  1. Access Your Instance: Navigate to your Klutch.sh app URL (e.g., https://example-app.klutch.sh)

  2. Create Admin Account: On first access, you’ll see a setup wizard. Create your admin account with a strong password.

  3. 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 Countly
Countly.init({
app_key: "YOUR_APP_KEY",
url: "https://example-app.klutch.sh",
debug: false
});
// Track page views automatically
Countly.track_pageview();
// Track custom events
Countly.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';
// Initialize
Countly.init("https://example-app.klutch.sh", "YOUR_APP_KEY");
// Enable crash reporting
Countly.enableCrashReporting();
// Track events
Countly.recordEvent({
key: "purchase",
count: 1,
sum: 29.99,
segmentation: {
product: "premium_plan",
currency: "USD"
}
});

iOS Example (Swift):

import Countly
// Configure Countly
let config: CountlyConfig = CountlyConfig()
config.appKey = "YOUR_APP_KEY"
config.host = "https://example-app.klutch.sh"
config.enableDebug = false
config.enableCrashReporting = true
// Start Countly
Countly.sharedInstance().start(with: config)
// Track events
Countly.sharedInstance().recordEvent("user_action",
segmentation: ["action": "signup", "source": "homepage"])

Android Example (Kotlin):

import ly.count.android.sdk.Countly
// Initialize Countly
Countly.sharedInstance()
.init(this, "https://example-app.klutch.sh", "YOUR_APP_KEY")
.enableCrashReporting()
.setLoggingEnabled(false)
// Track events
val segmentation = HashMap<String, String>()
segmentation["platform"] = "android"
segmentation["version"] = "1.0"
Countly.sharedInstance().events()
.recordEvent("app_opened", segmentation, 1)

Common Analytics Use Cases

  1. User Behavior Tracking: Monitor how users navigate through your application
  2. Conversion Funnels: Track user journey from signup to conversion
  3. Crash Analytics: Automatically collect and analyze app crashes
  4. Push Notifications: Send targeted notifications to user segments
  5. Retention Analysis: Measure user retention over time
  6. 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:

  1. MongoDB Backups: Schedule daily automated backups using mongodump
  2. Volume Snapshots: Create periodic snapshots of persistent volumes
  3. Configuration Backup: Keep copies of environment variables and configs
  4. Disaster Recovery Plan: Document recovery procedures and test regularly
Terminal window
# 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_HOST is 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/log and /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:


Advanced Configuration

Custom Plugins

Countly supports custom plugins for extended functionality. To add custom plugins:

  1. Create a plugins directory in your project
  2. Add your custom plugin code
  3. Update your Dockerfile to copy plugins:
COPY plugins /opt/countly/plugins
  1. Configure plugin settings via environment variables

Email Notifications

Configure email settings for user notifications and alerts:

COUNTLY_CONFIG_EMAIL_EMAIL_HOST=smtp.gmail.com
COUNTLY_CONFIG_EMAIL_EMAIL_PORT=587
COUNTLY_CONFIG_EMAIL_EMAIL_USE_TLS=true
COUNTLY_CONFIG_EMAIL_EMAIL_USER=notifications@yourdomain.com
COUNTLY_CONFIG_EMAIL_EMAIL_PASSWORD=your-app-password

Custom Domain Configuration

To use a custom domain with your Countly instance:

  1. Configure your custom domain in Klutch.sh (see custom domains guide)
  2. Update DNS records to point to your Klutch.sh app
  3. Klutch.sh will automatically handle SSL/TLS certificates
  4. 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 script
const retentionDays = 365; // Keep 1 year of data
const cutoffDate = new Date();
cutoffDate.setDate(cutoffDate.getDate() - retentionDays);
db.events.deleteMany({
timestamp: { $lt: cutoffDate }
});

Additional Resources


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.