Skip to content

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:

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

Step 2: Create the Dockerfile

Create a Dockerfile in your project root directory. This will define your Docassemble container configuration:

# Use the official Docassemble image
FROM jhpyle/docassemble:latest
# Set environment variables for basic configuration
# These can be overridden in the Klutch.sh dashboard
ENV DAHOSTNAME=example-app.klutch.sh
ENV TIMEZONE=America/New_York
ENV LOCALE=en_US.UTF-8
# Docassemble uses port 80 internally
EXPOSE 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 image

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

Terminal window
# .env.example - Document your Docassemble configuration
# Do not commit actual secrets to git
# Hostname where Docassemble will be accessible
DAHOSTNAME=example-app.klutch.sh
# Timezone for the application
TIMEZONE=America/New_York
# Locale settings
LOCALE=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=false

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

Terminal window
git add Dockerfile .env.example README.md
git commit -m "Add Docassemble Dockerfile and configuration"
git remote add origin https://github.com/yourusername/docassemble-klutch.git
git push -u origin main

Deploying 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

    1. Log in to Klutch.sh

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

    2. Create a New Project

      Go to Create Project and give your project a meaningful name (e.g., “Docassemble Document Assembly”).

    3. Create a New App

      Navigate to Create App and configure the following settings:

    4. 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)
    5. 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)
    6. 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 to true (Klutch.sh provides HTTPS termination)
      • USEHTTPS: Set to false (since HTTPS is handled by Klutch.sh)
      • CONTAINERROLE: Set to admin for 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.

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

    8. 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)
    9. 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
    10. 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 /admin to configure interviews, templates, and users

Getting Started with Docassemble

Accessing the Admin Interface

After deploying, access the admin interface to configure your Docassemble instance:

  1. Navigate to https://example-app.klutch.sh/admin (replace with your actual URL)
  2. Log in with the admin credentials you created during setup
  3. 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: True
code: |
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_screen
question: |
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: restart

To use this interview:

  1. Go to the Playground in the admin interface
  2. Create a new interview file
  3. Paste the YAML code above
  4. Click “Save and Run” to test your interview
  5. 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 Team

In your interview YAML, reference this template:

---
attachment:
name: Confirmation Letter
filename: confirmation_letter
docx template file: confirmation_template.docx
valid formats:
- pdf
- docx

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

  1. Provision a PostgreSQL database (version 12 or higher recommended)
  2. Create a dedicated database and user for Docassemble
  3. Add the following environment variables in Klutch.sh:
Terminal window
DB_HOST=your-postgres-host.example.com
DB_PORT=5432
DB_NAME=docassemble
DB_USER=docassemble_user
DB_PASSWORD=your_secure_database_password
  1. 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:

  1. Create an S3 bucket (or compatible object storage)
  2. Create an access key with read/write permissions to the bucket
  3. Add the following environment variables in Klutch.sh:
Terminal window
S3ENABLE=true
S3BUCKET=your-docassemble-bucket
S3ACCESSKEY=your_access_key
S3SECRETACCESSKEY=your_secret_access_key
S3REGION=us-east-1
  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:

  1. Choose an SMTP provider (Gmail, SendGrid, AWS SES, etc.)
  2. Obtain SMTP credentials
  3. Add the following environment variables in Klutch.sh:
Terminal window
MAIL_SERVER=smtp.example.com
MAIL_PORT=587
MAIL_USERNAME=noreply@example.com
MAIL_PASSWORD=your_email_password
MAIL_USE_TLS=true
MAIL_DEFAULT_SENDER=noreply@example.com
  1. 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

  1. Strong Admin Password: Use a complex, unique password for the admin account
  2. User Management: Create separate accounts for different users rather than sharing credentials
  3. Role-Based Access: Utilize Docassemble’s built-in role system to control access to interviews and admin features
  4. Two-Factor Authentication: Consider implementing 2FA for admin accounts (requires additional configuration)

Data Protection

  1. HTTPS Only: Always use HTTPS for production deployments (Klutch.sh provides this automatically)
  2. Encrypt Sensitive Data: Use Docassemble’s encryption features for sensitive interview data
  3. Regular Backups: Configure automatic backups of your persistent volumes
  4. Database Encryption: Enable encryption at rest for your PostgreSQL database

Network Security

  1. Firewall Rules: Restrict database access to only your Docassemble instance
  2. Private Networking: Use private networking between your app and database when possible
  3. Rate Limiting: Configure rate limiting in your interviews to prevent abuse

Regular Updates

  1. Update Base Image: Regularly update to the latest Docassemble Docker image for security patches
  2. Monitor Security Advisories: Subscribe to Docassemble security announcements
  3. Test Updates: Test updates in a staging environment before deploying to production

Monitoring and Troubleshooting

Accessing Logs

View application logs to troubleshoot issues:

  1. In the Klutch.sh dashboard, navigate to your Docassemble app
  2. Click on “Logs” to view real-time application logs
  3. 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:

  1. In Klutch.sh dashboard, navigate to your app settings
  2. Increase CPU and memory allocation
  3. 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:

  1. Configure external PostgreSQL database (required for multiple instances)
  2. Configure S3-compatible object storage (required for shared file access)
  3. Enable session stickiness in Klutch.sh load balancer
  4. Increase the number of instances in your app settings
  5. 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:

  1. The /usr/share/docassemble/backup volume stores regular backups
  2. Configure backup schedule in the admin interface under Configuration
  3. Backups include interview data, user information, and configurations

Manual Backups

To manually backup your Docassemble instance:

  1. Access the admin interface at /admin
  2. Navigate to ConfigurationBackup
  3. Click “Create Backup Now”
  4. Download the backup file to a secure location

Backup Best Practices

  1. Regular Schedule: Configure daily backups for production systems
  2. Off-Site Storage: Copy backups to external storage (S3, cloud storage)
  3. Test Restores: Periodically test backup restoration in a staging environment
  4. Retention Policy: Keep at least 30 days of backups for production systems
  5. Volume Snapshots: Use Klutch.sh volume snapshots as an additional backup layer

Recovery Process

To restore from a backup:

  1. Deploy a new Docassemble instance with the same configuration
  2. Access the admin interface
  3. Navigate to ConfigurationBackup
  4. Upload your backup file
  5. Click “Restore from Backup”
  6. Wait for the restoration process to complete
  7. Verify that interviews, users, and data are restored correctly

Advanced Configuration

Custom Themes and Branding

Customize the appearance of your Docassemble instance:

  1. Access the admin interface
  2. Navigate to ConfigurationGlobal Configuration
  3. 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.png

API Access

Enable and use the Docassemble API:

  1. In admin interface, navigate to ConfigurationAPI
  2. Enable API access and generate API keys
  3. Use the API to programmatically:
    • Start interview sessions
    • Submit answers
    • Retrieve generated documents
    • Manage users

Example API usage with curl:

Terminal window
# Start a new interview session
curl -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 interview
curl -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:

  1. Enable multi-tenancy in global configuration
  2. Create separate workspaces for different organizations
  3. Configure user isolation and data segregation
  4. 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 found
subquestion: |
% if case_info:
Case Number: ${ case_info[0] }
Case Status: ${ case_info[1] }
% endif

Use Cases and Examples

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

  1. Intake Forms: Collect client information systematically
  2. Legal Document Generators: Create contracts, wills, leases
  3. Court Forms: Complete jurisdiction-specific court forms
  4. Eligibility Screeners: Determine eligibility for services or benefits
  5. 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: True
code: |
intro_screen
client.name.first
provider.name.first
service_description
payment_amount
start_date
contract_generated
---
question: |
Welcome to the Service Contract Generator
subquestion: |
This interview will help you create a simple service contract.
continue button field: intro_screen
---
question: |
Client Information
fields:
- First Name: client.name.first
- Last Name: client.name.last
- Email: client.email
datatype: email
---
question: |
Service Provider Information
fields:
- First Name: provider.name.first
- Last Name: provider.name.last
- Business Name: provider.business_name
required: False
---
question: |
Describe the services to be provided
fields:
- Service Description: service_description
input type: area
---
question: |
Payment Details
fields:
- Payment Amount: payment_amount
datatype: currency
- Start Date: start_date
datatype: date
---
event: contract_generated
question: |
Your contract is ready
subquestion: |
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 Signature

Resources and Documentation

Official Documentation

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.