Skip to content

Deploying AgencyOS

Introduction

AgencyOS is a powerful open-source business management platform designed to streamline agency operations, client management, project tracking, invoicing, and team collaboration. Built with modern technologies, AgencyOS provides a comprehensive solution for agencies looking to manage their entire workflow from a single, unified interface.

Deploying AgencyOS on Klutch.sh provides you with a scalable, secure, and production-ready infrastructure for your business operations. With automated Dockerfile detection, persistent storage support, and seamless GitHub integration, Klutch.sh makes it simple to deploy and manage your AgencyOS instance. This guide walks you through the complete deployment process, from initial setup to production configuration, ensuring your business management platform is reliable, performant, and ready to scale.

Whether you’re deploying AgencyOS for the first time or migrating an existing instance, this comprehensive guide covers everything you need: Dockerfile configuration, database setup, persistent storage, environment variables, and production best practices.


Prerequisites

Before deploying AgencyOS on Klutch.sh, ensure you have the following:

  • A Klutch.sh account
  • A GitHub repository for your AgencyOS project (you can fork the official AgencyOS repository or create your own)
  • Basic knowledge of Docker and containerization concepts
  • Understanding of environment variables and application configuration
  • (Recommended) A managed database instance or plan to set one up for production use

Project Structure

A typical AgencyOS deployment repository should contain:

agencyos-docker/
├─ Dockerfile
├─ docker-entrypoint.sh
├─ config/
│ └─ production.json
├─ .env.example
└─ README.md

For development, you may also include Docker Compose files for local testing, though Klutch.sh does not support Docker Compose for deployment. The compose file would only be used for local development workflows.


1. Prepare Your AgencyOS Repository

Setting Up Your Repository

    1. Fork or clone the AgencyOS repository from the official source, or create a new repository for your customized deployment.

    2. Create a Dockerfile in the root of your repository (see detailed examples in the next section).

    3. Organize configuration files: Keep sensitive configuration and database files out of your Git repository. Use environment variables and persistent volumes to manage these securely.

    4. Connect your repository to GitHub: Push your code to GitHub, which is the supported Git source for Klutch.sh.

For detailed information on repository setup and GitHub integration, see the Klutch.sh Quick Start Guide.


2. Creating a Production-Ready Dockerfile

Klutch.sh automatically detects a Dockerfile if present in the root directory of your repository. When a Dockerfile is detected, Klutch.sh will use it to build your container image, eliminating the need to manually specify Docker as a deployment option.

Basic Dockerfile for AgencyOS

Here’s a foundational Dockerfile for deploying AgencyOS:

FROM node:18-alpine
# Set working directory
WORKDIR /app
# Install dependencies for building native modules
RUN apk add --no-cache python3 make g++ git
# Copy package files
COPY package*.json ./
# Install dependencies
RUN npm ci --production --silent
# Copy application code
COPY . .
# Create directory for persistent data
RUN mkdir -p /app/data /app/uploads
# Expose the application port
EXPOSE 3000
# Start the application
CMD ["npm", "start"]

Production-Optimized Dockerfile

For a more robust production deployment with health checks and optimized caching:

FROM node:18-alpine AS builder
# Install build dependencies
RUN apk add --no-cache python3 make g++ git
WORKDIR /app
# Copy package files
COPY package*.json ./
# Install all dependencies (including dev dependencies for build)
RUN npm ci --silent
# Copy source code
COPY . .
# Build the application if needed
RUN npm run build || echo "No build step required"
# Production stage
FROM node:18-alpine
# Install runtime dependencies
RUN apk add --no-cache tini
# Create non-root user
RUN addgroup -g 1001 -S agencyos && \
adduser -S agencyos -u 1001
WORKDIR /app
# Copy built application from builder
COPY --from=builder --chown=agencyos:agencyos /app .
# Create persistent data directories
RUN mkdir -p /app/data /app/uploads /app/logs && \
chown -R agencyos:agencyos /app
# Switch to non-root user
USER agencyos
# Expose application port
EXPOSE 3000
# Use tini for proper signal handling
ENTRYPOINT ["/sbin/tini", "--"]
# Start the application
CMD ["node", "server.js"]

Dockerfile with Custom Entrypoint Script

For advanced initialization and configuration management:

FROM node:18-alpine
WORKDIR /app
# Install system dependencies
RUN apk add --no-cache \
python3 \
make \
g++ \
git \
curl \
bash
# Copy package files and install dependencies
COPY package*.json ./
RUN npm ci --production --silent
# Copy application code
COPY . .
# Copy entrypoint script
COPY docker-entrypoint.sh /usr/local/bin/
RUN chmod +x /usr/local/bin/docker-entrypoint.sh
# Create necessary directories
RUN mkdir -p /app/data /app/uploads /app/logs /app/config
# Expose port
EXPOSE 3000
# Set entrypoint
ENTRYPOINT ["docker-entrypoint.sh"]
# Default command
CMD ["npm", "start"]

And the corresponding docker-entrypoint.sh script:

#!/bin/bash
set -e
# Wait for database to be ready
if [ -n "$DB_HOST" ]; then
echo "Waiting for database at $DB_HOST:${DB_PORT:-5432}..."
while ! nc -z "$DB_HOST" "${DB_PORT:-5432}"; do
sleep 1
done
echo "Database is ready!"
fi
# Run database migrations if needed
if [ "$RUN_MIGRATIONS" = "true" ]; then
echo "Running database migrations..."
npm run migrate
fi
# Execute the main command
exec "$@"

3. Persistent Storage Configuration

AgencyOS requires persistent storage for uploaded files, user data, database files, and application logs. Klutch.sh provides persistent volumes that survive deployments and restarts.

Configure the following persistent volumes in the Klutch.sh dashboard:

    1. Application Data: Mount path /app/data for application database files (if using SQLite) and configuration. Recommended size: 5-10 GB

    2. File Uploads: Mount path /app/uploads for user-uploaded files, documents, and media. Recommended size: 20-50 GB depending on usage

    3. Logs: Mount path /app/logs for application logs and debugging information. Recommended size: 5 GB

    4. Configuration: Mount path /app/config for persistent configuration files. Recommended size: 1 GB

Setting Up Volumes in Klutch.sh

When creating your app in the Klutch.sh dashboard:

    1. Navigate to the volume configuration section during app creation
    2. Click “Add Volume” for each mount path you need
    3. Specify the mount path (e.g., /app/data)
    4. Select the appropriate size for your expected usage
    5. The volumes will be created and mounted automatically during deployment

For more details on volume management, see the Klutch.sh Volumes Guide.


4. Environment Variables Configuration

AgencyOS requires several environment variables for proper operation. Configure these in the Klutch.sh dashboard under your app’s environment variables section.

Essential Environment Variables

Terminal window
# Application Configuration
NODE_ENV=production
PORT=3000
APP_URL=https://example-app.klutch.sh
# Database Configuration (PostgreSQL)
DB_TYPE=postgresql
DB_HOST=your-postgres-host
DB_PORT=5432
DB_NAME=agencyos
DB_USER=agencyos_user
DB_PASSWORD=your-secure-password
DB_SSL=true
# Session Configuration
SESSION_SECRET=your-random-session-secret-key-min-32-chars
# File Upload Configuration
UPLOAD_DIR=/app/uploads
MAX_UPLOAD_SIZE=52428800
# Email Configuration (for notifications)
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your-smtp-user
SMTP_PASSWORD=your-smtp-password
SMTP_FROM=noreply@yourdomain.com
# Security
ALLOWED_ORIGINS=https://example-app.klutch.sh,https://yourdomain.com
JWT_SECRET=your-jwt-secret-key-min-32-chars

Optional Environment Variables

Terminal window
# Redis Configuration (for caching and sessions)
REDIS_HOST=your-redis-host
REDIS_PORT=6379
REDIS_PASSWORD=your-redis-password
# Logging
LOG_LEVEL=info
LOG_DIR=/app/logs
# Features
ENABLE_NOTIFICATIONS=true
ENABLE_WEBHOOKS=true
ENABLE_API=true

Setting Environment Variables in Klutch.sh

    1. In the Klutch.sh dashboard, navigate to your app settings
    2. Find the “Environment Variables” section
    3. Add each variable with its corresponding value
    4. Mark sensitive values (passwords, secrets) as “Secret” to encrypt them
    5. Save your changes and redeploy if necessary

Security Best Practices:

  • Never commit secrets or passwords to your Git repository
  • Use strong, randomly generated values for SESSION_SECRET and JWT_SECRET
  • Rotate credentials regularly
  • Use the secret/encrypted option in Klutch.sh for all sensitive values

5. Deploying to Klutch.sh

Step-by-Step Deployment Process

    1. Push your repository to GitHub: Ensure your Dockerfile and all necessary files are committed and pushed to your GitHub repository.

    2. Create a new app in Klutch.sh: Log in to the Klutch.sh dashboard and click “Create New App”.

    3. Connect your GitHub repository: Select your AgencyOS repository from the list. Klutch.sh will automatically detect the Dockerfile in your root directory.

    4. Configure your app:

      • App Name: Choose a descriptive name for your AgencyOS instance
      • Branch: Select the branch to deploy (typically main or production)
      • Region: Choose the region closest to your users for optimal performance
      • Internal Port: Set to 3000 (or the port your AgencyOS app listens on)
    5. Select traffic type: Choose HTTP for AgencyOS web traffic. This allows Klutch.sh to route incoming HTTP/HTTPS requests to your container on the internal port you specified.

    6. Configure compute resources: Select the appropriate instance size based on your expected usage:

      • Small: 0.5 CPU, 512 MB RAM (development/testing)
      • Medium: 1 CPU, 1 GB RAM (small teams)
      • Large: 2 CPU, 2 GB RAM (production)
      • X-Large: 4 CPU, 4 GB RAM (high traffic)
    7. Add persistent volumes: Configure the volumes as described in section 3:

      • /app/data - Application data
      • /app/uploads - File uploads
      • /app/logs - Application logs
    8. Set environment variables: Add all required environment variables from section 4. Use the Klutch.sh secrets feature for sensitive values.

    9. Deploy: Click “Create” to start the deployment. Klutch.sh will:

      • Clone your repository
      • Build the Docker image using your Dockerfile
      • Create the container with your configuration
      • Mount the persistent volumes
      • Start your application
    10. Verify deployment: Once deployment completes, access your AgencyOS instance at the provided URL (e.g., https://example-app.klutch.sh).

Deployment Notes

  • Automatic Dockerfile detection: Klutch.sh automatically detects and uses your Dockerfile when present in the root directory. You don’t need to specify Docker as a deployment method.
  • Build time: Initial deployment may take 3-5 minutes depending on your application size and dependencies.
  • Zero-downtime deployments: Subsequent deployments use rolling updates to ensure your app remains available.

6. Database Setup

AgencyOS typically requires a relational database (PostgreSQL, MySQL, or SQLite for development). For production deployments, we strongly recommend using PostgreSQL.

    1. Provision a PostgreSQL database: You can either:

      • Use a managed PostgreSQL service from a cloud provider
      • Deploy PostgreSQL on Klutch.sh as a separate app
      • Use a dedicated database hosting service
    2. Create the AgencyOS database:

    CREATE DATABASE agencyos;
    CREATE USER agencyos_user WITH ENCRYPTED PASSWORD 'your-secure-password';
    GRANT ALL PRIVILEGES ON DATABASE agencyos TO agencyos_user;
    1. Configure connection: Set the database environment variables in your AgencyOS app (see section 4).

    2. Run initial migrations: AgencyOS will typically run migrations automatically on first start, or you may need to run them manually:

    Terminal window
    npm run migrate

For detailed database deployment instructions, see the PostgreSQL deployment guide.

Using SQLite (Development Only)

For development and testing purposes, you can use SQLite:

Terminal window
DB_TYPE=sqlite
DB_PATH=/app/data/agencyos.db

Ensure the /app/data volume is mounted for SQLite to persist data.

Note: SQLite is not recommended for production use due to concurrency limitations and performance constraints.


7. Getting Started with AgencyOS

Once your AgencyOS instance is deployed and accessible, follow these steps to get started:

Initial Setup

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

    2. Complete the setup wizard: On first launch, you’ll be prompted to:

      • Create an admin account
      • Configure basic organization settings
      • Set up your workspace preferences
    3. Configure your agency: Set up your agency profile, including:

      • Agency name and logo
      • Contact information
      • Timezone and locale settings
    4. Add team members: Invite your team members via email and assign appropriate roles and permissions

    5. Create your first project: Test the system by creating a sample project and familiarizing yourself with the interface

Sample Configuration

Here’s a sample configuration JSON that you might place in /app/config/production.json:

{
"app": {
"name": "Your Agency Name",
"url": "https://example-app.klutch.sh",
"timezone": "America/New_York"
},
"features": {
"notifications": true,
"webhooks": true,
"api": true,
"integrations": true
},
"uploads": {
"maxSize": 52428800,
"allowedTypes": ["image/*", "application/pdf", "application/msword"],
"storage": "local"
},
"email": {
"enabled": true,
"provider": "smtp"
},
"security": {
"sessionTimeout": 3600,
"passwordPolicy": {
"minLength": 8,
"requireUppercase": true,
"requireNumbers": true,
"requireSpecialChars": true
}
}
}

8. Customizing Your Dockerfile for Specific Needs

Changing the Start Command

If you need to customize how AgencyOS starts, you can use Nixpacks environment variables since Klutch.sh uses Nixpacks for builds. However, with a Dockerfile, you have direct control.

To change the start command in your Dockerfile:

# Instead of
CMD ["npm", "start"]
# Use a custom command
CMD ["node", "--max-old-space-size=2048", "server.js"]

Custom Build Commands

If your application requires custom build steps:

# Run custom build command
RUN npm run build:production
# Or with environment-specific configuration
RUN NODE_ENV=production npm run build

Adding System Dependencies

If AgencyOS requires additional system packages:

# For Alpine-based images
RUN apk add --no-cache \
imagemagick \
ghostscript \
poppler-utils
# For Debian-based images
RUN apt-get update && apt-get install -y \
imagemagick \
ghostscript \
poppler-utils && \
rm -rf /var/lib/apt/lists/*

9. Production Best Practices

Performance Optimization

    1. Use multi-stage builds: Reduce final image size by separating build and runtime stages (see production Dockerfile example in section 2)

    2. Enable caching: Configure Redis for session storage and application caching:

    Terminal window
    CACHE_DRIVER=redis
    REDIS_HOST=your-redis-host
    REDIS_PORT=6379
    1. Optimize Node.js: Set appropriate memory limits:
    Terminal window
    NODE_OPTIONS=--max-old-space-size=2048
    1. Monitor resource usage: Use the Klutch.sh dashboard to track CPU, memory, and disk usage. Scale resources as needed.

Security Hardening

    1. Run as non-root user: Always use a non-privileged user in your Dockerfile (see production example)

    2. Enable HTTPS: Klutch.sh automatically provides TLS/SSL for your apps

    3. Set secure headers: Configure your application to set security headers:

    // In your AgencyOS configuration
    headers: {
    'X-Frame-Options': 'DENY',
    'X-Content-Type-Options': 'nosniff',
    'X-XSS-Protection': '1; mode=block',
    'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
    }
    1. Regular updates: Keep your base images and dependencies updated:
    Terminal window
    # Periodically rebuild with updated base image
    docker pull node:18-alpine
    1. Backup regularly: Implement regular backups of your volumes and database

Scaling Considerations

    1. Horizontal scaling: Increase the number of instances in the Klutch.sh dashboard for high availability

    2. Database optimization:

      • Use connection pooling
      • Configure appropriate indexes
      • Monitor query performance
    3. Separate static assets: Consider using a CDN for static files and uploaded content

    4. Session management: Use Redis for distributed session storage when running multiple instances


10. Monitoring and Logging

Application Logs

Access your application logs through the Klutch.sh dashboard:

    1. Navigate to your app in the Klutch.sh dashboard
    2. Click on “Logs” to view real-time application output
    3. Filter logs by time range or search for specific events
    4. Download logs for offline analysis if needed

Health Checks

Implement health check endpoints in your AgencyOS application:

// Example health check endpoint
app.get('/health', (req, res) => {
const health = {
status: 'up',
timestamp: Date.now(),
uptime: process.uptime(),
database: 'connected' // Check actual DB connection
};
res.status(200).json(health);
});

Monitoring Metrics

Monitor key metrics:

  • Response times
  • Database query performance
  • Memory usage
  • CPU utilization
  • Disk I/O
  • Error rates

11. Troubleshooting Common Issues

Application Won’t Start

    1. Check logs: Review application logs in the Klutch.sh dashboard for error messages
    2. Verify environment variables: Ensure all required variables are set correctly
    3. Database connection: Confirm database is accessible and credentials are correct
    4. Port configuration: Verify the internal port matches what your application listens on

File Upload Issues

    1. Check volume mounting: Ensure /app/uploads volume is properly mounted
    2. Verify permissions: Make sure the application user has write access to the upload directory
    3. Check disk space: Ensure the volume has sufficient space available
    4. Review file size limits: Confirm MAX_UPLOAD_SIZE is set appropriately

Performance Problems

    1. Scale resources: Increase CPU and memory allocation in Klutch.sh dashboard
    2. Check database: Monitor database performance and optimize slow queries
    3. Enable caching: Implement Redis caching for frequently accessed data
    4. Review logs: Look for slow requests or errors causing bottlenecks

Database Connection Errors

    1. Verify credentials: Double-check database host, port, username, and password
    2. Network access: Ensure the AgencyOS app can reach the database server
    3. Connection limits: Check if database connection pool is properly configured
    4. SSL requirements: If using SSL, ensure certificates are properly configured

12. Backup and Disaster Recovery

Database Backups

    1. Automated backups: Set up regular database backups using your database provider’s backup features

    2. Manual backup (PostgreSQL example):

    Terminal window
    pg_dump -h $DB_HOST -U $DB_USER -d $DB_NAME > backup-$(date +%Y%m%d).sql
    1. Backup schedule: Implement daily backups with retention policy (e.g., keep 30 days)

Volume Backups

    1. Volume snapshots: Use Klutch.sh volume backup features (when available)
    2. Export important data: Periodically download critical files from your volumes
    3. Test restore procedures: Regularly test your backup restoration process

Disaster Recovery Plan

    1. Document configuration: Keep a copy of all environment variables and settings
    2. Repository backup: Ensure your GitHub repository is backed up
    3. Recovery procedure: Document steps to restore from backup
    4. Test recovery: Periodically test your recovery process in a staging environment

13. Migrating from Another Platform

If you’re migrating an existing AgencyOS instance to Klutch.sh:

    1. Backup existing data: Create complete backups of your database and file uploads

    2. Export environment variables: Document all current environment variables and configuration

    3. Deploy on Klutch.sh: Follow the deployment steps in section 5 to create your new instance

    4. Migrate database:

      • Create database dump from old instance
      • Restore to new PostgreSQL instance
      • Update connection strings
    5. Transfer files: Upload existing files to the persistent volume:

    Terminal window
    # Example using rsync or cloud storage
    rsync -avz /old/uploads/ /app/uploads/
    1. Test thoroughly: Verify all functionality before switching over

    2. Update DNS: Point your domain to the new Klutch.sh deployment

    3. Monitor: Watch logs and performance during the first few days


14. Custom Domain Configuration

To use a custom domain with your AgencyOS deployment:

    1. Add domain in Klutch.sh: Navigate to your app settings and add your custom domain

    2. Update DNS records: Configure your DNS provider:

      • Add an A record pointing to the Klutch.sh provided IP, or
      • Add a CNAME record as instructed by the dashboard
    3. Update environment variables: Update APP_URL to reflect your custom domain:

    Terminal window
    APP_URL=https://agency.yourdomain.com
    1. SSL/TLS: Klutch.sh automatically provisions and manages SSL certificates for your custom domain

    2. Verify: Access your AgencyOS instance via the custom domain to confirm everything works

For more details, see the Klutch.sh Custom Domains guide.


15. Example: Complete Quickstart

Here’s a complete, copy-paste quickstart to get AgencyOS running on Klutch.sh:

1. Create Repository

Terminal window
mkdir agencyos-docker
cd agencyos-docker
git init

2. Create Dockerfile

FROM node:18-alpine
WORKDIR /app
RUN apk add --no-cache python3 make g++ git
COPY package*.json ./
RUN npm ci --production
COPY . .
RUN mkdir -p /app/data /app/uploads /app/logs
EXPOSE 3000
CMD ["npm", "start"]

3. Create .env.example

Terminal window
NODE_ENV=production
PORT=3000
APP_URL=https://example-app.klutch.sh
DB_TYPE=postgresql
DB_HOST=your-db-host
DB_PORT=5432
DB_NAME=agencyos
DB_USER=agencyos_user
DB_PASSWORD=change-me
SESSION_SECRET=change-me-min-32-chars
JWT_SECRET=change-me-min-32-chars

4. Commit and Push

Terminal window
git add .
git commit -m "Initial AgencyOS Docker setup"
git remote add origin https://github.com/yourusername/agencyos-docker.git
git push -u origin main

5. Deploy on Klutch.sh

    1. Go to Klutch.sh dashboard
    2. Click “Create New App”
    3. Connect your GitHub repository
    4. Set internal port to 3000
    5. Select HTTP traffic type
    6. Add volumes: /app/data, /app/uploads, /app/logs
    7. Add environment variables from .env.example
    8. Click “Create”

Your AgencyOS instance will be live in 3-5 minutes at https://example-app.klutch.sh!


Resources