Deploying a Daptin App
Introduction
Daptin is a powerful open-source backend server that instantly provides a GraphQL and JSON-API based web service from database tables. It’s designed as a low-code platform that transforms your database schema into a full-featured REST API with authentication, authorization, and data relationships built in. Daptin offers a comprehensive solution for developers looking to quickly build scalable backends without writing extensive boilerplate code.
Daptin is known for its:
- Instant GraphQL & JSON-API: Automatically generates API endpoints from database schemas
- Authentication & Authorization: Built-in OAuth2, JWT, and role-based access control (RBAC)
- Multi-Database Support: Works with PostgreSQL, MySQL, SQLite, and more
- Data Modeling: Define entities, relationships, and workflows through a web interface
- Cloud Storage Integration: Native support for S3, Google Drive, Dropbox, and other storage backends
- Extensibility: Custom actions, workflows, and integrations
- Self-Hosted: Complete control over your data and infrastructure
This comprehensive guide walks you through deploying Daptin on Klutch.sh using Docker, including detailed installation steps, database configuration, persistent storage setup, and production-ready best practices.
Prerequisites
Before you begin, ensure you have the following:
- A Klutch.sh account
- A GitHub account with a repository for your Daptin project
- Docker installed locally for testing (optional but recommended)
- Basic understanding of Docker, APIs, and database concepts
- (Recommended) A PostgreSQL or MySQL database instance for production use
Installation and Setup
Step 1: Create Your Project Directory
First, create a new directory for your Daptin deployment project:
mkdir daptin-klutchcd daptin-klutchgit initStep 2: Create the Dockerfile
Create a Dockerfile in your project root directory. This will define your Daptin container configuration:
FROM daptin/daptin:latest
# Create directories for data and uploadsRUN mkdir -p /data /uploads
# Set working directoryWORKDIR /
# Expose the default Daptin portEXPOSE 6336
# Volume mount points for persistent dataVOLUME ["/data", "/uploads"]
# Start Daptin with custom arguments# Database configuration will be provided via environment variablesCMD ["/daptin", "-runtime_path=/data", "-port=6336"]Note: The daptin/daptin:latest image is the official Docker image for Daptin. For production, consider pinning to a specific version tag.
Step 3: Create Environment Configuration File
Create a .env.example file to document the environment variables needed:
# Database Configuration# For PostgreSQL (recommended for production)DB_TYPE=postgresDB_CONNECTION_STRING=postgres://username:password@postgres-host:5432/daptin?sslmode=disable
# For MySQL# DB_TYPE=mysql# DB_CONNECTION_STRING=username:password@tcp(mysql-host:3306)/daptin
# For SQLite (development only)# DB_TYPE=sqlite3# DB_CONNECTION_STRING=/data/daptin.db
# Daptin ConfigurationPORT=6336DAPTIN_ADMIN_EMAIL=admin@example.comDAPTIN_ADMIN_PASSWORD=your-secure-password
# JWT Secret for authentication (generate a random string)DAPTIN_JWT_SECRET=your-random-jwt-secret-key-here
# Optional: Cloud Storage Configuration# AWS_ACCESS_KEY_ID=your-aws-access-key# AWS_SECRET_ACCESS_KEY=your-aws-secret-key# AWS_REGION=us-east-1# AWS_BUCKET_NAME=your-bucket-nameStep 4: Create Initialization Script (Optional)
Create a setup.sh script for initial setup and validation:
#!/bin/bashset -e
echo "Starting Daptin setup..."
# Check if required environment variables are setif [ -z "$DB_CONNECTION_STRING" ]; then echo "Error: DB_CONNECTION_STRING is not set" exit 1fi
# Create necessary directoriesmkdir -p /data /uploads
# Set proper permissionschmod 755 /data /uploads
echo "Setup completed successfully!"
# Start Daptinexec /daptin -runtime_path=/data -port=6336Make the script executable:
chmod +x setup.shIf using this script, update your Dockerfile’s CMD to:
CMD ["/bin/sh", "/setup.sh"]Step 5: Test Locally (Optional)
Before deploying to Klutch.sh, you can test your Daptin setup locally with Docker Compose:
version: '3.8'
services: postgres: image: postgres:15-alpine environment: POSTGRES_DB: daptin POSTGRES_USER: daptin_user POSTGRES_PASSWORD: secure_password volumes: - postgres_data:/var/lib/postgresql/data ports: - "5432:5432"
daptin: build: . ports: - "6336:6336" environment: DB_TYPE: postgres DB_CONNECTION_STRING: postgres://daptin_user:secure_password@postgres:5432/daptin?sslmode=disable DAPTIN_ADMIN_EMAIL: admin@example.com DAPTIN_ADMIN_PASSWORD: admin123 DAPTIN_JWT_SECRET: your-random-jwt-secret-key volumes: - daptin_data:/data - daptin_uploads:/uploads depends_on: - postgres
volumes: postgres_data: daptin_data: daptin_uploads:Test locally:
# Start the servicesdocker-compose up -d
# Check logsdocker-compose logs -f daptin
# Access Daptin at http://localhost:6336# Stop services when donedocker-compose downNote: Docker Compose is only for local development and testing. Klutch.sh does not support Docker Compose for deployments.
Step 6: Push to GitHub
Commit your files to your GitHub repository:
git add Dockerfile .env.example setup.shgit commit -m "Add Daptin Dockerfile and configuration"git remote add origin https://github.com/yourusername/daptin-klutch.gitgit push -u origin mainDatabase Configuration
Daptin supports multiple database backends. Here are the recommended configurations for each:
PostgreSQL (Recommended for Production)
PostgreSQL is the recommended database for production deployments due to its reliability and feature set.
Connection String Format:
postgres://username:password@host:8000/database?sslmode=disableEnvironment Variables:
DB_TYPE=postgresDB_CONNECTION_STRING=postgres://daptin_user:secure_password@example-app.klutch.sh:8000/daptin?sslmode=disableFor detailed PostgreSQL setup on Klutch.sh, see the PostgreSQL deployment guide.
MySQL
MySQL is also well-supported and offers excellent performance.
Connection String Format:
username:password@tcp(host:8000)/databaseEnvironment Variables:
DB_TYPE=mysqlDB_CONNECTION_STRING=daptin_user:secure_password@tcp(example-app.klutch.sh:8000)/daptinFor detailed MySQL setup on Klutch.sh, see the MySQL deployment guide.
SQLite (Development Only)
SQLite is suitable for development and testing but not recommended for production.
Environment Variables:
DB_TYPE=sqlite3DB_CONNECTION_STRING=/data/daptin.dbNote: When using SQLite, ensure you have a persistent volume mounted at /data.
Deploying to Klutch.sh
Now that your Daptin project is ready and pushed to GitHub, follow these steps to deploy it on Klutch.sh with persistent storage.
Deployment Steps
-
Set Up Your Database
Before deploying Daptin, set up your database:
- For PostgreSQL: Follow the PostgreSQL guide
- For MySQL: Follow the MySQL guide
Make note of your database connection details (host, port, username, password, database name).
-
Log in to Klutch.sh
Navigate to klutch.sh/app and sign in to your account.
-
Create a New Project
Go to Create Project and give your project a meaningful name (e.g., “Daptin API Backend”).
-
Create a New App
Navigate to Create App and configure the following settings:
-
Select Your Repository
- Choose GitHub as your Git source
- Select the repository containing your Dockerfile
- Choose the branch you want to deploy (usually
mainormaster)
-
Configure Traffic Type
- Traffic Type: Select HTTP (Daptin provides a web API and dashboard)
- Internal Port: Set to
6336(the default Daptin port that your container listens on)
-
Set Environment Variables
Add the following environment variables for your Daptin configuration:
Required Variables:
DB_TYPE: Database type (postgres,mysql, orsqlite3)DB_CONNECTION_STRING: Your database connection string (see Database Configuration section above)DAPTIN_ADMIN_EMAIL: Admin email for initial loginDAPTIN_ADMIN_PASSWORD: Strong password for admin accountDAPTIN_JWT_SECRET: Random secret key for JWT token signing (generate a secure random string)
Optional Variables:
PORT: Port number (default:6336)AWS_ACCESS_KEY_ID: For S3 storage integrationAWS_SECRET_ACCESS_KEY: For S3 storage integrationAWS_REGION: AWS region for S3AWS_BUCKET_NAME: S3 bucket name
Security Note: Always use strong, unique passwords and JWT secrets for production deployments. Never commit sensitive credentials to your repository.
-
Attach Persistent Volumes
Daptin requires persistent storage for runtime data and user uploads:
First Volume - Runtime Data:
- In the Volumes section, click “Add Volume”
- Mount Path: Enter
/data(where Daptin stores configuration and runtime data) - Size: Choose 5GB to 10GB (adjust based on expected usage)
Second Volume - User Uploads:
- Click “Add Volume” again
- Mount Path: Enter
/uploads(where Daptin stores user-uploaded files) - Size: Choose 10GB to 50GB (adjust based on expected file storage needs)
Important: Persistent volumes ensure your data persists across deployments and restarts.
-
Configure Additional Settings
- Region: Select the region closest to your users for optimal latency
- Compute Resources: Choose CPU and memory based on your workload
- Minimum recommended: 1 CPU core, 1GB RAM
- Production recommended: 2 CPU cores, 2GB RAM or higher
- Instances: Start with 1 instance
-
Deploy Your Daptin Application
Click “Create” to start the deployment. Klutch.sh will:
- Automatically detect your Dockerfile in the repository root
- Build the Docker image
- Attach the persistent volumes
- Start your Daptin container
- Assign a URL for accessing your application
-
Access Your Daptin Dashboard
Once deployment is complete, you’ll receive a URL like
example-app.klutch.sh. Access your Daptin installation at:https://example-app.klutch.shLog in with the admin credentials you set in the environment variables:
- Email: The value from
DAPTIN_ADMIN_EMAIL - Password: The value from
DAPTIN_ADMIN_PASSWORD
- Email: The value from
Getting Started with Daptin
After deploying Daptin, you can start building your API backend through the web dashboard.
Initial Configuration
-
Access the Dashboard
Navigate to your Daptin URL:
https://example-app.klutch.sh -
Log In
Use the admin credentials you configured during deployment.
-
Configure Your First Entity
Entities in Daptin are similar to database tables. To create your first entity:
- Click on “Entities” in the left sidebar
- Click “Add Entity”
- Define your entity name (e.g., “users”, “posts”, “products”)
- Add columns with appropriate data types
- Set relationships between entities if needed
- Click “Save”
Example: Creating a Blog API
Here’s a quick example of creating a simple blog API with Daptin:
1. Create a “posts” entity with the following columns:
{ "name": "posts", "columns": [ { "name": "title", "column_type": "label", "is_nullable": false }, { "name": "content", "column_type": "content", "is_nullable": false }, { "name": "author", "column_type": "label", "is_nullable": false }, { "name": "published_at", "column_type": "datetime", "is_nullable": true }, { "name": "is_published", "column_type": "truefalse", "default_value": false } ]}2. Access the API:
Once created, Daptin automatically generates REST and GraphQL endpoints:
REST API Examples:
# Get all postscurl https://example-app.klutch.sh/api/posts
# Get a specific postcurl https://example-app.klutch.sh/api/posts/{id}
# Create a new post (requires authentication)curl -X POST https://example-app.klutch.sh/api/posts \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_JWT_TOKEN" \ -d '{ "data": { "type": "posts", "attributes": { "title": "My First Blog Post", "content": "This is the content of my first post", "author": "John Doe", "is_published": true } } }'
# Update a postcurl -X PATCH https://example-app.klutch.sh/api/posts/{id} \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_JWT_TOKEN" \ -d '{ "data": { "type": "posts", "attributes": { "title": "Updated Title" } } }'
# Delete a postcurl -X DELETE https://example-app.klutch.sh/api/posts/{id} \ -H "Authorization: Bearer YOUR_JWT_TOKEN"GraphQL API Example:
# GraphQL endpoint: https://example-app.klutch.sh/graphql
# Query all postsquery { posts { id title content author published_at is_published }}
# Create a post (mutation)mutation { createPost(input: { title: "My First Post" content: "This is the content" author: "John Doe" is_published: true }) { id title created_at }}Authentication
Daptin uses JWT (JSON Web Tokens) for authentication. To get a token:
curl -X POST https://example-app.klutch.sh/action/user/signin \ -H "Content-Type: application/json" \ -d '{ "attributes": { "email": "admin@example.com", "password": "your-admin-password" } }'The response will include a JWT token that you can use for authenticated requests.
Sample Client Code
JavaScript/Node.js Example:
// Using fetch APIconst DAPTIN_URL = 'https://example-app.klutch.sh';
// Sign in and get tokenasync function signIn(email, password) { const response = await fetch(`${DAPTIN_URL}/action/user/signin`, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ attributes: { email, password } }) });
const data = await response.json(); return data.token;}
// Get all postsasync function getPosts(token) { const response = await fetch(`${DAPTIN_URL}/api/posts`, { headers: { 'Authorization': `Bearer ${token}` } });
return await response.json();}
// Create a new postasync function createPost(token, postData) { const response = await fetch(`${DAPTIN_URL}/api/posts`, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${token}` }, body: JSON.stringify({ data: { type: 'posts', attributes: postData } }) });
return await response.json();}
// Usageasync function main() { const token = await signIn('admin@example.com', 'your-password'); const posts = await getPosts(token); console.log(posts);
const newPost = await createPost(token, { title: 'New Post', content: 'Post content', author: 'John Doe', is_published: true }); console.log(newPost);}
main();Python Example:
import requests
DAPTIN_URL = 'https://example-app.klutch.sh'
def sign_in(email, password): """Sign in and get JWT token""" response = requests.post( f'{DAPTIN_URL}/action/user/signin', json={'attributes': {'email': email, 'password': password}} ) return response.json()['token']
def get_posts(token): """Get all posts""" response = requests.get( f'{DAPTIN_URL}/api/posts', headers={'Authorization': f'Bearer {token}'} ) return response.json()
def create_post(token, post_data): """Create a new post""" response = requests.post( f'{DAPTIN_URL}/api/posts', headers={ 'Content-Type': 'application/json', 'Authorization': f'Bearer {token}' }, json={ 'data': { 'type': 'posts', 'attributes': post_data } } ) return response.json()
# Usageif __name__ == '__main__': token = sign_in('admin@example.com', 'your-password') posts = get_posts(token) print(posts)
new_post = create_post(token, { 'title': 'New Post', 'content': 'Post content', 'author': 'John Doe', 'is_published': True }) print(new_post)Production Best Practices
Security Recommendations
- Strong Credentials: Use strong, randomly generated passwords for admin accounts and database credentials
- JWT Secret: Generate a cryptographically secure random string for
DAPTIN_JWT_SECRET(at least 32 characters) - HTTPS Only: Always use HTTPS in production (Klutch.sh provides this automatically)
- Environment Variables: Never commit sensitive credentials to version control; use Klutch.sh environment variables
- Access Control: Configure proper role-based access control (RBAC) in Daptin for different user types
- Regular Updates: Keep Daptin updated to the latest version for security patches
- Database Security: Use strong database passwords and restrict database access to only the Daptin application
Performance Optimization
- Database Indexing: Create appropriate indexes on frequently queried columns in your database
- Connection Pooling: Ensure your database is configured with adequate connection pooling
- Resource Allocation: Monitor CPU and memory usage and scale resources as needed
- Caching: Implement caching strategies for frequently accessed data
- Query Optimization: Review and optimize slow database queries
- File Storage: For large file uploads, consider using external cloud storage (S3, etc.) instead of local volumes
Backup and Recovery
- Database Backups: Implement regular automated backups of your database
- Volume Snapshots: Regularly backup the
/dataand/uploadsvolumes - Backup Testing: Periodically test your backup restoration process
- Disaster Recovery Plan: Document your recovery procedures
Monitoring and Maintenance
Monitor your Daptin deployment for:
- API response times and latency
- Database query performance
- Error rates and exceptions
- CPU and memory utilization
- Disk usage for persistent volumes
- Number of active connections
- Authentication failures (potential security issues)
Scaling Considerations
- Vertical Scaling: Increase CPU and memory allocation as your API usage grows
- Database Scaling: Consider read replicas for read-heavy workloads
- File Storage: Monitor upload volume growth and increase storage capacity proactively
- Load Testing: Perform load testing to understand your application’s limits
- Caching Layer: Implement Redis or similar caching for improved performance
Troubleshooting
Application Won’t Start
Symptom: Container fails to start or immediately exits
Solutions:
- Verify
DB_CONNECTION_STRINGis correctly formatted for your database type - Check that your database is accessible from your Daptin container
- Review container logs for specific error messages
- Ensure all required environment variables are set
Database Connection Errors
Symptom: “Failed to connect to database” errors
Solutions:
- Verify database credentials are correct
- Check that the database host is accessible on port 8000 (for Klutch.sh TCP apps)
- Ensure the database exists and the user has proper permissions
- For PostgreSQL, verify the connection string includes
sslmode=disableif SSL is not configured - Test database connectivity using a database client with the same connection string
Authentication Issues
Symptom: Unable to log in or JWT token errors
Solutions:
- Verify
DAPTIN_JWT_SECRETis set and consistent across restarts - Check that
DAPTIN_ADMIN_EMAILandDAPTIN_ADMIN_PASSWORDare correctly set - Clear browser cache and cookies
- Try resetting the admin password through the database if necessary
File Upload Failures
Symptom: Files fail to upload or are not persisting
Solutions:
- Verify the
/uploadsvolume is properly attached with sufficient space - Check volume permissions (should be writable by the container user)
- Monitor disk space usage in the Klutch.sh dashboard
- Review Daptin logs for specific file upload errors
Performance Issues
Symptom: Slow API responses or timeouts
Solutions:
- Review database query performance and add indexes as needed
- Increase CPU and memory allocation in Klutch.sh
- Check for expensive operations in Daptin workflows or actions
- Implement caching for frequently accessed data
- Monitor database connection pool settings
API Endpoint Not Found
Symptom: 404 errors when accessing API endpoints
Solutions:
- Verify the entity name matches the endpoint path
- Check that the entity is properly created in the Daptin dashboard
- Ensure Daptin has completed database migrations
- Review API documentation in the Daptin dashboard
Advanced Configuration
Custom Domain Setup
To use a custom domain with your Daptin deployment:
- Add your custom domain in the Klutch.sh dashboard
- Point your DNS A/AAAA record to the Klutch.sh provided address or add a CNAME
- Update the
DAPTIN_SITE_URLenvironment variable to your custom domain
For detailed instructions, see Klutch.sh Custom Domains Guide.
Cloud Storage Integration
To integrate with cloud storage providers:
For AWS S3:
AWS_ACCESS_KEY_ID=your-access-keyAWS_SECRET_ACCESS_KEY=your-secret-keyAWS_REGION=us-east-1AWS_BUCKET_NAME=your-daptin-bucketConfigure cloud storage sites in the Daptin dashboard under Settings > Sites.
Email Configuration
To enable email notifications and user registration emails:
SMTP_HOST=smtp.example.comSMTP_PORT=587SMTP_USERNAME=your-smtp-usernameSMTP_PASSWORD=your-smtp-passwordSMTP_FROM=noreply@yourdomain.comOAuth2 Integration
Daptin supports OAuth2 for third-party authentication. Configure OAuth providers in the dashboard under Settings > OAuth Connections.
Additional Resources
- Klutch.sh Documentation
- Official Daptin Documentation
- Daptin GitHub Repository
- Daptin Docker Image
- Klutch.sh Volumes Guide
- Klutch.sh Networking Guide
- PostgreSQL Deployment Guide
- MySQL Deployment Guide
Conclusion
Deploying Daptin on Klutch.sh provides a powerful, scalable backend-as-a-service platform that can significantly accelerate your application development. With automatic API generation, built-in authentication, and extensive customization options, Daptin enables you to focus on building features rather than boilerplate code.
By following this guide, you’ve set up a production-ready Daptin installation with proper database connectivity, persistent storage, security configurations, and monitoring capabilities. Your backend is now ready to power your applications with a robust, self-hosted API platform.
Start building your entities and relationships through the Daptin dashboard, and watch as your backend API comes to life automatically. Happy coding!