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
- User registers an account and generates encryption keys on their device
- Public keys are uploaded to the server; private keys remain on the device
- When sending a message, the client encrypts it with the recipient’s public key
- Encrypted message is transmitted to the server via WebSocket or HTTP
- Server stores the encrypted message and routes it to the recipient
- Recipient’s client retrieves and decrypts the message with their private key
- For federated contacts, messages are securely relayed between servers
- 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:
mkdir databag-deploymentcd databag-deploymentgit initStep 2: Create the Dockerfile
Create a Dockerfile in the root directory:
FROM golang:1.21-alpine AS backend-build
# Install build dependenciesRUN apk add --no-cache git make gcc musl-dev
# Set working directoryWORKDIR /build
# Clone Databag repositoryRUN git clone https://github.com/balzack/databag.git .
# Build the Go backendWORKDIR /build/net/serverRUN go mod downloadRUN CGO_ENABLED=1 GOOS=linux go build -a -installsuffix cgo -o databag-server .
# Frontend build stageFROM node:18-alpine AS frontend-build
WORKDIR /build
# Copy repository from backend buildCOPY --from=backend-build /build /build
# Build the React frontendWORKDIR /build/net/webRUN npm installRUN npm run build
# Final production imageFROM alpine:latest
# Install runtime dependenciesRUN apk add --no-cache ca-certificates sqlite
# Create app userRUN addgroup -g 1000 databag && \ adduser -D -u 1000 -G databag databag
# Create necessary directoriesRUN mkdir -p /opt/databag/data /opt/databag/images
# Copy built artifactsCOPY --from=backend-build /build/net/server/databag-server /opt/databag/COPY --from=frontend-build /build/net/web/build /opt/databag/web
# Set permissionsRUN chown -R databag:databag /opt/databag
# Switch to app userUSER databag
# Set working directoryWORKDIR /opt/databag
# Expose portEXPOSE 7000
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \ CMD wget --no-verbose --tries=1 --spider http://localhost:7000/health || exit 1
# Start the serverCMD ["./databag-server"]Step 3: Create Configuration File
Create a .env.example file with configuration options:
# Server ConfigurationSERVER_HOST=0.0.0.0SERVER_PORT=7000
# Database ConfigurationDB_PATH=/opt/databag/data/databag.db
# Media StorageMEDIA_PATH=/opt/databag/images
# Federation Settings (optional)# FEDERATION_DOMAIN=your-domain.com# FEDERATION_ENABLED=true
# Security# ADMIN_PASSWORD=your-secure-admin-password
# LoggingLOG_LEVEL=infoStep 4: Create .dockerignore
Create a .dockerignore file to optimize the build:
node_modulesnpm-debug.log.git.gitignore.env.env.local*.md.DS_StoreThumbs.dbdist/build/coverage/*.sqlite*.dbStep 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
git add .git commit -m "Initial Databag setup for Klutch.sh deployment"git branch -M mastergit remote add origin https://github.com/yourusername/databag-deployment.gitgit push -u origin masterDeploying to Klutch.sh
Now that your Databag application is configured, let’s deploy it to Klutch.sh.
-
Log in to Klutch.sh
Navigate to klutch.sh/app and sign in with your GitHub account.
-
Create a New Project
Click “New Project” and select “Import from GitHub”. Choose the repository containing your Databag deployment.
-
Configure Build Settings
Klutch.sh will automatically detect the Dockerfile in your repository. The platform will use this for building your container.
-
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.
-
Set Environment Variables
In the project settings, add the following environment variables:
SERVER_HOST:0.0.0.0SERVER_PORT:7000DB_PATH:/opt/databag/data/databag.dbMEDIA_PATH:/opt/databag/imagesLOG_LEVEL:infoADMIN_PASSWORD:your-secure-password(optional but recommended)
-
Configure Persistent Storage
Databag requires persistent storage for the database and media files:
- Database Volume:
- Mount path:
/opt/databag/data - Size:
2GB
- Mount path:
- Media Volume:
- Mount path:
/opt/databag/images - Size:
5GB(adjust based on expected usage)
- Mount path:
These volumes ensure your messages, media files, and user data persist across deployments.
- Database Volume:
-
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.
-
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
- Visit your deployed URL (e.g.,
example-app.klutch.sh) - The first account you create will automatically become the admin account
- Set a strong password for your admin account
- Complete the initial setup wizard
Creating Your First Account
- Click “Create Account” on the login page
- Enter your desired username
- Create a strong password
- Your encryption keys will be automatically generated on your device
- Save your recovery phrase in a secure location (critical for account recovery)
Adding Contacts
Local Contacts (same instance)
1. Click the "Contacts" tab2. Click "Add Contact"3. Enter the username of another user on your instance4. Send a contact request5. Wait for the other user to acceptFederated Contacts (other instances)
1. Click the "Contacts" tab2. Click "Add Federated Contact"3. Enter the full contact address: username@their-databag-instance.com4. Send a contact request5. Wait for acceptance from the remote userSending Messages
- Select a contact from your contacts list
- Type your message in the input field
- Messages are automatically encrypted before sending
- Press Enter or click Send
Sharing Media
Images
1. Click the image icon in the message composer2. Select an image from your device3. The image will be encrypted and uploaded4. Recipient can view the decrypted image inlineVideos and Audio
1. Click the attachment icon2. Select your video or audio file3. Files are encrypted before upload4. Recipients can stream the decrypted mediaGroup Conversations
- Click “New Group” in the conversations tab
- Enter a group name
- Select contacts to add to the group
- All group messages are end-to-end encrypted
- Each member can add additional contacts
Profile Customization
- Click your username in the top-right corner
- Select “Profile Settings”
- Upload a profile picture (encrypted)
- Add a status message
- Configure notification preferences
Advanced Configuration
Enabling Federation
To allow users from other Databag instances to add your users as contacts, enable federation:
- Configure a custom domain for your Klutch.sh deployment
- Add the following environment variables:
FEDERATION_DOMAIN=your-domain.comFEDERATION_ENABLED=true- Ensure your domain’s DNS is properly configured
- 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:
- Navigate to
https://example-app.klutch.sh/admin - Enter your admin password
- View server statistics
- Manage user accounts
- Monitor federation status
- Review system logs
Custom Branding
You can customize the appearance of your Databag instance:
Server Name
Add this environment variable:
SERVER_NAME=My Private MessengerLogo and Colors
For advanced customization, you’ll need to modify the frontend build:
- Fork the Databag repository
- Edit
net/web/src/theme.jsfor color schemes - Replace logo files in
net/web/public/ - 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:
# Access your containerdocker exec -it your-container-id /bin/sh
# Create a backupsqlite3 /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:
# Environment variable for better performanceSQLITE_CACHE_SIZE=10000SQLITE_PAGE_SIZE=4096Connection Limits
Control concurrent connections:
MAX_CONNECTIONS=100WEBSOCKET_TIMEOUT=3600Media Compression
Reduce storage usage by compressing media:
IMAGE_COMPRESSION_QUALITY=85VIDEO_MAX_RESOLUTION=1080pProduction Best Practices
Follow these recommendations for running Databag in production:
Security
Strong Admin Password
Always set a strong admin password:
ADMIN_PASSWORD=use-a-long-random-password-hereRegular Updates
Keep your Databag instance updated:
- Watch the GitHub repository for updates
- Update your Dockerfile to pull the latest version
- Test updates in a staging environment first
- Schedule maintenance windows for updates
Rate Limiting
Protect against abuse with rate limiting:
RATE_LIMIT_ENABLED=trueRATE_LIMIT_REQUESTS=100RATE_LIMIT_WINDOW=60HTTPS Only
Ensure all traffic uses HTTPS (automatically enforced by Klutch.sh):
FORCE_HTTPS=trueData 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:
MESSAGE_RETENTION_DAYS=365MEDIA_RETENTION_DAYS=180Database Maintenance
Perform regular database maintenance:
# Vacuum the database periodicallyVACUUM_ENABLED=trueVACUUM_SCHEDULE=weeklyPerformance
Caching
Enable caching for better performance:
CACHE_ENABLED=trueCACHE_TTL=3600CDN 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:
REGISTRATION_ENABLED=trueINVITE_ONLY=falseFor private instances, enable invite-only mode:
REGISTRATION_ENABLED=trueINVITE_ONLY=trueUser Limits
Set limits to prevent resource exhaustion:
MAX_USERS=1000MAX_CONTACTS_PER_USER=500MAX_FILE_SIZE=50MMonitoring and Logging
Log Configuration
Adjust logging levels based on your needs:
LOG_LEVEL=info # Options: debug, info, warn, errorLOG_FORMAT=jsonHealth Checks
The Dockerfile includes a health check endpoint at /health. Monitor this endpoint to ensure service availability.
Error Tracking
Review logs regularly for errors:
# View logs through Klutch.sh dashboard# Look for patterns in failed message deliveries# Monitor federation connection issues# Track authentication failuresTroubleshooting
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_HOSTis set to0.0.0.0 - Verify
SERVER_PORTis7000 - Check browser console for WebSocket errors
- Test with a different browser or device
Problem: Federation not working
Solutions:
- Verify
FEDERATION_DOMAINmatches your actual domain - Ensure
FEDERATION_ENABLEDis set totrue - 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_SIZElimit - Ensure media path
/opt/databag/imagesis 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_ENABLEDistrue - Check if
INVITE_ONLYmode 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
- Databag GitHub Repository
- Official Documentation
- Issue Tracker
- Klutch.sh Documentation
- Persistent Volumes Guide
- Networking Configuration
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.