Deploying Docassemble
Introduction
Docassemble is a powerful open-source expert system designed for guided interviews and automated document assembly. Built on Python and Flask, Docassemble enables legal professionals, organizations, and developers to create sophisticated interactive questionnaires that generate customized documents, contracts, legal forms, and reports based on user responses.
Docassemble is renowned for its:
- Guided Interviews: Create branching logic questionnaires that adapt based on user input
- Document Assembly: Generate PDFs, DOCX files, and other formats from templates
- Legal Focus: Specifically designed for legal document automation and access to justice initiatives
- Multi-language Support: Internationalization capabilities for global deployments
- Python-Powered: Leverage Python’s extensive libraries for complex logic and data processing
- Flexible Templates: Use Markdown, DOCX, or PDF templates with variable substitution
- User Management: Built-in authentication and multi-tenancy support
- API Access: RESTful API for integration with other systems
- Playground Interface: Built-in development environment for creating and testing interviews
This comprehensive guide walks you through deploying Docassemble on Klutch.sh using Docker, including detailed installation steps, sample configurations, 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 Docassemble project
- Docker installed locally for testing (optional but recommended)
- Basic understanding of Docker, environment variables, and document assembly concepts
- (Optional) A PostgreSQL database for production deployments (Docassemble includes an embedded database for testing)
Installation and Setup
Step 1: Create Your Project Directory
First, create a new directory for your Docassemble deployment project:
mkdir docassemble-klutchcd docassemble-klutchgit initStep 2: Create the Dockerfile
Create a Dockerfile in your project root directory. This will define your Docassemble container configuration:
# Use the official Docassemble imageFROM jhpyle/docassemble:latest
# Set environment variables for basic configuration# These can be overridden in the Klutch.sh dashboardENV DAHOSTNAME=example-app.klutch.shENV TIMEZONE=America/New_YorkENV LOCALE=en_US.UTF-8
# Docassemble uses port 80 internallyEXPOSE 80
# Optional: Pre-configure additional settings# ENV USEHTTPS=false# ENV BEHIND_HTTPS_LOAD_BALANCER=true
# The base image already includes the entrypoint# No CMD needed as it's inherited from the base imageNote: The official Docassemble Docker image (jhpyle/docassemble) includes a complete environment with Python, Flask, PostgreSQL (embedded), Redis, and all necessary dependencies for running guided interviews and document assembly.
Step 3: Create Environment Configuration File
Create a .env.example file to document your environment variables:
# .env.example - Document your Docassemble configuration# Do not commit actual secrets to git
# Hostname where Docassemble will be accessibleDAHOSTNAME=example-app.klutch.sh
# Timezone for the applicationTIMEZONE=America/New_York
# Locale settingsLOCALE=en_US.UTF-8
# Database configuration (if using external PostgreSQL)# DB_HOST=postgres.example.com# DB_PORT=5432# DB_NAME=docassemble# DB_USER=docassemble# DB_PASSWORD=your_secure_password
# Admin email (for initial setup)# CONTAINERROLE=admin# DAPYTHONVERSION=3
# S3 configuration (optional for file storage)# S3ENABLE=true# S3BUCKET=docassemble-files# S3ACCESSKEY=your_access_key# S3SECRETACCESSKEY=your_secret_key# S3REGION=us-east-1
# Email configuration (optional for notifications)# MAIL_SERVER=smtp.example.com# MAIL_PORT=587# MAIL_USERNAME=noreply@example.com# MAIL_PASSWORD=your_email_password# MAIL_USE_TLS=true
# Security settings# BEHIND_HTTPS_LOAD_BALANCER=true# USEHTTPS=falseStep 4: Create README
Create a README.md file to document your deployment:
# Docassemble on Klutch.sh
This repository contains the Dockerfile and configuration for deploying Docassemble on Klutch.sh.
## What is Docassemble?
Docassemble is an expert system for guided interviews and document assembly, primarily used for legal document automation.
## Deployment
See the main documentation for detailed deployment instructions.
## Environment Variables
Copy `.env.example` to `.env` and configure your settings before deployment.
## Support
- <a href="https://docassemble.org/docs.html" target="_blank" rel="noopener noreferrer">Docassemble Documentation</a>- <a href="https://docs.klutch.sh?utm_source=docs" target="_blank">Klutch.sh Support</a>Step 5: Push to GitHub
Commit your Dockerfile and configuration files to your GitHub repository:
git add Dockerfile .env.example README.mdgit commit -m "Add Docassemble Dockerfile and configuration"git remote add origin https://github.com/yourusername/docassemble-klutch.gitgit push -u origin mainDeploying to Klutch.sh
Now that your Docassemble project is ready and pushed to GitHub, follow these steps to deploy it on Klutch.sh with persistent storage.
Deployment Steps
-
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., “Docassemble Document Assembly”).
-
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 (Docassemble is a web application that needs HTTP traffic)
- Internal Port: Set to
80(the port your container listens on)
-
Set Environment Variables
Add the following environment variables for your Docassemble configuration:
Required environment variables:
DAHOSTNAME: The public URL where your app will be accessible (e.g.,example-app.klutch.sh)TIMEZONE: Your preferred timezone (e.g.,America/New_York,Europe/London,Asia/Tokyo)LOCALE: Your preferred locale (e.g.,en_US.UTF-8)
Recommended environment variables:
BEHIND_HTTPS_LOAD_BALANCER: Set totrue(Klutch.sh provides HTTPS termination)USEHTTPS: Set tofalse(since HTTPS is handled by Klutch.sh)CONTAINERROLE: Set toadminfor the initial setup
Optional environment variables:
- Database configuration if using external PostgreSQL
- S3 configuration if using external file storage
- Email/SMTP settings for notifications
Security Note: Always use strong, unique passwords for database credentials and avoid committing secrets to your repository.
-
Attach Persistent Volumes
Docassemble requires persistent storage to maintain interview data, uploaded files, and configuration across deployments. You should attach two volumes:
Volume 1: Main Application Data
- Mount Path: Enter
/usr/share/docassemble/webapp/docassemble-filestorage - Size: Choose based on expected usage (e.g., 10GB for small deployments, 50GB+ for production with many interviews and documents)
Volume 2: Backups
- Mount Path: Enter
/usr/share/docassemble/backup - Size: Choose based on backup retention needs (e.g., 5-20GB)
Important: These persistent volumes are critical for ensuring your interview data, uploaded documents, and user-generated content persist between container restarts and deployments.
- Mount Path: Enter
-
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: 1 CPU, 2GB RAM for testing
- Recommended: 2 CPU, 4GB RAM for production
- Heavy usage: 4+ CPU, 8GB+ RAM for large deployments with many concurrent users
- Instances: Start with 1 instance (you can scale later based on usage)
-
Deploy Your Application
Click “Create” to start the deployment. Klutch.sh will:
- Automatically detect your Dockerfile in the repository root
- Build the Docker image from the official Docassemble base
- Attach the persistent volumes
- Start your Docassemble container
- Assign a URL for accessing your application
-
Access Your Docassemble Instance
Once deployment is complete, you’ll receive a URL like
example-app.klutch.sh. Visit this URL in your browser to access Docassemble.On your first visit, you’ll see the Docassemble welcome screen. You’ll need to complete the initial setup:
- Create an admin account with a strong password
- Configure basic settings through the admin interface
- Access the admin panel at
/adminto configure interviews, templates, and users
Getting Started with Docassemble
Accessing the Admin Interface
After deploying, access the admin interface to configure your Docassemble instance:
- Navigate to
https://example-app.klutch.sh/admin(replace with your actual URL) - Log in with the admin credentials you created during setup
- Explore the following key sections:
- Playground: Develop and test interviews in a live environment
- Package Management: Install pre-built interview packages
- User Management: Create and manage user accounts
- Configuration: Adjust system-wide settings
Creating Your First Interview
Docassemble interviews are written in YAML with embedded Python. Here’s a simple example:
---metadata: title: Simple Intake Form short title: Intake---objects: - client: Individual---mandatory: Truecode: | client.name.first client.name.last client.email final_screen---question: | What is your first name?fields: - First Name: client.name.first---question: | What is your last name?fields: - Last Name: client.name.last---question: | What is your email address?fields: - Email: client.email datatype: email---event: final_screenquestion: | Thank you, ${ client.name.first }!subquestion: | We have received your information:
* Name: ${ client.name.full() } * Email: ${ client.email }
You will receive a confirmation at ${ client.email }.buttons: - Exit: exit - Restart: restartTo use this interview:
- Go to the Playground in the admin interface
- Create a new interview file
- Paste the YAML code above
- Click “Save and Run” to test your interview
- Follow the guided questions to see the interview in action
Understanding Interview Structure
Docassemble interviews consist of:
- Metadata: Title, description, and other interview information
- Objects: Define data structures (Individual, Organization, Document, etc.)
- Questions: Individual screens that collect information from users
- Code Blocks: Python logic for processing data and controlling flow
- Templates: Document templates for generating output (DOCX, PDF, etc.)
- Attachments: Files to be generated and sent to users
Sample Document Assembly Template
Create a simple DOCX template with variables:
Dear {{ client.name.first }} {{ client.name.last }},
Thank you for contacting us on {{ today() }}.
We have received your information and will respond to your inquiry sent from {{ client.email }} within 24 hours.
Sincerely,The TeamIn your interview YAML, reference this template:
---attachment: name: Confirmation Letter filename: confirmation_letter docx template file: confirmation_template.docx valid formats: - pdf - docxDatabase Configuration
Using the Embedded Database (Development)
For testing and development, Docassemble includes an embedded PostgreSQL database. This is automatically configured and requires no additional setup.
Note: The embedded database is suitable for testing but may not provide the performance and reliability needed for production deployments.
Using an External PostgreSQL Database (Production)
For production deployments, it’s recommended to use an external PostgreSQL database:
- Provision a PostgreSQL database (version 12 or higher recommended)
- Create a dedicated database and user for Docassemble
- Add the following environment variables in Klutch.sh:
DB_HOST=your-postgres-host.example.comDB_PORT=5432DB_NAME=docassembleDB_USER=docassemble_userDB_PASSWORD=your_secure_database_password- Redeploy your application for the changes to take effect
Security Tip: Use a strong, randomly-generated password for your database user and store it securely.
File Storage Configuration
Local File Storage (Default)
By default, Docassemble stores uploaded files and generated documents in the local filesystem within the persistent volume. This works well for single-instance deployments.
S3-Compatible Object Storage (Production)
For production deployments with multiple instances or high availability requirements, configure S3-compatible object storage:
- Create an S3 bucket (or compatible object storage)
- Create an access key with read/write permissions to the bucket
- Add the following environment variables in Klutch.sh:
S3ENABLE=trueS3BUCKET=your-docassemble-bucketS3ACCESSKEY=your_access_keyS3SECRETACCESSKEY=your_secret_access_keyS3REGION=us-east-1- Redeploy your application
This configuration allows multiple Docassemble instances to share the same file storage, enabling horizontal scaling.
Email Configuration
To enable email functionality for user notifications, password resets, and document delivery:
- Choose an SMTP provider (Gmail, SendGrid, AWS SES, etc.)
- Obtain SMTP credentials
- Add the following environment variables in Klutch.sh:
MAIL_SERVER=smtp.example.comMAIL_PORT=587MAIL_USERNAME=noreply@example.comMAIL_PASSWORD=your_email_passwordMAIL_USE_TLS=trueMAIL_DEFAULT_SENDER=noreply@example.com- Redeploy your application
Test email functionality by triggering a password reset or using the email functions in your interviews.
Security Best Practices
Authentication and Access Control
- Strong Admin Password: Use a complex, unique password for the admin account
- User Management: Create separate accounts for different users rather than sharing credentials
- Role-Based Access: Utilize Docassemble’s built-in role system to control access to interviews and admin features
- Two-Factor Authentication: Consider implementing 2FA for admin accounts (requires additional configuration)
Data Protection
- HTTPS Only: Always use HTTPS for production deployments (Klutch.sh provides this automatically)
- Encrypt Sensitive Data: Use Docassemble’s encryption features for sensitive interview data
- Regular Backups: Configure automatic backups of your persistent volumes
- Database Encryption: Enable encryption at rest for your PostgreSQL database
Network Security
- Firewall Rules: Restrict database access to only your Docassemble instance
- Private Networking: Use private networking between your app and database when possible
- Rate Limiting: Configure rate limiting in your interviews to prevent abuse
Regular Updates
- Update Base Image: Regularly update to the latest Docassemble Docker image for security patches
- Monitor Security Advisories: Subscribe to Docassemble security announcements
- Test Updates: Test updates in a staging environment before deploying to production
Monitoring and Troubleshooting
Accessing Logs
View application logs to troubleshoot issues:
- In the Klutch.sh dashboard, navigate to your Docassemble app
- Click on “Logs” to view real-time application logs
- Look for error messages, warnings, or performance issues
Common log locations within the container:
- Application logs:
/var/log/supervisor/ - Nginx logs:
/var/log/nginx/ - PostgreSQL logs:
/var/log/postgresql/
Common Issues and Solutions
Issue: Interview pages load slowly
- Solution: Increase compute resources (CPU and memory) in Klutch.sh
- Check database performance if using external PostgreSQL
- Review interview code for inefficient logic or large data processing
Issue: Uploaded files are lost after deployment
- Solution: Ensure persistent volumes are properly attached at the correct mount paths
- Verify volume permissions allow the application to write files
Issue: Database connection errors
- Solution: Verify database environment variables are correct
- Check network connectivity between app and database
- Ensure database credentials have proper permissions
Issue: Email functionality not working
- Solution: Verify SMTP configuration and credentials
- Check SMTP provider logs for rejected connections
- Test with a simple email function in the Playground
Performance Monitoring
Monitor these key metrics for optimal performance:
- CPU Usage: Should typically be below 70% during normal operation
- Memory Usage: Monitor for memory leaks in custom Python code
- Disk Usage: Track growth of file storage and database volumes
- Response Time: Monitor page load times and interview performance
- Database Connections: Watch for connection pool exhaustion
Health Checks
Docassemble includes a health check endpoint at /health_check that you can use to monitor application status.
Scaling and High Availability
Vertical Scaling
Increase resources for your Docassemble instance:
- In Klutch.sh dashboard, navigate to your app settings
- Increase CPU and memory allocation
- Redeploy the application
Recommended resources by usage:
- Small (1-50 users): 2 CPU, 4GB RAM
- Medium (50-200 users): 4 CPU, 8GB RAM
- Large (200+ users): 8+ CPU, 16GB+ RAM
Horizontal Scaling (Multiple Instances)
For high availability and load distribution:
- Configure external PostgreSQL database (required for multiple instances)
- Configure S3-compatible object storage (required for shared file access)
- Enable session stickiness in Klutch.sh load balancer
- Increase the number of instances in your app settings
- Deploy the changes
Note: Ensure both database and file storage are external before running multiple instances to avoid data inconsistencies.
Backup and Recovery
Automated Backups
Docassemble includes built-in backup functionality:
- The
/usr/share/docassemble/backupvolume stores regular backups - Configure backup schedule in the admin interface under Configuration
- Backups include interview data, user information, and configurations
Manual Backups
To manually backup your Docassemble instance:
- Access the admin interface at
/admin - Navigate to Configuration → Backup
- Click “Create Backup Now”
- Download the backup file to a secure location
Backup Best Practices
- Regular Schedule: Configure daily backups for production systems
- Off-Site Storage: Copy backups to external storage (S3, cloud storage)
- Test Restores: Periodically test backup restoration in a staging environment
- Retention Policy: Keep at least 30 days of backups for production systems
- Volume Snapshots: Use Klutch.sh volume snapshots as an additional backup layer
Recovery Process
To restore from a backup:
- Deploy a new Docassemble instance with the same configuration
- Access the admin interface
- Navigate to Configuration → Backup
- Upload your backup file
- Click “Restore from Backup”
- Wait for the restoration process to complete
- Verify that interviews, users, and data are restored correctly
Advanced Configuration
Custom Themes and Branding
Customize the appearance of your Docassemble instance:
- Access the admin interface
- Navigate to Configuration → Global Configuration
- Add custom CSS and branding elements:
---custom css: | .navbar-brand img { height: 50px; } .da-page-header { background-color: #1a73e8; }---site name: Your Organization Name---default icons: font awesome---brand logo: | https://example.com/logo.pngAPI Access
Enable and use the Docassemble API:
- In admin interface, navigate to Configuration → API
- Enable API access and generate API keys
- Use the API to programmatically:
- Start interview sessions
- Submit answers
- Retrieve generated documents
- Manage users
Example API usage with curl:
# Start a new interview sessioncurl -X POST https://example-app.klutch.sh/api/session/new \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{"i": "docassemble.interview:interview.yml"}'
# Submit answers to an interviewcurl -X POST https://example-app.klutch.sh/api/session/answer \ -H "X-API-Key: your-api-key" \ -H "Content-Type: application/json" \ -d '{ "session_id": "session-id", "variables": { "client.name.first": "John", "client.name.last": "Doe" } }'Multi-Tenancy
Configure Docassemble for multi-tenant deployments:
- Enable multi-tenancy in global configuration
- Create separate workspaces for different organizations
- Configure user isolation and data segregation
- Set up custom domains for each tenant (optional)
Integration Examples
Webhook Integration
Receive notifications when interviews are completed:
---code: | import requests
def send_webhook(data): webhook_url = "https://your-webhook-endpoint.com/callback" headers = {"Content-Type": "application/json"} response = requests.post(webhook_url, json=data, headers=headers) return response.status_code == 200---code: | if interview_complete: webhook_data = { "client_name": client.name.full(), "email": client.email, "completion_date": today() } send_webhook(webhook_data)External Database Lookup
Query external databases from your interviews:
---code: | import psycopg2
def lookup_case_info(case_number): conn = psycopg2.connect( host=os.environ.get('EXTERNAL_DB_HOST'), database=os.environ.get('EXTERNAL_DB_NAME'), user=os.environ.get('EXTERNAL_DB_USER'), password=os.environ.get('EXTERNAL_DB_PASSWORD') ) cursor = conn.cursor() cursor.execute("SELECT * FROM cases WHERE case_number = %s", (case_number,)) result = cursor.fetchone() conn.close() return result---question: | Case information foundsubquestion: | % if case_info: Case Number: ${ case_info[0] } Case Status: ${ case_info[1] } % endifUse Cases and Examples
Legal Document Automation
Docassemble is widely used for:
- Legal Aid Organizations: Automated intake forms, simple legal documents
- Court Systems: Self-service document preparation for pro se litigants
- Law Firms: Client intake, standard document generation
- Government Agencies: Benefits applications, permit requests
Common Interview Types
- Intake Forms: Collect client information systematically
- Legal Document Generators: Create contracts, wills, leases
- Court Forms: Complete jurisdiction-specific court forms
- Eligibility Screeners: Determine eligibility for services or benefits
- Data Collection: Surveys, assessments, and questionnaires
Example: Simple Contract Generator
A complete example of a basic contract generator:
---metadata: title: Simple Service Contract Generator---objects: - client: Individual - provider: Individual---mandatory: Truecode: | intro_screen client.name.first provider.name.first service_description payment_amount start_date contract_generated---question: | Welcome to the Service Contract Generatorsubquestion: | This interview will help you create a simple service contract.continue button field: intro_screen---question: | Client Informationfields: - First Name: client.name.first - Last Name: client.name.last - Email: client.email datatype: email---question: | Service Provider Informationfields: - First Name: provider.name.first - Last Name: provider.name.last - Business Name: provider.business_name required: False---question: | Describe the services to be providedfields: - Service Description: service_description input type: area---question: | Payment Detailsfields: - Payment Amount: payment_amount datatype: currency - Start Date: start_date datatype: date---event: contract_generatedquestion: | Your contract is readysubquestion: | Download your service contract below.attachment: name: Service Contract filename: service_contract content: | # SERVICE CONTRACT
This Service Contract is entered into on ${ today() }
**Client**: ${ client.name.full() } Email: ${ client.email }
**Service Provider**: ${ provider.name.full() } % if provider.business_name: Business: ${ provider.business_name } % endif
**Services**: ${ service_description }
**Compensation**: ${ currency(payment_amount) }
**Start Date**: ${ start_date }
The parties agree to the terms outlined above.
___________________________ Client Signature
___________________________ Provider SignatureResources and Documentation
Official Documentation
- Docassemble Official Website
- Docassemble Documentation
- Docassemble API Reference
- Playground Tutorial
Community Resources
Klutch.sh Resources
Learning Resources
Conclusion
Docassemble on Klutch.sh provides a powerful, scalable platform for building guided interviews and document assembly applications. Whether you’re automating legal documents, creating interactive questionnaires, or building complex expert systems, this deployment guide gives you everything you need to get started.
Remember to:
- Always use persistent volumes for production deployments
- Configure external PostgreSQL and S3 for high-availability setups
- Implement proper security measures including strong passwords and HTTPS
- Regularly backup your data and test restoration procedures
- Monitor resource usage and scale as needed
For additional support and advanced configurations, refer to the official Docassemble documentation and the Klutch.sh support resources listed above.