Deploying a Corteza App
Introduction
Corteza is a powerful, open-source low-code platform that empowers organizations to build sophisticated business applications without extensive coding. It combines CRM capabilities, workflow automation, and a visual application builder to help teams streamline operations, manage customer relationships, and automate complex business processes.
What sets Corteza apart is its flexibility and developer-friendly approach. Rather than being confined to predefined workflows, you can design applications that match your business exactly. Build custom CRM systems, automate multi-step business processes, integrate data from multiple sources, and create applications without writing code.
Core Strengths of Corteza:
Low-Code Development: Build sophisticated applications through an intuitive visual interface. No coding required for basic functionality, with the ability to extend with custom code when needed. Drag-and-drop form builders, workflow composers, and data models make application development accessible to anyone.
Customer Relationship Management: Manage customer data, track interactions, and build lasting relationships. Built-in contact management, deal tracking, customer communication history, and sales pipeline management help your team stay organized and close more deals.
Workflow Automation: Automate repetitive tasks and complex multi-step processes. Define triggers and actions visually. Route approvals, send notifications, update records, and orchestrate workflows that connect your entire organization.
Data Integration: Connect and consolidate data from multiple sources. Corteza’s flexible data model and API make it easy to integrate with external systems and build a unified view of your business data.
Application Builder: Create custom business applications without code. Design forms, build views, set up permissions, and deploy applications in minutes. Perfect for managing unique business processes that off-the-shelf software doesn’t handle.
Case and Issue Management: Organize and track cases from creation through resolution. Assign ownership, track status, add detailed notes, and generate reports. Ideal for support teams, service desks, and issue management.
Multi-Tenant Architecture: Support multiple organizations or departments within a single deployment. Share infrastructure while maintaining complete data isolation and customization per tenant.
API-First Platform: Open, RESTful APIs for integration with any external system. Build custom integrations, connect to existing tools, and extend functionality through webhooks and API calls.
Role-Based Access Control: Granular permissions at the field, record, and module level. Build role hierarchies, set dynamic permissions, and maintain security and compliance requirements.
Extensibility: Customize virtually every aspect through plugins, custom fields, and code extensions. Modify workflows, create custom field types, build plugins, or integrate external systems.
Open Source: Community-driven development with no licensing restrictions. Audit the code, understand internals, and deploy with complete confidence and control.
Whether you’re a growing startup needing affordable CRM, an enterprise automating complex workflows, or a team building custom business applications, Corteza provides the flexibility and power to get the job done.
This guide walks you through deploying Corteza on Klutch.sh. You’ll learn how to set up a powerful low-code platform with persistent storage for your applications and data, configure authentication and security, establish external integrations, optimize performance, and troubleshoot common issues in production.
Prerequisites
Before deploying Corteza to Klutch.sh, ensure you have:
- A Klutch.sh account with dashboard access
- A GitHub account for repository hosting
- Docker installed locally for testing (optional but recommended)
- Basic understanding of low-code platforms and business application development
- Familiarity with database administration concepts
- Knowledge of workflow automation and automation rules
- A domain name for your Corteza instance (required for production use)
- Understanding of role-based access control and permissions
Understanding Corteza Architecture
Technology Stack
Corteza is built on modern, robust technologies designed for scalable business applications:
Core Platform:
- Go for the backend API server with high concurrency and performance
- Node.js/JavaScript for server-side processing and automation
- PostgreSQL for reliable, persistent data storage
- Redis for caching and session management
- Vue.js for dynamic, responsive user interfaces
Key Components:
- RESTful API gateway for all client communication
- Workflow automation engine for business process automation
- Low-code application builder for visual application development
- CRM module for customer relationship management
- Case management system for issue and ticket tracking
- Record/data management system with flexible schemas
- Authentication and authorization framework
- Integration hub for external system connections
Features:
- Real-time data synchronization across clients
- Multi-level role-based access control
- Multi-language support for global deployments
- Email integration for notifications and workflows
- Webhook support for external system integration
- Custom field types and data models
- Automation triggers and actions
- Data export and reporting capabilities
Core Components
API Server: Go-based API handling all business logic and data operations
Web Interface: Vue.js frontend providing intuitive user experience
Database: PostgreSQL for persistent storage of applications, records, workflows, and configurations
Cache Layer: Redis for session management, caching, and real-time updates
Message Queue: For asynchronous background job processing and email delivery
Workflow Engine: Processes automation rules, triggers, and actions
Application Builder: Visual interface for creating custom business applications
Integration Framework: Webhooks, APIs, and connectors for external system integration
Installation and Setup
Step 1: Create Your Project Directory
First, create a new directory for your Corteza deployment project:
mkdir corteza-klutchcd corteza-klutchgit initYour project structure will look like:
corteza-deployment/├── Dockerfile├── docker-entrypoint.sh├── .env.example├── .dockerignore├── .gitignore├── docker-compose.yml├── config/│ └── corteza.env├── data/│ └── (database files and uploads)└── logs/ └── (application logs)Step 2: Create the Dockerfile
# Base stage - using official Corteza imageFROM cortezaproject/corteza:2024.9-latest
# Set working directoryWORKDIR /corteza
# Install additional dependencies for production useRUN apk add --no-cache \ curl \ wget \ ca-certificates \ dumb-init \ bash \ postgresql-client
# Create a non-root user for securityRUN addgroup -g 1000 corteza && \ adduser -u 1000 -G corteza -s /sbin/nologin -D corteza && \ chown -R corteza:corteza /corteza
# Create necessary directories for persistent storageRUN mkdir -p /corteza/data /corteza/logs && \ chown -R corteza:corteza /corteza/data /corteza/logs
# Switch to non-root userUSER corteza
# Expose the HTTP portEXPOSE 80
# Health check to ensure Corteza is running and responsiveHEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \ CMD curl -f http://localhost:80/health || exit 1
# Use dumb-init to handle proper signal forwardingENTRYPOINT ["/usr/bin/dumb-init", "--"]
# The official image has the correct entrypoint configured# It will start the Corteza server automaticallyCMD [""]Note: This Dockerfile leverages the official Corteza image which includes all necessary components (server, workflows, and web applications) pre-configured and optimized for production use.
Step 3: Create Environment Configuration
Create a .env.example file with the necessary Corteza configuration for production use:
# Corteza Configuration
# Application SettingsCORTEZA_VERSION=2024.9.0CORTEZA_ENV=production
# Database ConfigurationDB_DSN=postgres://corteza:corteza_password@db:5432/corteza?sslmode=disableDB_AUTO_MIGRATE=true
# Server ConfigurationHTTP_ADDR=0.0.0.0:80API_BASE_URL=https://example-app.klutch.sh
# Authentication and SecurityAUTH_JWT_SECRET=your_super_secret_jwt_key_change_this_to_random_stringAUTH_SESSION_LIFETIME=24hAUTH_SESSION_PERM_LIFETIME=720hAUTH_SESSION_SECURE=trueAUTH_SESSION_SAMESITE=LaxCSRF_ENABLED=true
# Email ConfigurationSMTP_HOST=smtp.gmail.comSMTP_PORT=587SMTP_USERNAME=your-email@gmail.comSMTP_PASSWORD=your_app_passwordSMTP_FROM=noreply@example-app.klutch.shMAIL_DELIVERY=smtp
# Storage ConfigurationSTORAGE_PATH=/corteza/dataSTORAGE_ATTACHMENT_MAX_SIZE=26214400
# CORS and SecurityCORS_ALLOWED_ORIGINS=https://example-app.klutch.shCOOKIES_DOMAIN=example-app.klutch.sh
# External OAuth (optional)OAUTH_ENABLED=falseOAUTH_PROVIDER_URL=OAUTH_CLIENT_ID=OAUTH_CLIENT_SECRET=
# MonitoringMETRICS_ENABLED=trueMETRICS_PORT=8081Important: Never commit real credentials to your repository. This file documents the necessary environment variables for your deployment.
Step 4: Create Docker Entrypoint Script
Create a docker-entrypoint.sh script for initialization and health checks:
#!/bin/bashset -e
echo "Starting Corteza application..."
# Wait for database to be readyecho "Waiting for PostgreSQL..."until pg_isready -h ${DB_HOST:-db} -p ${DB_PORT:-5432} -U ${DB_USER:-corteza}; do echo "PostgreSQL is unavailable - sleeping..." sleep 2done
echo "PostgreSQL is up - continuing with application startup..."
# Start Cortezaecho "Starting Corteza server..."exec /corteza/bin/corteza serveStep 5: Create .dockerignore File
Create a .dockerignore file to keep your Docker image lean:
.git.gitignore.dockerignore.env.env.*node_modulesnpm-debug.logyarn-error.logREADME.md.vscode.idea*.logdistbuildcoverage.DS_StoreStep 6: Create .gitignore File
Create a .gitignore file to prevent committing sensitive information:
# Environment variables.env.env.local.env.*.local
# Dependenciesnode_modulesvendor
# Build artifactsdistbuildbin
# Database files*.db*.sqlite
# Logslogs*.lognpm-debug.log*yarn-error.log*
# IDE.vscode.idea*.swp*.swo
# OS.DS_StoreThumbs.db
# Data directoriesdata/uploads/var/temp/Step 7: Create Local Configuration File
Create a config/corteza.env file for local testing:
# Local Development ConfigurationCORTEZA_ENV=development
# Local Database (for Docker Compose testing)DB_DSN=postgres://corteza:corteza@db:5432/corteza?sslmode=disableDB_HOST=dbDB_PORT=5432DB_USER=cortezaDB_PASSWORD=corteza
# Local ServerAPI_BASE_URL=http://localhost:8000HTTP_ADDR=0.0.0.0:80
# Local Auth (less strict for development)AUTH_SESSION_SECURE=falseCORS_ALLOWED_ORIGINS=http://localhost:*Step 8: Create docker-compose.yml for Local Testing
Create a docker-compose.yml for local development:
version: '3.8'
services: db: image: postgres:16-alpine container_name: corteza-db environment: POSTGRES_USER: corteza POSTGRES_PASSWORD: corteza POSTGRES_DB: corteza ports: - "5432:5432" volumes: - db-data:/var/lib/postgresql/data healthcheck: test: ["CMD-SHELL", "pg_isready -U corteza"] interval: 10s timeout: 5s retries: 5
corteza: build: . container_name: corteza-app depends_on: db: condition: service_healthy environment: DB_DSN: postgres://corteza:corteza@db:5432/corteza?sslmode=disable AUTH_JWT_SECRET: dev-secret-change-in-production API_BASE_URL: http://localhost:8000 HTTP_ADDR: 0.0.0.0:80 ports: - "8000:80" volumes: - ./data:/corteza/data - ./logs:/corteza/logs healthcheck: test: ["CMD", "curl", "-f", "http://localhost/health"] interval: 30s timeout: 10s retries: 3 start_period: 40s
volumes: db-data:Step 9: Create package.json
Create a package.json for managing dependencies:
{ "name": "corteza-deployment", "version": "1.0.0", "description": "Corteza low-code platform deployment on Klutch.sh", "keywords": [ "corteza", "low-code", "crm", "workflow", "automation", "klutch" ], "author": "Your Name", "license": "ISC"}Step 10: Initialize Git Repository
Set up your Git repository for deployment:
git add .git commit -m "Initial Corteza deployment setup"git branch -M maingit remote add origin https://github.com/yourusername/corteza-deployment.gitgit push -u origin mainStep 11: Deploy to Klutch.sh
You’re ready to deploy. Follow these steps in the Klutch.sh dashboard:
Connecting to Corteza
Once deployed, Corteza is accessible via HTTPS at your assigned Klutch.sh URL with a web-based interface for building and managing your business applications.
Accessing the Web Interface
Navigate to your deployment URL:
https://example-app.klutch.shOn first access, complete the initial setup:
- Create your first admin user account
- Set up your organization
- Begin creating your business applications
Creating Your First Application
Corteza’s low-code builder makes it straightforward to create business applications:
// Example: Create a namespace (application container)const response = await fetch('https://example-app.klutch.sh/api/system/namespace', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer YOUR_AUTH_TOKEN' }, body: JSON.stringify({ name: "Customer Management", slug: "customer-management", enabled: true })});
const namespace = await response.json();console.log('Namespace created:', namespace);API Access Examples
Corteza provides comprehensive REST APIs for programmatic access:
JavaScript/Node.js - Fetching Records:
const fetch = require('node-fetch');
const CORTEZA_URL = 'https://example-app.klutch.sh';const API_TOKEN = 'your-api-token-here';
async function fetchRecords() { const response = await fetch(`${CORTEZA_URL}/api/compose/namespace/your-namespace/module/your-module/record/`, { headers: { 'Authorization': `Bearer ${API_TOKEN}`, 'Content-Type': 'application/json' } });
const data = await response.json(); console.log('Records retrieved:', data.set); return data;}
fetchRecords().catch(error => console.error('Error fetching records:', error));Python - Working with Records:
import requests
CORTEZA_URL = 'https://example-app.klutch.sh'API_TOKEN = 'your-api-token-here'
headers = { 'Authorization': f'Bearer {API_TOKEN}', 'Content-Type': 'application/json'}
# Fetch records from a moduleresponse = requests.get( f'{CORTEZA_URL}/api/compose/namespace/your-namespace/module/your-module/record/', headers=headers)
records = response.json()print(f'Found {len(records["set"])} records')
# Create a new recordnew_record = { "values": { "name": "John Doe", "email": "john@example.com" }}
create_response = requests.post( f'{CORTEZA_URL}/api/compose/namespace/your-namespace/module/your-module/record/', json=new_record, headers=headers)
print('Record created:', create_response.json())Go - API Integration:
package main
import ( "fmt" "io/ioutil" "net/http" "strings")
func main() { cortezaURL := "https://example-app.klutch.sh" apiToken := "your-api-token-here"
client := &http.Client{} req, _ := http.NewRequest("GET", cortezaURL+"/api/compose/namespace/your-namespace/module/your-module/record/", nil) req.Header.Add("Authorization", "Bearer "+apiToken) req.Header.Add("Content-Type", "application/json")
resp, err := client.Do(req) if err != nil { panic(err) } defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body) fmt.Println("Response:", string(body))}Setting Up Automation Workflows
Automate business processes without code:
// Example automation trigger for sending notifications{ "trigger": "record.create", "module": "contacts", "conditions": [ { "field": "status", "operator": "eq", "value": "VIP" } ], "actions": [ { "type": "send_email", "recipient": "sales@company.com", "subject": "New VIP Contact Created", "message": "Name: {{ record.name }}\nEmail: {{ record.email }}" }, { "type": "add_notification", "message": "VIP contact created: {{ record.name }}" } ]}Configuring Email Notifications
Set up SMTP for email notifications:
# Environment variables for emailSMTP_HOST=smtp.gmail.comSMTP_PORT=587SMTP_USERNAME=your-corteza@gmail.comSMTP_PASSWORD=your_app_specific_passwordSMTP_FROM=noreply@yourdomain.comSMTP_FROM_NAME=Your CompanyMAIL_DELIVERY=smtpDeploying to Klutch.sh
Now that your Corteza project is ready, deploy it on Klutch.sh with persistent storage:
- Log in to klutch.sh/app and access your dashboard
- Click "New" and select "Application" to create a new app deployment
- Choose GitHub as your git source and select your Corteza repository
- Select the main branch for automatic deployments
- Select HTTP as the traffic type (Corteza is a web application)
- Set the internal port to 80 (where Corteza listens)
- Add environment variables from your .env.example file:
- DB_DSN - PostgreSQL connection string
- AUTH_JWT_SECRET - Strong random secret for JWT token signing
- API_BASE_URL - Set to your domain (e.g., https://example-app.klutch.sh)
- SMTP_HOST, SMTP_PORT, SMTP_USERNAME, SMTP_PASSWORD - Email configuration
- AUTH_SESSION_LIFETIME - Session duration (e.g., 24h)
- Add persistent volumes for data persistence:
- Mount path: /corteza/data - Size: 50GB (for application data and uploads)
- Mount path: /corteza/logs - Size: 20GB (for application logs)
- Review your configuration and click "Deploy"
- Wait for the build and deployment to complete (typically 3-5 minutes)
- Access your Corteza instance at the provided URL
- Log in with your admin credentials and configure your organization
- Begin building applications and automating workflows
- Set up custom domain if desired by adding CNAME record
Performance Optimization
Database Optimization
Keep your PostgreSQL database performing well:
- Connection Pooling: Use pgBouncer for efficient connection management and resource utilization
- Index Creation: Create indexes on frequently filtered and searched fields
- Query Analysis: Use EXPLAIN to identify and optimize slow queries
- Regular Maintenance: Schedule vacuum and analyze operations for cleanup and statistics
- Query Caching: Cache frequently accessed queries with Redis
Caching Strategy
Redis caching significantly improves response times:
- Session Caching: Store user sessions in Redis for faster authentication
- Query Results: Cache frequently accessed data to reduce database load
- Module Definitions: Cache module metadata to avoid repeated lookups
- API Responses: Cache external API results to minimize integration delays
- Time to Live: Set appropriate TTL values based on data freshness requirements
Application Performance
Optimize Corteza operations:
- Pagination: Implement pagination for large record sets and list views
- Field Filtering: Select only needed fields in API calls to reduce data transfer
- Async Processing: Use background jobs for heavy operations and bulk updates
- Compression: Enable gzip compression for API responses
- Asset Delivery: Use CDN for static assets in high-traffic scenarios
Security Best Practices
Authentication and Authorization
Protect access to your Corteza instance:
- Strong Passwords: Enforce strong password requirements for all users
- Two-Factor Authentication: Enable 2FA for admin and sensitive accounts
- Role-Based Access: Implement granular role-based access control
- Session Management: Set appropriate session timeouts for security
- Audit Logging: Enable logging of sensitive operations and access patterns
Data Protection
Safeguard your business data:
- HTTPS Only: Always use HTTPS for all communication
- Encryption: Enable encryption for sensitive fields and data at rest
- Database Backups: Regular automated backups to prevent data loss
- Access Logs: Monitor and review access patterns regularly
- Data Retention: Implement appropriate data retention policies
API Security
Secure your API integrations:
- API Tokens: Use secure, unique tokens for API access
- Rate Limiting: Implement rate limits to prevent abuse
- CORS Configuration: Carefully configure allowed origins
- Input Validation: Validate all API input data
- TLS Certificates: Maintain valid SSL/TLS certificates
Troubleshooting
Application Won’t Start
If your Corteza instance isn’t starting:
- Check Logs: View deployment logs in Klutch.sh dashboard for error messages
- Database Connection: Verify PostgreSQL is running and accessible
- Environment Variables: Confirm all required variables are set correctly
- Port Configuration: Ensure port 80 is correctly configured
- Resource Limits: Check if memory or CPU limits are being exceeded
Solution: Review error logs and verify database credentials. Restart the container through the dashboard if needed.
Database Connection Errors
PostgreSQL connection issues prevent Corteza from functioning:
- Connection String: Verify the DSN format is correct
- Database Exists: Ensure the corteza database exists
- User Permissions: Verify the database user has appropriate permissions
- Network Access: Check that the container can reach the database
- Password Issues: Confirm special characters are properly escaped
Solution: Test the connection string from the container shell. Verify user permissions match the connection string.
Email Not Sending
Email notifications aren’t being delivered:
- SMTP Configuration: Verify SMTP host, port, and credentials
- App Passwords: Gmail requires app-specific passwords, not account passwords
- Firewall Rules: Check that outbound port 587 (SMTP) is allowed
- From Address: Ensure the from address matches SMTP configuration
- Email Logs: Check Corteza logs for email delivery errors
Solution: Test SMTP credentials manually. For Gmail, generate an app password in account settings. Verify the from address matches configuration.
Slow Application Performance
Slow response times affect user experience:
- Database Queries: Check for slow queries in PostgreSQL logs
- Memory Usage: Monitor Redis and application memory usage
- Connection Pool: Verify database connection pooling is configured
- Cache Hits: Monitor cache hit rates for effectiveness
- Record Volume: Large record sets may need pagination or filtering
Solution: Enable query logging to identify slow queries. Add indexes to frequently filtered fields. Increase cache TTL for stable data.
High Memory Usage
Corteza consuming excessive memory:
- Connection Leaks: Check for database connection leaks in logs
- Cache Growth: Monitor Redis memory usage and eviction
- Log Files: Large log files consume disk space
- Background Jobs: Long-running jobs may retain memory
- Record Size: Large records in memory during operations
Solution: Restart the application to clear memory. Implement log rotation. Monitor job queue sizes. Consider breaking large operations into smaller batches.
API Integration Failures
External system connections not working:
- Authentication: Verify API credentials and tokens haven’t expired
- Rate Limits: Check if external API rate limits are exceeded
- Network Access: Confirm outbound connectivity to external services
- Data Format: Ensure request/response formats match API specifications
- Error Responses: Check external API response codes and messages
Solution: Verify authentication tokens haven’t expired. Implement exponential backoff for retries. Check firewall rules for outbound access.
Custom Domain Setup
To use your own domain instead of the default example-app.klutch.sh URL:
Step 1: Add Domain in Klutch.sh
In the Klutch.sh dashboard, go to your application settings and add your custom domain.
Step 2: Create DNS CNAME Record
In your domain registrar’s DNS settings, create a CNAME record:
Domain: yourdomain.comType: CNAMEValue: example-app.klutch.shStep 3: Verify SSL Certificate
Klutch.sh automatically provisions SSL certificates. Verification typically completes within minutes.
Step 4: Update API Configuration
Update your Corteza environment variables with the custom domain:
API_BASE_URL=https://yourdomain.comCORS_ALLOWED_ORIGINS=https://yourdomain.comCOOKIES_DOMAIN=yourdomain.comSMTP_FROM=noreply@yourdomain.comRestart your application for changes to take effect.
Production Best Practices
Regular Backups
Protect your data with regular backup procedures:
- Automated Backups: Schedule daily database backups
- Backup Storage: Store backups in separate storage location
- Backup Testing: Periodically test backup restoration procedures
- Retention Policy: Keep backups for at least 30 days
- Disaster Recovery: Document and test recovery procedures
Monitoring and Alerts
Stay informed about system health:
- Uptime Monitoring: Use external monitoring services
- Error Tracking: Monitor application error rates
- Performance Metrics: Track response times and throughput
- Resource Monitoring: Alert on CPU and memory usage
- Log Aggregation: Centralize logs for easier troubleshooting
Scaling Considerations
As your usage grows, plan for scaling:
- Horizontal Scaling: Run multiple instances behind a load balancer
- Database Scaling: Consider read replicas for high read volumes
- Cache Optimization: Increase Redis memory for larger datasets
- Content Delivery: Use CDN for static assets
- Storage Growth: Plan for increasing persistent storage needs
Compliance and Security Maintenance
Keep your deployment secure:
- Regular Updates: Apply security patches promptly
- Dependency Updates: Keep dependencies current
- Access Reviews: Regularly review user permissions
- Compliance: Ensure compliance with applicable regulations
- Security Audits: Conduct periodic security reviews
Conclusion
Deploying Corteza on Klutch.sh provides a powerful, flexible low-code platform for building custom business applications. The combination of CRM capabilities, workflow automation, and visual application building makes Corteza ideal for organizations that need flexibility beyond off-the-shelf solutions.
For more information about Corteza, visit the Corteza Project website and the official Corteza documentation. Check out the Corteza GitHub repository for source code and community contributions.
Klutch.sh handles the infrastructure complexity, letting you focus on building applications and automating business processes. With persistent storage, automatic scaling, and integrated monitoring, you have everything needed for a production-ready deployment.
Start small with a basic CRM module, and expand with custom applications and automations as your organizational needs grow. The flexible architecture supports your organization’s evolution without migration headaches or architectural constraints.
Happy deploying!