Skip to content

Deploying an Alf.io App

Introduction

Alf.io is an open-source event management and ticketing platform designed for organizing events, managing ticket sales, and handling attendee registration. Built with Java and Spring Boot, Alf.io provides a comprehensive solution for event organizers to create events, sell tickets, manage attendees, and generate reports.

Alf.io is renowned for its:

  • Event Management: Create and manage multiple events with detailed configurations
  • Ticket Sales: Flexible ticketing system with various pricing models and discounts
  • Payment Integration: Support for multiple payment gateways including Stripe, PayPal, and more
  • Attendee Management: Comprehensive attendee registration and check-in system
  • Reporting: Detailed reports on ticket sales, revenue, and attendance
  • Multi-Language Support: Internationalization for global events
  • Customization: Extensive customization options for branding and workflows
  • API Access: RESTful API for integration with other systems
  • Email Notifications: Automated email notifications for tickets and event updates
  • QR Code Support: QR code generation for ticket validation and check-in

Common use cases include conferences, workshops, meetups, webinars, concerts, festivals, corporate events, and any gathering requiring ticket sales and attendee management.

This comprehensive guide walks you through deploying Alf.io on Klutch.sh using a Dockerfile, including detailed installation steps, PostgreSQL database configuration, persistent storage setup, and production-ready best practices for hosting an event management platform.

Prerequisites

Before you begin, ensure you have the following:

  • A Klutch.sh account
  • A GitHub account with a repository for your Alf.io 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 Java, Spring Boot, and event management systems
  • Payment gateway account (Stripe, PayPal, etc.) for ticket sales

Installation and Setup

Step 1: Create Your Project Directory

First, create a new directory for your Alf.io deployment project:

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

Step 2: Clone or Prepare Alf.io Source

You can either clone the official Alf.io repository or prepare your own Alf.io-based application:

Terminal window
# Option 1: Clone the official Alf.io repository
git clone https://github.com/alfio-event/alf.io.git
cd alf.io
# Option 2: If you have your own Alf.io fork or custom instance
# Copy your Alf.io source code to the project directory

Step 3: Create the Dockerfile

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

# Build stage
FROM gradle:7.6-jdk17 AS builder
# Set working directory
WORKDIR /app
# Copy Gradle files
COPY build.gradle settings.gradle gradlew ./
COPY gradle ./gradle
# Copy source code
COPY src ./src
# Build the application
RUN ./gradlew bootWar --no-daemon
# Production stage
FROM eclipse-temurin:17-jre-alpine
# Install curl for health checks
RUN apk add --no-cache curl
# Create alfio user
RUN addgroup -g 1000 -S alfio && \
adduser -u 1000 -S alfio -G alfio
# Set working directory
WORKDIR /app
# Copy built WAR file from builder
COPY --from=builder --chown=alfio:alfio /app/build/libs/alfio-*.war ./alfio.war
# Create directories for persistent data
RUN mkdir -p /var/lib/alfio/data \
/var/lib/alfio/upload \
/var/lib/alfio/logs && \
chown -R alfio:alfio /var/lib/alfio
# Switch to alfio user
USER alfio
# Expose port
EXPOSE 8080
# Set environment variables
ENV JAVA_OPTS="-Xmx512m -Xms256m" \
SPRING_PROFILES_ACTIVE=prod \
SERVER_PORT=8080
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD curl -f http://localhost:8080/health || exit 1
# Start the application
ENTRYPOINT ["sh", "-c", "java $JAVA_OPTS -jar alfio.war"]

Note: This Dockerfile uses a multi-stage build to create an optimized production image. Alf.io runs on port 8080 by default, which will be your internal port in Klutch.sh. The application requires Java 17 and uses Spring Boot.

Step 4: Create Application Properties Template

Create an application.properties.example file with configuration options:

# Database Configuration
spring.datasource.url=jdbc:postgresql://${DB_HOST}:${DB_PORT}/${DB_NAME}
spring.datasource.username=${DB_USER}
spring.datasource.password=${DB_PASSWORD}
spring.datasource.driver-class-name=org.postgresql.Driver
# JPA/Hibernate Configuration
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=false
# Server Configuration
server.port=8080
server.servlet.context-path=/
# Application Configuration
alfio.base-url=${ALFIO_BASE_URL:https://example-app.klutch.sh}
alfio.name=${ALFIO_NAME:Alf.io}
alfio.support-email=${ALFIO_SUPPORT_EMAIL:support@example.com}
# File Upload Configuration
alfio.upload.dir=${ALFIO_UPLOAD_DIR:/var/lib/alfio/upload}
alfio.data.dir=${ALFIO_DATA_DIR:/var/lib/alfio/data}
# Email Configuration
spring.mail.host=${SMTP_HOST}
spring.mail.port=${SMTP_PORT:587}
spring.mail.username=${SMTP_USER}
spring.mail.password=${SMTP_PASSWORD}
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.starttls.required=true
spring.mail.from=${SMTP_FROM:noreply@example.com}
# Payment Configuration (Stripe)
stripe.public-key=${STRIPE_PUBLIC_KEY}
stripe.secret-key=${STRIPE_SECRET_KEY}
# Payment Configuration (PayPal)
paypal.client-id=${PAYPAL_CLIENT_ID}
paypal.client-secret=${PAYPAL_CLIENT_SECRET}
paypal.mode=${PAYPAL_MODE:sandbox}
# Security
spring.security.oauth2.client.registration.alfio.client-id=${OAUTH_CLIENT_ID}
spring.security.oauth2.client.registration.alfio.client-secret=${OAUTH_CLIENT_SECRET}
# Logging
logging.file.name=/var/lib/alfio/logs/alfio.log
logging.level.root=INFO
logging.level.org.alfio=INFO

Step 5: Create Environment Configuration Template

Create a .env.example file with required environment variables:

# Database Configuration
DB_HOST=your-postgresql-host
DB_PORT=5432
DB_NAME=alfio
DB_USER=alfio
DB_PASSWORD=your-secure-password
# Application Configuration
ALFIO_BASE_URL=https://example-app.klutch.sh
ALFIO_NAME=Alf.io Event Management
ALFIO_SUPPORT_EMAIL=support@example.com
# Storage Paths
ALFIO_UPLOAD_DIR=/var/lib/alfio/upload
ALFIO_DATA_DIR=/var/lib/alfio/data
# Email Configuration
SMTP_HOST=smtp.example.com
SMTP_PORT=587
SMTP_USER=your-smtp-username
SMTP_PASSWORD=your-smtp-password
SMTP_FROM=noreply@example.com
# Payment Configuration - Stripe
STRIPE_PUBLIC_KEY=your-stripe-public-key
STRIPE_SECRET_KEY=your-stripe-secret-key
# Payment Configuration - PayPal (Optional)
PAYPAL_CLIENT_ID=your-paypal-client-id
PAYPAL_CLIENT_SECRET=your-paypal-client-secret
PAYPAL_MODE=live
# OAuth Configuration (Optional)
OAUTH_CLIENT_ID=your-oauth-client-id
OAUTH_CLIENT_SECRET=your-oauth-client-secret
# Java Options
JAVA_OPTS=-Xmx512m -Xms256m
# Spring Profile
SPRING_PROFILES_ACTIVE=prod
# Timezone
TZ=UTC

Step 6: Create Database Initialization Script

Create a script to initialize the database schema:

scripts/init_db.sh:

#!/bin/bash
set -e
echo "Initializing Alf.io database..."
# Wait for PostgreSQL to be ready
until 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 1
done
echo "PostgreSQL is ready"
# Create database if it doesn't exist
PGPASSWORD=$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')\gexec
EOSQL
echo "Database initialization complete"
echo "Alf.io will create the schema automatically on first startup"

Step 7: Create .dockerignore File

Create a .dockerignore file to exclude unnecessary files from the Docker build:

.git
.gitignore
.dockerignore
.env
.env.local
*.md
docker-compose.yml
docker-compose.*.yml
Dockerfile
.gradle
build
.idea
*.iml

Step 8: Test Locally (Optional)

Before deploying to Klutch.sh, you can test your Alf.io setup locally:

Terminal window
# Build the Docker image
docker build -t my-alfio .
# Run the container (assuming you have a PostgreSQL database running)
docker run -d \
--name alfio-test \
-p 8080:8080 \
-e DB_HOST=host.docker.internal \
-e DB_PORT=5432 \
-e DB_NAME=alfio \
-e DB_USER=alfio \
-e DB_PASSWORD=password \
-e ALFIO_BASE_URL=http://localhost:8080 \
-e SMTP_HOST=smtp.example.com \
-e SMTP_USER=your-smtp-user \
-e SMTP_PASSWORD=your-smtp-password \
-v $(pwd)/data:/var/lib/alfio/data \
-v $(pwd)/upload:/var/lib/alfio/upload \
my-alfio
# Check if the application is running
curl http://localhost:8080/health

Note: For local development with a database, you can use Docker Compose to run both Alf.io and PostgreSQL together. Docker Compose is only for local development; Klutch.sh does not support Docker Compose for deployment.

Step 9: Push to GitHub

Commit your Alf.io project files to your GitHub repository:

Terminal window
git add .
git commit -m "Initial Alf.io Docker setup for Klutch.sh"
git branch -M main
git remote add origin https://github.com/yourusername/alfio-klutch.git
git push -u origin main

Deploying to Klutch.sh

Now that your Alf.io 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., “Alf.io Event Management”).

    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)

      Klutch.sh will automatically detect the Dockerfile in your repository root and use it for deployment.

    5. Configure Traffic Type

      • Traffic Type: Select HTTP (Alf.io is a web application)
      • Internal Port: Set to 8080 (the port your Alf.io container listens on, as defined in your Dockerfile)
    6. Set Environment Variables

      Add the following environment variables for your Alf.io configuration:

      Database Configuration:

      • DB_HOST: Your database host (if using a Klutch.sh PostgreSQL app, use the app URL like example-db.klutch.sh)
      • DB_PORT: Database port (for Klutch.sh TCP apps, use 8000 externally, but the internal port in your database app should be 5432 for PostgreSQL)
      • DB_NAME: Your database name (e.g., alfio)
      • DB_USER: Database username
      • DB_PASSWORD: Database password

      Application Configuration:

      • ALFIO_BASE_URL: Your Klutch.sh app URL (e.g., https://example-app.klutch.sh)
      • ALFIO_NAME: Your application name (e.g., My Event Management)
      • ALFIO_SUPPORT_EMAIL: Support email address

      Storage Paths:

      • ALFIO_UPLOAD_DIR: Set to /var/lib/alfio/upload
      • ALFIO_DATA_DIR: Set to /var/lib/alfio/data

      Email Configuration:

      • SMTP_HOST: Your SMTP server hostname
      • SMTP_PORT: SMTP port (typically 587)
      • SMTP_USER: SMTP username
      • SMTP_PASSWORD: SMTP password
      • SMTP_FROM: Default sender email address

      Payment Configuration - Stripe:

      • STRIPE_PUBLIC_KEY: Your Stripe public key
      • STRIPE_SECRET_KEY: Your Stripe secret key

      Payment Configuration - PayPal (Optional):

      • PAYPAL_CLIENT_ID: Your PayPal client ID
      • PAYPAL_CLIENT_SECRET: Your PayPal client secret
      • PAYPAL_MODE: Set to live for production or sandbox for testing

      Java Configuration:

      • JAVA_OPTS: Java runtime options (e.g., -Xmx512m -Xms256m)
      • SPRING_PROFILES_ACTIVE: Set to prod for production

      Timezone:

      • TZ: Your timezone (e.g., UTC or America/New_York)
    7. Attach Persistent Volumes

      Alf.io requires persistent storage for several directories to ensure data persists across deployments:

      Data Volume:

      • Mount Path: /var/lib/alfio/data
      • Size: Start with 10GB minimum (20GB+ recommended for production with event data)

      This volume stores:

      • Application data files
      • Configuration files
      • Event data

      Upload Volume:

      • Mount Path: /var/lib/alfio/upload
      • Size: Start with 20GB minimum (50GB+ recommended for production with file uploads)

      This volume stores:

      • Uploaded event images
      • User-uploaded files
      • Media files
      • Attachments

      Logs Volume (Optional):

      • Mount Path: /var/lib/alfio/logs
      • Size: 5GB (for application logs)

      Note: For production instances with many events and file uploads, allocate sufficient storage. You can increase volume sizes later if needed.

    8. Configure Additional Settings

      • Region: Select the region closest to your users for optimal performance
      • Compute Resources: Alf.io can be resource-intensive during high-traffic events; allocate at least:
        • CPU: 2+ cores recommended
        • Memory: 2GB minimum (4GB+ recommended for production workloads)
      • Instances: Start with 1 instance (you can scale horizontally later if needed)
    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
      • Attach the persistent volume(s)
      • Start your Alf.io container
      • Assign a URL for external access

      Note: The first deployment may take several minutes as it builds the Docker image, compiles the Java application, and installs dependencies.

    10. Initialize Database

      After deployment, Alf.io will automatically create the database schema on first startup. The application will run database migrations automatically when it starts.

    11. Access Your Application

      Once deployment is complete, you’ll receive a URL like example-app.klutch.sh. Visit this URL to access your Alf.io instance and complete the initial setup, including creating your admin account.


Sample Code: Getting Started with Alf.io

Here are some examples to help you interact with your Alf.io instance:

Example 1: JavaScript Client - API Authentication

// Frontend JavaScript example for Alf.io API
async function authenticateAlfio(username, password) {
try {
const response = await fetch('https://example-app.klutch.sh/api/v1/admin/login', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
username: username,
password: password
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const authData = await response.json();
console.log('Authentication successful:', authData);
return authData;
} catch (error) {
console.error('Error authenticating:', error);
throw error;
}
}

Example 2: Creating an Event

async function createEvent(apiToken, eventData) {
try {
const response = await fetch('https://example-app.klutch.sh/api/v1/admin/events', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${apiToken}`
},
body: JSON.stringify({
shortName: eventData.shortName,
displayName: eventData.displayName,
description: eventData.description,
location: eventData.location,
start: eventData.start,
end: eventData.end,
timeZone: eventData.timeZone || 'UTC',
websiteUrl: eventData.websiteUrl,
imageUrl: eventData.imageUrl
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const event = await response.json();
console.log('Event created:', event);
return event;
} catch (error) {
console.error('Error creating event:', error);
throw error;
}
}
// Example usage
createEvent('your-api-token', {
shortName: 'my-event-2024',
displayName: 'My Event 2024',
description: 'An amazing event',
location: 'Conference Center',
start: '2024-06-01T09:00:00Z',
end: '2024-06-01T17:00:00Z',
timeZone: 'UTC'
});

Example 3: Fetching Events

async function getEvents(apiToken) {
try {
const response = await fetch('https://example-app.klutch.sh/api/v1/admin/events', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'Authorization': `Bearer ${apiToken}`
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const events = await response.json();
console.log('Events:', events);
return events;
} catch (error) {
console.error('Error fetching events:', error);
throw error;
}
}

Example 4: Python Client Example

import requests
import json
class AlfioClient:
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 login(self, username, password):
"""Authenticate and get API token"""
response = requests.post(
f'{self.base_url}/api/v1/admin/login',
headers=self.headers,
json={'username': username, 'password': password}
)
response.raise_for_status()
data = response.json()
self.api_token = data.get('token')
self.headers['Authorization'] = f'Bearer {self.api_token}'
return data
def get_events(self):
"""Get all events"""
response = requests.get(
f'{self.base_url}/api/v1/admin/events',
headers=self.headers
)
response.raise_for_status()
return response.json()
def create_event(self, event_data):
"""Create a new event"""
response = requests.post(
f'{self.base_url}/api/v1/admin/events',
headers=self.headers,
json=event_data
)
response.raise_for_status()
return response.json()
def get_tickets(self, event_id):
"""Get tickets for an event"""
response = requests.get(
f'{self.base_url}/api/v1/admin/events/{event_id}/tickets',
headers=self.headers
)
response.raise_for_status()
return response.json()
# Example usage
client = AlfioClient('https://example-app.klutch.sh')
# Login
client.login('admin', 'password')
# Get events
events = client.get_events()
print(f"Found {len(events)} events")
# Create an event
new_event = client.create_event({
'shortName': 'python-event-2024',
'displayName': 'Python Event 2024',
'description': 'A Python conference',
'location': 'Virtual',
'start': '2024-06-01T09:00:00Z',
'end': '2024-06-01T17:00:00Z'
})
print(f"Created event: {new_event['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
  • Database Security: Use strong database passwords and enable SSL connections
  • Payment Security: Use secure payment gateway configurations and never expose secret keys
  • API Security: Use strong API tokens and rotate them regularly
  • Input Validation: Always validate and sanitize user input
  • Regular Updates: Keep Alf.io and dependencies updated with security patches
  • Backup Strategy: Regularly backup your database and uploaded files
  • Access Control: Implement proper access control for admin functions
  • Email Security: Use secure SMTP connections (TLS/SSL)

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 and media files
  • Resource Monitoring: Monitor CPU, memory, and storage usage
  • Load Balancing: Consider load balancing for high-traffic events
  • Database Indexing: Ensure proper database indexes for query performance

Event Management Best Practices

  • Event Planning: Plan events well in advance and configure settings early
  • Ticket Configuration: Set up ticket categories and pricing carefully
  • Payment Testing: Test payment integrations thoroughly before going live
  • Email Templates: Customize email templates for your brand
  • Reporting: Regularly review sales and attendance reports
  • Backup Strategy: Implement regular backups before and after major events
  • Monitoring: Monitor system performance during high-traffic ticket sales periods

Monitoring and Maintenance

Monitor your Alf.io 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
  • Payment Processing: Monitor payment gateway integration status

Regular maintenance tasks:

  • Backup Database: Regularly backup your PostgreSQL database
  • Backup Files: Backup uploaded files from persistent volumes
  • Update Dependencies: Keep Java dependencies updated
  • Review Logs: Review application and error logs regularly
  • Security Audits: Perform regular security audits
  • Database Maintenance: Regularly run database maintenance tasks
  • Storage Cleanup: Clean up old event data and files as needed

Troubleshooting

Application Not Loading

  • Verify the app’s Traffic Type is HTTP
  • Check that the internal port is set to 8080 and matches your Dockerfile
  • Review build and runtime logs in the Klutch.sh dashboard
  • Ensure the Java 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 8000 externally
  • Check that the database is accessible from your Alf.io app
  • Verify database credentials and permissions
  • Ensure the database exists and is accessible

Payment Integration Issues

  • Verify payment gateway credentials are correct
  • Check payment gateway API status
  • Review payment processing logs
  • Test payment flows in sandbox/test mode first
  • Verify webhook configurations if using webhooks

Email Not Sending

  • Verify SMTP configuration is correct
  • Check SMTP server connectivity
  • Review email sending logs
  • Test email configuration with a test email
  • Verify SMTP authentication credentials

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 increasing Java heap size if needed
  • Optimize database queries and connections

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


Conclusion

Deploying Alf.io to Klutch.sh with a Dockerfile provides a scalable, reliable event management and ticketing platform with persistent storage, automatic deployments, and production-ready configuration. By following this guide, you’ve set up a high-performance Alf.io instance with proper data persistence, security configurations, and the ability to handle ticket sales and event management.

Alf.io’s comprehensive event management features, flexible ticketing system, and payment integrations make it an excellent choice for organizing events of all sizes. Your application is now ready to create events, sell tickets, manage attendees, and generate reports 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 event volume grows. With proper configuration, monitoring, and maintenance, Alf.io on Klutch.sh will provide a reliable, secure foundation for your event management and ticketing needs.