Skip to content

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:

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

Step 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 uploads
RUN mkdir -p /data /uploads
# Set working directory
WORKDIR /
# Expose the default Daptin port
EXPOSE 6336
# Volume mount points for persistent data
VOLUME ["/data", "/uploads"]
# Start Daptin with custom arguments
# Database configuration will be provided via environment variables
CMD ["/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:

Terminal window
# Database Configuration
# For PostgreSQL (recommended for production)
DB_TYPE=postgres
DB_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 Configuration
PORT=6336
DAPTIN_ADMIN_EMAIL=admin@example.com
DAPTIN_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-name

Step 4: Create Initialization Script (Optional)

Create a setup.sh script for initial setup and validation:

#!/bin/bash
set -e
echo "Starting Daptin setup..."
# Check if required environment variables are set
if [ -z "$DB_CONNECTION_STRING" ]; then
echo "Error: DB_CONNECTION_STRING is not set"
exit 1
fi
# Create necessary directories
mkdir -p /data /uploads
# Set proper permissions
chmod 755 /data /uploads
echo "Setup completed successfully!"
# Start Daptin
exec /daptin -runtime_path=/data -port=6336

Make the script executable:

Terminal window
chmod +x setup.sh

If 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:

Terminal window
# Start the services
docker-compose up -d
# Check logs
docker-compose logs -f daptin
# Access Daptin at http://localhost:6336
# Stop services when done
docker-compose down

Note: 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:

Terminal window
git add Dockerfile .env.example setup.sh
git commit -m "Add Daptin Dockerfile and configuration"
git remote add origin https://github.com/yourusername/daptin-klutch.git
git push -u origin main

Database Configuration

Daptin supports multiple database backends. Here are the recommended configurations for each:

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=disable

Environment Variables:

Terminal window
DB_TYPE=postgres
DB_CONNECTION_STRING=postgres://daptin_user:secure_password@example-app.klutch.sh:8000/daptin?sslmode=disable

For 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)/database

Environment Variables:

Terminal window
DB_TYPE=mysql
DB_CONNECTION_STRING=daptin_user:secure_password@tcp(example-app.klutch.sh:8000)/daptin

For 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:

Terminal window
DB_TYPE=sqlite3
DB_CONNECTION_STRING=/data/daptin.db

Note: 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

    1. Set Up Your Database

      Before deploying Daptin, set up your database:

      Make note of your database connection details (host, port, username, password, database name).

    2. Log in to Klutch.sh

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

    3. Create a New Project

      Go to Create Project and give your project a meaningful name (e.g., “Daptin API Backend”).

    4. Create a New App

      Navigate to Create App and configure the following settings:

    5. Select Your Repository

      • Choose GitHub as your Git source
      • Select the repository containing your Dockerfile
      • Choose the branch you want to deploy (usually main or master)
    6. 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)
    7. Set Environment Variables

      Add the following environment variables for your Daptin configuration:

      Required Variables:

      • DB_TYPE: Database type (postgres, mysql, or sqlite3)
      • DB_CONNECTION_STRING: Your database connection string (see Database Configuration section above)
      • DAPTIN_ADMIN_EMAIL: Admin email for initial login
      • DAPTIN_ADMIN_PASSWORD: Strong password for admin account
      • DAPTIN_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 integration
      • AWS_SECRET_ACCESS_KEY: For S3 storage integration
      • AWS_REGION: AWS region for S3
      • AWS_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.

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

    9. 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
    10. 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
    11. 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.sh

      Log 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

Getting Started with Daptin

After deploying Daptin, you can start building your API backend through the web dashboard.

Initial Configuration

  1. Access the Dashboard

    Navigate to your Daptin URL: https://example-app.klutch.sh

  2. Log In

    Use the admin credentials you configured during deployment.

  3. 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:

Terminal window
# Get all posts
curl https://example-app.klutch.sh/api/posts
# Get a specific post
curl 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 post
curl -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 post
curl -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 posts
query {
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:

Terminal window
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 API
const DAPTIN_URL = 'https://example-app.klutch.sh';
// Sign in and get token
async 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 posts
async function getPosts(token) {
const response = await fetch(`${DAPTIN_URL}/api/posts`, {
headers: {
'Authorization': `Bearer ${token}`
}
});
return await response.json();
}
// Create a new post
async 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();
}
// Usage
async 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()
# Usage
if __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 /data and /uploads volumes
  • 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_STRING is 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=disable if 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_SECRET is set and consistent across restarts
  • Check that DAPTIN_ADMIN_EMAIL and DAPTIN_ADMIN_PASSWORD are 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 /uploads volume 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:

  1. Add your custom domain in the Klutch.sh dashboard
  2. Point your DNS A/AAAA record to the Klutch.sh provided address or add a CNAME
  3. Update the DAPTIN_SITE_URL environment 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:

Terminal window
AWS_ACCESS_KEY_ID=your-access-key
AWS_SECRET_ACCESS_KEY=your-secret-key
AWS_REGION=us-east-1
AWS_BUCKET_NAME=your-daptin-bucket

Configure cloud storage sites in the Daptin dashboard under Settings > Sites.

Email Configuration

To enable email notifications and user registration emails:

Terminal window
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USERNAME=your-smtp-username
SMTP_PASSWORD=your-smtp-password
SMTP_FROM=noreply@yourdomain.com

OAuth2 Integration

Daptin supports OAuth2 for third-party authentication. Configure OAuth providers in the dashboard under Settings > OAuth Connections.


Additional Resources


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!