Deploying an AliasVault App
Introduction
AliasVault is an open-source digital identity management platform designed for creating, managing, and organizing digital aliases and identities. Built with Node.js, AliasVault provides a secure and user-friendly solution for managing multiple online identities, email aliases, and digital personas while maintaining privacy and control.
AliasVault is renowned for its:
- Identity Management: Create and manage multiple digital identities and aliases
- Email Aliases: Generate and manage email aliases for privacy protection
- Privacy Protection: Protect your real identity while maintaining online presence
- Secure Storage: Encrypted storage for sensitive identity information
- User-Friendly Interface: Intuitive web interface for managing identities
- API Access: RESTful API for programmatic access and integration
- Multi-Identity Support: Manage multiple identities from a single platform
- Privacy Controls: Granular privacy controls for each identity
- Secure Authentication: Secure authentication and authorization
- Data Encryption: End-to-end encryption for sensitive data
Common use cases include privacy-focused identity management, email alias management, online persona management, digital identity protection, anonymous communication, privacy-conscious web services, and identity verification systems.
This comprehensive guide walks you through deploying AliasVault on Klutch.sh using a Dockerfile, including detailed installation steps, PostgreSQL database configuration, persistent storage setup, and production-ready best practices for hosting a digital identity management platform.
Prerequisites
Before you begin, ensure you have the following:
- A Klutch.sh account
- A GitHub account with a repository for your AliasVault project
- A PostgreSQL database (can be deployed separately on Klutch.sh or use an external database)
- Docker installed locally for testing (optional but recommended)
- Basic understanding of Node.js, databases, and identity management systems
Installation and Setup
Step 1: Create Your Project Directory
First, create a new directory for your AliasVault deployment project:
mkdir aliasvault-klutchcd aliasvault-klutchgit initStep 2: Clone or Prepare AliasVault Source
You can either clone the official AliasVault repository or prepare your own AliasVault-based application:
# Option 1: Clone the official AliasVault repositorygit clone https://github.com/aliasvault/aliasvault.gitcd aliasvault
# Option 2: If you have your own AliasVault fork or custom instance# Copy your AliasVault source code to the project directoryStep 3: Create the Dockerfile
Create a Dockerfile in your project root directory. This will define your AliasVault container configuration:
FROM node:18-alpine
# Install build dependenciesRUN apk add --no-cache \ python3 \ make \ g++ \ postgresql-client
# Set working directoryWORKDIR /app
# Copy package filesCOPY package*.json ./
# Install dependenciesRUN npm ci --only=production && npm cache clean --force
# Copy application filesCOPY . .
# Create directories for persistent dataRUN mkdir -p /var/lib/aliasvault/data \ /var/lib/aliasvault/uploads \ /var/lib/aliasvault/logs && \ chown -R node:node /var/lib/aliasvault
# Switch to non-root userUSER node
# Expose portEXPOSE 3000
# Set environment variablesENV NODE_ENV=productionENV PORT=3000
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=40s --retries=3 \ CMD node -e "require('http').get('http://localhost:3000/health', (r) => {process.exit(r.statusCode === 200 ? 0 : 1)})"
# Start the applicationCMD ["node", "server.js"]Note: This Dockerfile uses Node.js 18 Alpine for a lightweight container. AliasVault runs on port 3000 by default, which will be your internal port in Klutch.sh. The application requires PostgreSQL for data storage.
Step 4: Create Sample Application Code
If you’re creating a custom AliasVault application, here’s a basic example:
server.js (main application file):
const express = require('express');const { Pool } = require('pg');require('dotenv').config();
const app = express();const PORT = process.env.PORT || 3000;
// Middlewareapp.use(express.json());app.use(express.urlencoded({ extended: true }));
// Database connectionconst pool = new Pool({ host: process.env.DB_HOST, port: process.env.DB_PORT || 5432, database: process.env.DB_NAME, user: process.env.DB_USER, password: process.env.DB_PASSWORD, ssl: process.env.DB_SSL === 'true' ? { rejectUnauthorized: false } : false});
// Health check endpointapp.get('/health', async (req, res) => { try { await pool.query('SELECT 1'); res.json({ status: 'healthy', database: 'connected' }); } catch (error) { res.status(503).json({ status: 'unhealthy', error: error.message }); }});
// API endpoint to get aliasesapp.get('/api/aliases', async (req, res) => { try { const result = await pool.query( 'SELECT * FROM aliases ORDER BY created_at DESC LIMIT 100' ); res.json(result.rows); } catch (error) { console.error('Error fetching aliases:', error); res.status(500).json({ error: 'Failed to fetch aliases' }); }});
// API endpoint to create an aliasapp.post('/api/aliases', async (req, res) => { try { const { name, email, description } = req.body;
const result = await pool.query( `INSERT INTO aliases (name, email, description, created_at) VALUES ($1, $2, $3, NOW()) RETURNING *`, [name, email, description] );
res.status(201).json(result.rows[0]); } catch (error) { console.error('Error creating alias:', error); res.status(500).json({ error: 'Failed to create alias' }); }});
// Start serverapp.listen(PORT, '0.0.0.0', () => { console.log(`AliasVault server running on port ${PORT}`); console.log(`Environment: ${process.env.NODE_ENV || 'development'}`);});Step 5: Create Database Schema
Create a SQL file for initializing the database schema:
schema.sql:
-- Create aliases tableCREATE TABLE IF NOT EXISTS aliases ( id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255) UNIQUE NOT NULL, description TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
-- Create identities tableCREATE TABLE IF NOT EXISTS identities ( id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL, email VARCHAR(255), notes TEXT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
-- Create indexes for better query performanceCREATE INDEX IF NOT EXISTS idx_aliases_email ON aliases(email);CREATE INDEX IF NOT EXISTS idx_aliases_created ON aliases(created_at);CREATE INDEX IF NOT EXISTS idx_identities_email ON identities(email);Step 6: Create Environment Configuration Template
Create a .env.example file with required environment variables:
# Server ConfigurationNODE_ENV=productionPORT=3000
# Database ConfigurationDB_HOST=your-postgresql-hostDB_PORT=5432DB_NAME=aliasvaultDB_USER=aliasvaultDB_PASSWORD=your-secure-passwordDB_SSL=false
# Application ConfigurationAPP_NAME=AliasVaultAPP_URL=https://example-app.klutch.shSECRET_KEY_BASE=your-secret-key-base-here
# Storage PathsALIASVAULT_DATA_DIR=/var/lib/aliasvault/dataALIASVAULT_UPLOADS_DIR=/var/lib/aliasvault/uploadsALIASVAULT_LOGS_DIR=/var/lib/aliasvault/logs
# Email Configuration (Optional)SMTP_HOST=smtp.example.comSMTP_PORT=587SMTP_USER=your-smtp-usernameSMTP_PASSWORD=your-smtp-passwordSMTP_FROM=noreply@example.com
# TimezoneTZ=UTCStep 7: Create Database Initialization Script
Create a script to initialize the database schema:
scripts/init_db.sh:
#!/bin/bashset -e
echo "Initializing AliasVault database..."
# Wait for PostgreSQL to be readyuntil PGPASSWORD=$DB_PASSWORD psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres -c '\q'; do >&2 echo "PostgreSQL is unavailable - sleeping" sleep 1done
echo "PostgreSQL is ready"
# Create database if it doesn't existPGPASSWORD=$DB_PASSWORD psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d postgres <<-EOSQL SELECT 'CREATE DATABASE $DB_NAME' WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = '$DB_NAME')\gexecEOSQL
# Run schema initializationecho "Running database migrations..."PGPASSWORD=$DB_PASSWORD psql -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" -f /app/schema.sql || true
echo "Database initialization complete"Step 8: Create .dockerignore File
Create a .dockerignore file to exclude unnecessary files from the Docker build:
.git.gitignore.dockerignore.env.env.local*.mddocker-compose.ymldocker-compose.*.ymlDockerfilenode_modulesnpm-debug.logStep 9: Test Locally (Optional)
Before deploying to Klutch.sh, you can test your AliasVault setup locally:
# Build the Docker imagedocker build -t my-aliasvault .
# Run the container (assuming you have a PostgreSQL database running)docker run -d \ --name aliasvault-test \ -p 3000:3000 \ -e DB_HOST=host.docker.internal \ -e DB_PORT=5432 \ -e DB_NAME=aliasvault \ -e DB_USER=aliasvault \ -e DB_PASSWORD=password \ -e SECRET_KEY_BASE=$(openssl rand -base64 32) \ -v $(pwd)/data:/var/lib/aliasvault/data \ my-aliasvault
# Check if the application is runningcurl http://localhost:3000/healthNote: For local development with a database, you can use Docker Compose to run both AliasVault and PostgreSQL together. Docker Compose is only for local development; Klutch.sh does not support Docker Compose for deployment.
Step 10: Push to GitHub
Commit your AliasVault project files to your GitHub repository:
git add .git commit -m "Initial AliasVault Docker setup for Klutch.sh"git branch -M maingit remote add origin https://github.com/yourusername/aliasvault-klutch.gitgit push -u origin mainDeploying to Klutch.sh
Now that your AliasVault 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., “AliasVault Identity Management”).
-
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)
Klutch.sh will automatically detect the Dockerfile in your repository root and use it for deployment.
-
Configure Traffic Type
- Traffic Type: Select HTTP (AliasVault is a web application)
- Internal Port: Set to
3000(the port your AliasVault container listens on, as defined in your Dockerfile)
-
Set Environment Variables
Add the following environment variables for your AliasVault configuration:
Server Configuration:
NODE_ENV: Set toproductionPORT: Set to3000(matches the internal port)
Database Configuration:
DB_HOST: Your database host (if using a Klutch.sh PostgreSQL app, use the app URL likeexample-db.klutch.sh)DB_PORT: Database port (for Klutch.sh TCP apps, use8000externally, but the internal port in your database app should be5432for PostgreSQL)DB_NAME: Your database name (e.g.,aliasvault)DB_USER: Database usernameDB_PASSWORD: Database passwordDB_SSL: Set totrueif your database requires SSL connections
Application Configuration:
APP_NAME: Your application name (e.g.,AliasVault)APP_URL: Your Klutch.sh app URL (e.g.,https://example-app.klutch.sh)SECRET_KEY_BASE: Generate usingopenssl rand -base64 32(a long random string for encryption)
Storage Paths:
ALIASVAULT_DATA_DIR: Set to/var/lib/aliasvault/dataALIASVAULT_UPLOADS_DIR: Set to/var/lib/aliasvault/uploadsALIASVAULT_LOGS_DIR: Set to/var/lib/aliasvault/logs
Optional - Email Configuration:
SMTP_HOST: Your SMTP server hostnameSMTP_PORT: SMTP port (typically587)SMTP_USER: SMTP usernameSMTP_PASSWORD: SMTP passwordSMTP_FROM: Default sender email address
Timezone:
TZ: Your timezone (e.g.,UTCorAmerica/New_York)
-
Attach Persistent Volumes
AliasVault requires persistent storage for several directories to ensure data persists across deployments:
Data Volume:
- Mount Path:
/var/lib/aliasvault/data - Size: Start with 10GB minimum (20GB+ recommended for production with identity data)
This volume stores:
- Application data files
- Identity information
- Configuration files
- Encrypted data
Uploads Volume (Optional):
- Mount Path:
/var/lib/aliasvault/uploads - Size: 10GB (for user-uploaded files and attachments)
Logs Volume (Optional):
- Mount Path:
/var/lib/aliasvault/logs - Size: 5GB (for application logs)
Note: For production instances with many users and identities, allocate sufficient storage. You can increase volume sizes later if needed.
- Mount Path:
-
Configure Additional Settings
- Region: Select the region closest to your users for optimal performance
- Compute Resources: AliasVault has moderate resource requirements; allocate at least:
- CPU: 1-2 cores recommended
- Memory: 1GB minimum (2GB+ recommended for production workloads)
- Instances: Start with 1 instance (you can scale horizontally later if needed)
-
Deploy Your 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 volume(s)
- Start your AliasVault container
- Assign a URL for external access
Note: The first deployment may take several minutes as it builds the Docker image and installs dependencies.
-
Initialize Database
After deployment, you’ll need to initialize your AliasVault database. Connect to your PostgreSQL database and run the SQL schema from
schema.sql, or use a database migration tool if your AliasVault application includes one. -
Access Your Application
Once deployment is complete, you’ll receive a URL like
example-app.klutch.sh. Visit this URL to access your AliasVault instance and complete the initial setup, including creating your admin account.
Sample Code: Getting Started with AliasVault
Here are some examples to help you interact with your AliasVault instance:
Example 1: JavaScript Client - Fetching Aliases
// Frontend JavaScript example for AliasVault API
async function fetchAliases() { try { const response = await fetch('https://example-app.klutch.sh/api/aliases', { method: 'GET', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' } });
if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
const aliases = await response.json(); console.log('Aliases:', aliases); return aliases; } catch (error) { console.error('Error fetching aliases:', error); throw error; }}
// Display aliases in the UIasync function displayAliases() { const aliases = await fetchAliases(); const container = document.getElementById('aliases-container');
aliases.forEach(alias => { const aliasElement = document.createElement('div'); aliasElement.innerHTML = ` <h3>${alias.name}</h3> <p>Email: ${alias.email}</p> <p>Description: ${alias.description || 'No description'}</p> `; container.appendChild(aliasElement); });}Example 2: Creating an Alias
async function createAlias(aliasData) { try { const response = await fetch('https://example-app.klutch.sh/api/aliases', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, body: JSON.stringify({ name: aliasData.name, email: aliasData.email, description: aliasData.description }) });
if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
const newAlias = await response.json(); console.log('Alias created:', newAlias); return newAlias; } catch (error) { console.error('Error creating alias:', error); throw error; }}
// Example usagecreateAlias({ name: 'Work Alias', email: 'work@example.com', description: 'Alias for work-related communications'});Example 3: Python Client Example
import requestsimport json
class AliasVaultClient: def __init__(self, base_url, api_token=None): self.base_url = base_url self.api_token = api_token self.headers = { 'Content-Type': 'application/json', 'Accept': 'application/json' } if api_token: self.headers['Authorization'] = f'Bearer {api_token}'
def get_aliases(self): """Get all aliases""" response = requests.get( f'{self.base_url}/api/aliases', headers=self.headers ) response.raise_for_status() return response.json()
def create_alias(self, name, email, description=None): """Create a new alias""" data = { 'name': name, 'email': email } if description: data['description'] = description
response = requests.post( f'{self.base_url}/api/aliases', headers=self.headers, json=data ) response.raise_for_status() return response.json()
def get_health(self): """Get application health status""" response = requests.get( f'{self.base_url}/health', headers=self.headers ) response.raise_for_status() return response.json()
# Example usageclient = AliasVaultClient('https://example-app.klutch.sh')
# Get health statushealth = client.get_health()print(f"Status: {health['status']}")
# Get aliasesaliases = client.get_aliases()print(f"Found {len(aliases)} aliases")
# Create a new aliasnew_alias = client.create_alias( name='Personal Alias', email='personal@example.com', description='Personal email alias')print(f"Created alias: {new_alias['id']}")Production Best Practices
Security Recommendations
- Enable HTTPS: Always use HTTPS in production (Klutch.sh provides TLS certificates)
- Secure Environment Variables: Store all sensitive credentials as environment variables in Klutch.sh
- Strong Secrets: Generate strong
SECRET_KEY_BASEvalues using secure random generators - Database Security: Use strong database passwords and enable SSL connections
- Data Encryption: Ensure sensitive identity data is properly encrypted
- Input Validation: Always validate and sanitize user input
- Access Control: Implement proper access control and authentication
- Regular Updates: Keep AliasVault and dependencies updated with security patches
- Backup Strategy: Regularly backup your database and data volumes
- Audit Logging: Enable audit logging for security monitoring
Performance Optimization
- Database Optimization: Regularly optimize PostgreSQL database with VACUUM and ANALYZE
- Connection Pooling: Configure appropriate database connection pool sizes
- Caching: Implement caching strategies for frequently accessed data
- CDN Integration: Consider using a CDN for static assets
- Resource Monitoring: Monitor CPU, memory, and storage usage
- Query Optimization: Optimize database queries and add indexes
Identity Management Best Practices
- Data Privacy: Implement proper data privacy controls
- Encryption: Use encryption for sensitive identity information
- Access Control: Establish clear access control policies
- Backup Strategy: Implement regular backups of identity data
- Audit Trails: Maintain audit trails for identity access and changes
- Compliance: Ensure compliance with privacy regulations
Monitoring and Maintenance
Monitor your AliasVault application for:
- Application Logs: Check logs in Klutch.sh dashboard for errors
- Database Performance: Monitor query performance and slow queries
- Storage Usage: Monitor persistent volume usage and plan for growth
- Response Times: Track API response times
- Error Rates: Monitor 4xx and 5xx error rates
- Resource Usage: Track CPU and memory usage in Klutch.sh dashboard
Regular maintenance tasks:
- Backup Database: Regularly backup your PostgreSQL database
- Backup Data: Backup data files from persistent volumes
- Update Dependencies: Keep npm dependencies updated
- Review Logs: Review application and error logs regularly
- Security Audits: Perform regular security audits
- Database Maintenance: Regularly run database maintenance tasks
Troubleshooting
Application Not Loading
- Verify the app’s Traffic Type is HTTP
- Check that the internal port is set to
3000and matches your Dockerfile - Review build and runtime logs in the Klutch.sh dashboard
- Ensure the Node.js application starts correctly (check the CMD in Dockerfile)
- Verify all required environment variables are set
Database Connection Issues
- Verify database environment variables are set correctly
- For Klutch.sh PostgreSQL apps, use the app URL as the host and port
8000externally - Check that the database is accessible from your AliasVault app
- Verify database credentials and permissions
- Ensure the database schema has been initialized
Health Check Failing
- Verify the
/healthendpoint is accessible - Check database connectivity
- Review application logs for errors
- Ensure the database tables exist
Performance Issues
- Review database query performance and add indexes if needed
- Check resource allocation in Klutch.sh (CPU and memory)
- Monitor database connection pool usage
- Review application logs for slow operations
- Consider implementing caching for frequently accessed data
Data Not Persisting
- Ensure persistent volumes are correctly mounted
- Check file permissions on persistent volumes
- Verify the application is writing to the correct directories
- Ensure sufficient disk space in persistent volumes
Related Documentation
- Learn more about deploying applications on Klutch.sh in Deployments
- Understand traffic types, ports, and routing in Networking
- Explore how to work with storage in Volumes
- Browse the full platform documentation at Klutch.sh Documentation
- For AliasVault-specific details, see the official AliasVault Documentation
- Learn about digital identity management and privacy best practices
Conclusion
Deploying AliasVault to Klutch.sh with a Dockerfile provides a scalable, reliable digital identity management platform with persistent storage, automatic deployments, and production-ready configuration. By following this guide, you’ve set up a high-performance AliasVault instance with proper data persistence, security configurations, and the ability to manage digital identities and aliases.
AliasVault’s comprehensive identity management features, privacy protection, and user-friendly interface make it an excellent choice for managing digital identities. Your application is now ready to create and manage aliases, protect user privacy, and provide secure identity management while maintaining security and performance.
Remember to follow the production best practices outlined in this guide, regularly monitor your application performance, and adjust resources as your user base grows. With proper configuration, monitoring, and maintenance, AliasVault on Klutch.sh will provide a reliable, secure foundation for your digital identity management needs.