Skip to content

Deploying Databag

Databag is a self-hosted, federated messaging platform that prioritizes privacy and security through end-to-end encryption. Unlike centralized messaging services, Databag allows you to run your own instance while still being able to communicate with users on other Databag servers through its federation capabilities. Built with Go for the backend and React for the frontend, Databag provides a modern messaging experience with support for text, images, video, and audio messages, all protected by robust encryption.

The platform stands out for its commitment to privacy—messages are encrypted on your device before being sent, and the server never has access to decryption keys. Databag supports features like group conversations, media sharing, contact management, and profile customization. Its federation protocol means you can maintain independence while staying connected to the broader Databag network, similar to how email works across different providers.

Why Deploy Databag on Klutch.sh?

Deploying Databag on Klutch.sh offers several advantages for hosting your private messaging server:

  • Automatic Docker Detection: Klutch.sh automatically recognizes your Dockerfile and handles the containerization process without manual configuration
  • Persistent Storage: Built-in volume management ensures your messages, media files, and user data persist across deployments
  • Simple HTTP Routing: Access your messaging platform through HTTPS with automatic SSL certificate provisioning
  • Federation Ready: Expose your instance to the internet with proper domain configuration for federated messaging
  • Environment Management: Securely store encryption keys and configuration through environment variables
  • Rapid Deployment: Go from configuration to production in minutes with GitHub integration and automated deployment pipelines
  • Resource Efficiency: Databag’s lightweight architecture makes it cost-effective to host on containerized infrastructure

Prerequisites

Before deploying Databag to Klutch.sh, ensure you have:

  • A Klutch.sh account (sign up here)
  • A GitHub account with a repository for your Databag deployment
  • Basic understanding of Docker and containerization concepts
  • A domain name if you plan to enable federation (optional but recommended)
  • Git installed on your local development machine
  • Understanding of end-to-end encryption concepts (helpful but not required)

Understanding Databag Architecture

Databag follows a client-server architecture with federation capabilities:

Core Components

Go Backend Server

The backend is written in Go, providing a high-performance HTTP API that handles user authentication, message routing, media storage, and federation protocols. The server manages WebSocket connections for real-time message delivery and handles all the cryptographic operations that don’t require access to private keys. Go’s efficient concurrency model ensures the server can handle multiple simultaneous connections with minimal resource overhead.

React Frontend

The web interface is built with React, offering a responsive single-page application that works across desktop and mobile browsers. The frontend handles all client-side encryption and decryption operations, ensuring that your private keys never leave your device. The UI provides an intuitive messaging experience with support for rich media, notifications, and contact management.

SQLite Database

Databag uses SQLite for data persistence, storing user accounts, encrypted message metadata, contact relationships, and server configuration. While messages are stored in encrypted form, the database maintains the necessary indices and relationships for efficient message retrieval and federation.

Media Storage

Uploaded images, videos, and audio files are stored on the filesystem in encrypted form. The server handles media uploads, thumbnail generation, and efficient streaming delivery while maintaining encryption at rest.

Federation Protocol

Databag implements a federation protocol that allows different instances to communicate securely. When you add a contact from another Databag server, your instance establishes a secure connection to relay encrypted messages. Each instance maintains its own user database while participating in the federated network.

Encryption System

End-to-end encryption is implemented using modern cryptographic libraries:

  • Each user has a public/private key pair generated on their device
  • Messages are encrypted with the recipient’s public key before transmission
  • Only the recipient’s private key can decrypt the messages
  • The server never has access to decryption keys or plaintext messages
  • Perfect forward secrecy ensures past messages remain secure

Data Flow

  1. User registers an account and generates encryption keys on their device
  2. Public keys are uploaded to the server; private keys remain on the device
  3. When sending a message, the client encrypts it with the recipient’s public key
  4. Encrypted message is transmitted to the server via WebSocket or HTTP
  5. Server stores the encrypted message and routes it to the recipient
  6. Recipient’s client retrieves and decrypts the message with their private key
  7. For federated contacts, messages are securely relayed between servers
  8. Media files are encrypted before upload and decrypted after download

Storage Requirements

Databag requires persistent storage for:

  • SQLite Database: User accounts, message metadata, and relationships (grows with usage)
  • Media Files: Encrypted images, videos, and audio (can grow significantly)
  • Configuration: Server settings and federation certificates
  • Logs: Application logs for debugging and monitoring

A typical installation might use 100MB-1GB initially, but media-heavy usage can require several gigabytes over time.

Installation and Setup

Let’s walk through setting up Databag for deployment on Klutch.sh.

Step 1: Create the Project Structure

First, create a new directory for your Databag deployment:

Terminal window
mkdir databag-deployment
cd databag-deployment
git init

Step 2: Create the Dockerfile

Create a Dockerfile in the root directory:

FROM golang:1.21-alpine AS backend-build
# Install build dependencies
RUN apk add --no-cache git make gcc musl-dev
# Set working directory
WORKDIR /build
# Clone Databag repository
RUN git clone https://github.com/balzack/databag.git .
# Build the Go backend
WORKDIR /build/net/server
RUN go mod download
RUN CGO_ENABLED=1 GOOS=linux go build -a -installsuffix cgo -o databag-server .
# Frontend build stage
FROM node:18-alpine AS frontend-build
WORKDIR /build
# Copy repository from backend build
COPY --from=backend-build /build /build
# Build the React frontend
WORKDIR /build/net/web
RUN npm install
RUN npm run build
# Final production image
FROM alpine:latest
# Install runtime dependencies
RUN apk add --no-cache ca-certificates sqlite
# Create app user
RUN addgroup -g 1000 databag && \
adduser -D -u 1000 -G databag databag
# Create necessary directories
RUN mkdir -p /opt/databag/data /opt/databag/images
# Copy built artifacts
COPY --from=backend-build /build/net/server/databag-server /opt/databag/
COPY --from=frontend-build /build/net/web/build /opt/databag/web
# Set permissions
RUN chown -R databag:databag /opt/databag
# Switch to app user
USER databag
# Set working directory
WORKDIR /opt/databag
# Expose port
EXPOSE 7000
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD wget --no-verbose --tries=1 --spider http://localhost:7000/health || exit 1
# Start the server
CMD ["./databag-server"]

Step 3: Create Configuration File

Create a .env.example file with configuration options:

Terminal window
# Server Configuration
SERVER_HOST=0.0.0.0
SERVER_PORT=7000
# Database Configuration
DB_PATH=/opt/databag/data/databag.db
# Media Storage
MEDIA_PATH=/opt/databag/images
# Federation Settings (optional)
# FEDERATION_DOMAIN=your-domain.com
# FEDERATION_ENABLED=true
# Security
# ADMIN_PASSWORD=your-secure-admin-password
# Logging
LOG_LEVEL=info

Step 4: Create .dockerignore

Create a .dockerignore file to optimize the build:

node_modules
npm-debug.log
.git
.gitignore
.env
.env.local
*.md
.DS_Store
Thumbs.db
dist/
build/
coverage/
*.sqlite
*.db

Step 5: Create README

Create README.md with deployment information:

# Databag Messaging Server
This repository contains the configuration for deploying Databag on Klutch.sh.
## Features
- End-to-end encrypted messaging
- Federated communication across instances
- Media sharing (images, video, audio)
- Group conversations
- Self-hosted privacy
## Configuration
Copy `.env.example` to `.env` and configure your environment variables.
## Deployment
This application is configured to deploy on Klutch.sh with automatic Docker detection.

Step 6: Initialize Git Repository

Terminal window
git add .
git commit -m "Initial Databag setup for Klutch.sh deployment"
git branch -M master
git remote add origin https://github.com/yourusername/databag-deployment.git
git push -u origin master

Deploying to Klutch.sh

Now that your Databag application is configured, let’s deploy it to Klutch.sh.

  1. Log in to Klutch.sh

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

  2. Create a New Project

    Click “New Project” and select “Import from GitHub”. Choose the repository containing your Databag deployment.

  3. Configure Build Settings

    Klutch.sh will automatically detect the Dockerfile in your repository. The platform will use this for building your container.

  4. Configure Traffic Settings

    Select “HTTP” as the traffic type. Databag serves its web interface on port 7000, and Klutch.sh will route HTTPS traffic to this port.

  5. Set Environment Variables

    In the project settings, add the following environment variables:

    • SERVER_HOST: 0.0.0.0
    • SERVER_PORT: 7000
    • DB_PATH: /opt/databag/data/databag.db
    • MEDIA_PATH: /opt/databag/images
    • LOG_LEVEL: info
    • ADMIN_PASSWORD: your-secure-password (optional but recommended)
  6. Configure Persistent Storage

    Databag requires persistent storage for the database and media files:

    • Database Volume:
      • Mount path: /opt/databag/data
      • Size: 2GB
    • Media Volume:
      • Mount path: /opt/databag/images
      • Size: 5GB (adjust based on expected usage)

    These volumes ensure your messages, media files, and user data persist across deployments.

  7. Deploy the Application

    Click “Deploy” to start the build process. Klutch.sh will:

    • Clone your repository
    • Build the Docker image using your Dockerfile
    • Deploy the container with the specified configuration
    • Provision an HTTPS endpoint

    The build process may take 5-10 minutes as it compiles the Go backend and builds the React frontend.

  8. Access Your Instance

    Once deployment completes, Klutch.sh will provide a URL like example-app.klutch.sh. Visit this URL to access your Databag messaging platform.

Getting Started with Databag

Once your Databag instance is deployed, here’s how to set it up and start using it:

Initial Configuration

  1. Visit your deployed URL (e.g., example-app.klutch.sh)
  2. The first account you create will automatically become the admin account
  3. Set a strong password for your admin account
  4. Complete the initial setup wizard

Creating Your First Account

  1. Click “Create Account” on the login page
  2. Enter your desired username
  3. Create a strong password
  4. Your encryption keys will be automatically generated on your device
  5. Save your recovery phrase in a secure location (critical for account recovery)

Adding Contacts

Local Contacts (same instance)

1. Click the "Contacts" tab
2. Click "Add Contact"
3. Enter the username of another user on your instance
4. Send a contact request
5. Wait for the other user to accept

Federated Contacts (other instances)

1. Click the "Contacts" tab
2. Click "Add Federated Contact"
3. Enter the full contact address: username@their-databag-instance.com
4. Send a contact request
5. Wait for acceptance from the remote user

Sending Messages

  1. Select a contact from your contacts list
  2. Type your message in the input field
  3. Messages are automatically encrypted before sending
  4. Press Enter or click Send

Sharing Media

Images

1. Click the image icon in the message composer
2. Select an image from your device
3. The image will be encrypted and uploaded
4. Recipient can view the decrypted image inline

Videos and Audio

1. Click the attachment icon
2. Select your video or audio file
3. Files are encrypted before upload
4. Recipients can stream the decrypted media

Group Conversations

  1. Click “New Group” in the conversations tab
  2. Enter a group name
  3. Select contacts to add to the group
  4. All group messages are end-to-end encrypted
  5. Each member can add additional contacts

Profile Customization

  1. Click your username in the top-right corner
  2. Select “Profile Settings”
  3. Upload a profile picture (encrypted)
  4. Add a status message
  5. Configure notification preferences

Advanced Configuration

Enabling Federation

To allow users from other Databag instances to add your users as contacts, enable federation:

  1. Configure a custom domain for your Klutch.sh deployment
  2. Add the following environment variables:
Terminal window
FEDERATION_DOMAIN=your-domain.com
FEDERATION_ENABLED=true
  1. Ensure your domain’s DNS is properly configured
  2. Federation requires HTTPS (automatically provided by Klutch.sh)

Admin Panel Access

If you set an ADMIN_PASSWORD environment variable, you can access the admin panel:

  1. Navigate to https://example-app.klutch.sh/admin
  2. Enter your admin password
  3. View server statistics
  4. Manage user accounts
  5. Monitor federation status
  6. Review system logs

Custom Branding

You can customize the appearance of your Databag instance:

Server Name

Add this environment variable:

Terminal window
SERVER_NAME=My Private Messenger

Logo and Colors

For advanced customization, you’ll need to modify the frontend build:

  1. Fork the Databag repository
  2. Edit net/web/src/theme.js for color schemes
  3. Replace logo files in net/web/public/
  4. Rebuild the Docker image with your changes

Backup Configuration

Regular backups are essential for data safety:

Database Backups

The SQLite database contains all user accounts and message metadata. Back it up regularly:

Terminal window
# Access your container
docker exec -it your-container-id /bin/sh
# Create a backup
sqlite3 /opt/databag/data/databag.db ".backup /opt/databag/data/backup.db"

Media Backups

The /opt/databag/images directory contains all encrypted media files. Use Klutch.sh’s volume backup features or set up periodic backups to external storage.

Performance Tuning

Database Optimization

For instances with many users, optimize SQLite:

Terminal window
# Environment variable for better performance
SQLITE_CACHE_SIZE=10000
SQLITE_PAGE_SIZE=4096

Connection Limits

Control concurrent connections:

Terminal window
MAX_CONNECTIONS=100
WEBSOCKET_TIMEOUT=3600

Media Compression

Reduce storage usage by compressing media:

Terminal window
IMAGE_COMPRESSION_QUALITY=85
VIDEO_MAX_RESOLUTION=1080p

Production Best Practices

Follow these recommendations for running Databag in production:

Security

Strong Admin Password

Always set a strong admin password:

Terminal window
ADMIN_PASSWORD=use-a-long-random-password-here

Regular Updates

Keep your Databag instance updated:

  1. Watch the GitHub repository for updates
  2. Update your Dockerfile to pull the latest version
  3. Test updates in a staging environment first
  4. Schedule maintenance windows for updates

Rate Limiting

Protect against abuse with rate limiting:

Terminal window
RATE_LIMIT_ENABLED=true
RATE_LIMIT_REQUESTS=100
RATE_LIMIT_WINDOW=60

HTTPS Only

Ensure all traffic uses HTTPS (automatically enforced by Klutch.sh):

Terminal window
FORCE_HTTPS=true

Data Management

Storage Monitoring

Monitor your persistent volumes:

  • Database size grows with users and messages
  • Media storage can grow rapidly with heavy usage
  • Plan for storage expansion as your community grows
  • Set up alerts when volumes reach 80% capacity

Data Retention Policies

Implement retention policies if needed:

Terminal window
MESSAGE_RETENTION_DAYS=365
MEDIA_RETENTION_DAYS=180

Database Maintenance

Perform regular database maintenance:

Terminal window
# Vacuum the database periodically
VACUUM_ENABLED=true
VACUUM_SCHEDULE=weekly

Performance

Caching

Enable caching for better performance:

Terminal window
CACHE_ENABLED=true
CACHE_TTL=3600

CDN Integration

For media-heavy instances, consider CDN integration for static assets.

Resource Monitoring

Monitor server resources in Klutch.sh:

  • CPU usage during peak hours
  • Memory consumption trends
  • Network bandwidth for media transfers
  • WebSocket connection counts

User Management

Registration Control

Control who can create accounts:

Terminal window
REGISTRATION_ENABLED=true
INVITE_ONLY=false

For private instances, enable invite-only mode:

Terminal window
REGISTRATION_ENABLED=true
INVITE_ONLY=true

User Limits

Set limits to prevent resource exhaustion:

Terminal window
MAX_USERS=1000
MAX_CONTACTS_PER_USER=500
MAX_FILE_SIZE=50M

Monitoring and Logging

Log Configuration

Adjust logging levels based on your needs:

Terminal window
LOG_LEVEL=info # Options: debug, info, warn, error
LOG_FORMAT=json

Health Checks

The Dockerfile includes a health check endpoint at /health. Monitor this endpoint to ensure service availability.

Error Tracking

Review logs regularly for errors:

Terminal window
# View logs through Klutch.sh dashboard
# Look for patterns in failed message deliveries
# Monitor federation connection issues
# Track authentication failures

Troubleshooting

Connection Issues

Problem: Cannot connect to the server

Solutions:

  • Verify the deployment is running in Klutch.sh dashboard
  • Check that HTTPS is working (visit your URL)
  • Ensure SERVER_HOST is set to 0.0.0.0
  • Verify SERVER_PORT is 7000
  • Check browser console for WebSocket errors
  • Test with a different browser or device

Problem: Federation not working

Solutions:

  • Verify FEDERATION_DOMAIN matches your actual domain
  • Ensure FEDERATION_ENABLED is set to true
  • Check DNS configuration for your custom domain
  • Confirm HTTPS certificate is valid
  • Test connectivity from another Databag instance
  • Review federation logs for connection errors

Message Delivery Issues

Problem: Messages not sending

Solutions:

  • Check WebSocket connection status in browser dev tools
  • Verify recipient is online or will receive when they reconnect
  • Ensure database volume has sufficient space
  • Check for encryption key errors in browser console
  • Restart the application if messages are stuck in queue

Problem: Media upload failures

Solutions:

  • Verify media volume has sufficient space
  • Check file size against MAX_FILE_SIZE limit
  • Ensure media path /opt/databag/images is writable
  • Review logs for specific upload errors
  • Try uploading smaller files to isolate the issue
  • Check browser console for client-side errors

Account Issues

Problem: Cannot create account

Solutions:

  • Verify REGISTRATION_ENABLED is true
  • Check if INVITE_ONLY mode requires an invite code
  • Ensure username meets requirements (alphanumeric, no spaces)
  • Review logs for database write errors
  • Verify database volume is mounted correctly
  • Check for username conflicts

Problem: Lost encryption keys

Solutions:

  • If user saved their recovery phrase, use account recovery
  • Without recovery phrase, account data cannot be decrypted
  • Create a new account if recovery is not possible
  • Educate users about importance of recovery phrase backup
  • Consider implementing recovery key backup reminders

Performance Issues

Problem: Slow message delivery

Solutions:

  • Check CPU and memory usage in Klutch.sh dashboard
  • Review database size and performance
  • Increase cache settings if applicable
  • Optimize database with VACUUM command
  • Check for excessive WebSocket connections
  • Review logs for slow queries or operations

Problem: High storage usage

Solutions:

  • Implement data retention policies
  • Clean up old media files
  • Compress images before upload (client-side)
  • Increase volume size in Klutch.sh if needed
  • Archive old conversations
  • Review and delete unused media

Database Issues

Problem: Database corruption

Solutions:

  • Restore from latest backup
  • Run SQLite integrity check
  • Ensure proper shutdown procedures
  • Verify volume mount is stable
  • Check for disk space issues
  • Review logs for write errors before corruption

Problem: Migration failures after updates

Solutions:

  • Always backup before updates
  • Review migration logs for specific errors
  • Rollback to previous version if needed
  • Check database schema compatibility
  • Verify all columns and tables exist
  • Contact Databag support with error details

Additional Resources

Conclusion

Databag provides a powerful solution for self-hosted, encrypted messaging with federation capabilities. By deploying on Klutch.sh, you get the benefits of containerized hosting with automatic HTTPS, persistent storage, and straightforward deployment workflows. Whether you’re setting up a private messenger for your family, a secure communication platform for your organization, or joining the federated Databag network, this deployment gives you full control over your messaging infrastructure.

The combination of end-to-end encryption, federation support, and self-hosting puts you in complete control of your communications. Start your Databag instance today and take back ownership of your private conversations.