Skip to content

Deploying an AmuseWiki App

Introduction

AmuseWiki is an open-source wiki platform designed for creating and managing documentation, knowledge bases, and collaborative content. Built with Perl and the Mojolicious web framework, AmuseWiki provides a modern, feature-rich wiki solution with support for multiple markup languages, version control, and publishing workflows.

AmuseWiki is renowned for its:

  • Multiple Markup Languages: Support for Markdown, Textile, and AmuseWiki’s own markup
  • Version Control: Built-in version control for tracking document changes
  • Publishing Workflow: Flexible publishing and editorial workflow system
  • PDF Generation: Automatic PDF generation from wiki content
  • Search Functionality: Full-text search capabilities
  • User Management: Multi-user support with roles and permissions
  • Theming: Customizable themes and templates
  • API Access: RESTful API for programmatic access
  • Media Support: Support for images, attachments, and media files
  • SEO-Friendly: Built-in SEO features for better search engine visibility

Common use cases include documentation wikis, knowledge bases, technical documentation, collaborative writing platforms, content management systems, internal wikis, and publishing platforms.

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

Prerequisites

Before you begin, ensure you have the following:

  • A Klutch.sh account
  • A GitHub account with a repository for your AmuseWiki project
  • A MySQL, MariaDB, or PostgreSQL database (can be deployed separately on Klutch.sh or use SQLite for simpler setups)
  • Docker installed locally for testing (optional but recommended)
  • Basic understanding of Perl, web applications, and wiki systems

Installation and Setup

Step 1: Create Your Project Directory

First, create a new directory for your AmuseWiki deployment project:

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

Step 2: Clone or Prepare AmuseWiki Source

You can either clone the official AmuseWiki repository or use the official Docker image:

Terminal window
# Option 1: Clone the official AmuseWiki repository
git clone https://github.com/melmothx/amusewiki.git
cd amusewiki
# Option 2: Use the official AmuseWiki Docker image as base
# We'll create a custom Dockerfile based on the official image

Step 3: Create the Dockerfile

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

FROM perl:5.36-slim
# Install system dependencies
RUN apt-get update && apt-get install -y \
build-essential \
curl \
git \
libc6-dev \
libdb-dev \
libexpat1-dev \
libssl-dev \
libxml2-dev \
libxslt1-dev \
libyaml-dev \
zlib1g-dev \
texlive-latex-base \
texlive-latex-extra \
imagemagick \
poppler-utils \
&& rm -rf /var/lib/apt/lists/*
# Set working directory
WORKDIR /app
# Install cpanminus
RUN cpanm --notest App::cpanminus
# Copy cpanfile if it exists
COPY cpanfile* ./
# Install Perl dependencies
RUN if [ -f cpanfile ]; then cpanm --notest --installdeps .; fi
# Copy application files
COPY . .
# Create directories for persistent data
RUN mkdir -p /var/lib/amusewiki/repo \
/var/lib/amusewiki/root \
/var/lib/amusewiki/logs \
/var/lib/amusewiki/upload \
&& chmod -R 755 /var/lib/amusewiki
# Expose port
EXPOSE 8080
# Set environment variables
ENV AMW_HOSTNAME=example-app.klutch.sh
ENV AMW_ADMIN_EMAIL=admin@example.com
ENV AMW_DB_TYPE=sqlite
ENV AMW_PORT=8080
ENV AMW_HOME=/var/lib/amusewiki
# Health check
HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
CMD curl -f http://localhost:8080/ || exit 1
# Start the application
CMD ["hypnotoad", "-f", "script/amusewiki"]

Note: This Dockerfile uses Perl 5.36 with all necessary dependencies for AmuseWiki including LaTeX for PDF generation. AmuseWiki runs on port 8080 by default, which will be your internal port in Klutch.sh.

Step 4: Create Configuration File

Create an amusewiki.conf file with production configuration:

amusewiki.conf:

{
hypnotoad => {
listen => ['http://*:8080'],
workers => 4,
pid_file => '/var/lib/amusewiki/logs/hypnotoad.pid',
},
home => '/var/lib/amusewiki',
repo => '/var/lib/amusewiki/repo',
site => 'AmuseWiki',
canonical => 'https://example-app.klutch.sh',
mail => {
sendmail => '/usr/sbin/sendmail',
from => $ENV{AMW_ADMIN_EMAIL} || 'noreply@example.com',
},
db => {
type => $ENV{AMW_DB_TYPE} || 'sqlite',
database => $ENV{AMW_DB_NAME} || '/var/lib/amusewiki/amusewiki.db',
host => $ENV{DB_HOST} || 'localhost',
port => $ENV{DB_PORT} || 3306,
user => $ENV{DB_USER} || '',
password => $ENV{DB_PASSWORD} || '',
},
upload => {
allowed_extensions => [qw/pdf epub zip tar.gz tar.bz2/],
max_size => 50 * 1024 * 1024, # 50MB
},
}

Step 5: Create Environment Configuration Template

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

# Application Configuration
AMW_HOSTNAME=example-app.klutch.sh
AMW_ADMIN_EMAIL=admin@example.com
AMW_PORT=8080
AMW_HOME=/var/lib/amusewiki
# Database Configuration
# For SQLite (default)
AMW_DB_TYPE=sqlite
AMW_DB_NAME=/var/lib/amusewiki/amusewiki.db
# For MySQL/MariaDB
# AMW_DB_TYPE=mysql
# DB_HOST=your-mysql-host
# DB_PORT=3306
# DB_NAME=amusewiki
# DB_USER=amusewiki
# DB_PASSWORD=your-secure-password
# For PostgreSQL
# AMW_DB_TYPE=postgresql
# DB_HOST=your-postgresql-host
# DB_PORT=5432
# DB_NAME=amusewiki
# DB_USER=amusewiki
# DB_PASSWORD=your-secure-password
# Storage Paths
AMW_REPO_DIR=/var/lib/amusewiki/repo
AMW_ROOT_DIR=/var/lib/amusewiki/root
AMW_LOGS_DIR=/var/lib/amusewiki/logs
AMW_UPLOAD_DIR=/var/lib/amusewiki/upload
# Timezone
TZ=UTC

Step 6: Create Database Initialization Script

Create a script to initialize the database schema (for MySQL/PostgreSQL):

scripts/init_db.sh:

#!/bin/bash
set -e
if [ "$AMW_DB_TYPE" != "sqlite" ]; then
echo "Initializing AmuseWiki database..."
if [ "$AMW_DB_TYPE" = "mysql" ] || [ "$AMW_DB_TYPE" = "mariadb" ]; then
# Wait for MySQL/MariaDB to be ready
until mysqladmin ping -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASSWORD" --silent; do
>&2 echo "MySQL is unavailable - sleeping"
sleep 1
done
echo "MySQL is ready"
# Create database if it doesn't exist
mysql -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASSWORD" <<-EOSQL
CREATE DATABASE IF NOT EXISTS $DB_NAME;
GRANT ALL PRIVILEGES ON $DB_NAME.* TO '$DB_USER'@'%';
FLUSH PRIVILEGES;
EOSQL
elif [ "$AMW_DB_TYPE" = "postgresql" ]; then
# 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
fi
echo "Database initialization complete"
echo "AmuseWiki will create the schema automatically on first startup"
else
echo "Using SQLite database - no initialization needed"
fi

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

Step 8: Test Locally (Optional)

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

Terminal window
# Build the Docker image
docker build -t my-amusewiki .
# Run the container
docker run -d \
--name amusewiki-test \
-p 8080:8080 \
-e AMW_HOSTNAME=localhost \
-e AMW_ADMIN_EMAIL=admin@example.com \
-e AMW_DB_TYPE=sqlite \
-v $(pwd)/data:/var/lib/amusewiki \
my-amusewiki
# Check if the application is running
curl http://localhost:8080/

Note: For local development with a database, you can use Docker Compose to run both AmuseWiki and MySQL/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 AmuseWiki project files to your GitHub repository:

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

Deploying to Klutch.sh

Now that your AmuseWiki 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., “AmuseWiki Documentation”).

    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 (AmuseWiki is a web application)
      • Internal Port: Set to 8080 (the port your AmuseWiki container listens on, as defined in your Dockerfile)
    6. Set Environment Variables

      Add the following environment variables for your AmuseWiki configuration:

      Application Configuration:

      • AMW_HOSTNAME: Your Klutch.sh app URL (e.g., example-app.klutch.sh)
      • AMW_ADMIN_EMAIL: Admin email address
      • AMW_PORT: Set to 8080 (matches the internal port)
      • AMW_HOME: Set to /var/lib/amusewiki

      Database Configuration:

      For SQLite (Simplest):

      • AMW_DB_TYPE: Set to sqlite
      • AMW_DB_NAME: Set to /var/lib/amusewiki/amusewiki.db

      For MySQL/MariaDB:

      • AMW_DB_TYPE: Set to mysql
      • DB_HOST: Your database host (if using a Klutch.sh MySQL/MariaDB 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 3306 for MySQL/MariaDB)
      • DB_NAME: Your database name (e.g., amusewiki)
      • DB_USER: Database username
      • DB_PASSWORD: Database password

      For PostgreSQL:

      • AMW_DB_TYPE: Set to postgresql
      • 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., amusewiki)
      • DB_USER: Database username
      • DB_PASSWORD: Database password

      Storage Paths:

      • AMW_REPO_DIR: Set to /var/lib/amusewiki/repo
      • AMW_ROOT_DIR: Set to /var/lib/amusewiki/root
      • AMW_LOGS_DIR: Set to /var/lib/amusewiki/logs
      • AMW_UPLOAD_DIR: Set to /var/lib/amusewiki/upload

      Timezone:

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

      AmuseWiki requires persistent storage for several directories to ensure data persists across deployments:

      Main Data Volume:

      • Mount Path: /var/lib/amusewiki
      • Size: Start with 20GB minimum (50GB+ recommended for production with many documents and media files)

      This volume stores:

      • Wiki repository data
      • Document files
      • Database files (if using SQLite)
      • Configuration files
      • Uploaded files
      • Generated PDFs
      • Logs

      Note: For production instances with many documents and media files, 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: AmuseWiki has moderate resource requirements; 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 AmuseWiki container
      • Assign a URL for external access

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

    10. Complete Initial Setup

      Once deployment is complete, you’ll receive a URL like example-app.klutch.sh. Visit this URL to access your AmuseWiki instance and complete the initial setup:

      • Create admin account
      • Configure site settings
      • Set up your first wiki pages
      • Configure themes and templates
    11. Access Your Application

      After completing the setup, you can access your AmuseWiki instance at https://example-app.klutch.sh and start creating wiki content.


Sample Code: Getting Started with AmuseWiki

Here are some examples to help you interact with your AmuseWiki instance:

Example 1: JavaScript Client - Fetching Pages

// Frontend JavaScript example for AmuseWiki API
async function fetchPages() {
try {
const response = await fetch('https://example-app.klutch.sh/api/pages', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const pages = await response.json();
console.log('Pages:', pages);
return pages;
} catch (error) {
console.error('Error fetching pages:', error);
throw error;
}
}
// Display pages in the UI
async function displayPages() {
const pages = await fetchPages();
const container = document.getElementById('pages-container');
pages.forEach(page => {
const pageElement = document.createElement('div');
pageElement.innerHTML = `
<h3><a href="/page/${page.id}">${page.title}</a></h3>
<p>${page.summary || 'No summary available'}</p>
`;
container.appendChild(pageElement);
});
}

Example 2: Creating a Page

async function createPage(pageData) {
try {
const response = await fetch('https://example-app.klutch.sh/api/pages', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
body: JSON.stringify({
title: pageData.title,
content: pageData.content,
format: pageData.format || 'markdown'
})
});
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const newPage = await response.json();
console.log('Page created:', newPage);
return newPage;
} catch (error) {
console.error('Error creating page:', error);
throw error;
}
}
// Example usage
createPage({
title: 'Getting Started',
content: '# Getting Started\n\nWelcome to AmuseWiki!',
format: 'markdown'
});

Example 3: Python Client Example

import requests
import json
class AmuseWikiClient:
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_pages(self):
"""Get all pages"""
response = requests.get(
f'{self.base_url}/api/pages',
headers=self.headers
)
response.raise_for_status()
return response.json()
def get_page(self, page_id):
"""Get a specific page"""
response = requests.get(
f'{self.base_url}/api/pages/{page_id}',
headers=self.headers
)
response.raise_for_status()
return response.json()
def create_page(self, title, content, format='markdown'):
"""Create a new page"""
data = {
'title': title,
'content': content,
'format': format
}
response = requests.post(
f'{self.base_url}/api/pages',
headers=self.headers,
json=data
)
response.raise_for_status()
return response.json()
def search(self, query):
"""Search for pages"""
response = requests.get(
f'{self.base_url}/api/search',
headers=self.headers,
params={'q': query}
)
response.raise_for_status()
return response.json()
# Example usage
client = AmuseWikiClient('https://example-app.klutch.sh')
# Get pages
pages = client.get_pages()
print(f"Found {len(pages)} pages")
# Create a new page
new_page = client.create_page(
title='Python Example',
content='# Python Example\n\nThis page was created via the API.',
format='markdown'
)
print(f"Created page: {new_page['id']}")
# Search for pages
results = client.search('example')
print(f"Search results: {len(results)}")

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
  • Access Control: Implement proper user access control and permissions
  • Input Validation: Always validate and sanitize user input
  • File Upload Security: Implement proper file type validation for uploads
  • Regular Updates: Keep AmuseWiki and dependencies updated with security patches
  • Backup Strategy: Regularly backup your database and wiki data
  • Admin Account Security: Use strong passwords for admin accounts

Performance Optimization

  • Database Optimization: Regularly optimize database (if using MySQL/PostgreSQL)
  • Caching: Implement caching strategies for frequently accessed content
  • CDN Integration: Consider using a CDN for static assets
  • Resource Monitoring: Monitor CPU, memory, and storage usage
  • PDF Generation: Optimize PDF generation settings for better performance
  • Search Optimization: Configure search indexing for better performance

Wiki Management Best Practices

  • Content Organization: Organize content with proper structure and categories
  • Version Control: Use version control features to track changes
  • Backup Strategy: Implement regular backups of wiki content
  • User Management: Establish clear user roles and permissions
  • Content Review: Implement content review workflows
  • Media Management: Organize media files efficiently

Monitoring and Maintenance

Monitor your AmuseWiki application for:

  • Application Logs: Check logs in Klutch.sh dashboard for errors
  • Database Performance: Monitor query performance (if using MySQL/PostgreSQL)
  • 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 database (or SQLite file)
  • Backup Content: Backup wiki content from persistent volumes
  • Update Dependencies: Keep Perl dependencies updated
  • Review Logs: Review application and error logs regularly
  • Security Audits: Perform regular security audits
  • Database Maintenance: Regularly run database maintenance tasks (if using MySQL/PostgreSQL)
  • Content Cleanup: Clean up old versions and unused content

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 Perl application starts correctly (check the CMD in Dockerfile)
  • Verify all required Perl modules are installed

Database Connection Issues

  • Verify database environment variables are set correctly
  • For Klutch.sh database apps, use the app URL as the host and port 8000 externally
  • Check that the database is accessible from your AmuseWiki app
  • Verify database credentials and permissions
  • Ensure the database exists and is accessible
  • For SQLite, check file permissions on the database file

PDF Generation Issues

  • Verify LaTeX is installed and working
  • Check LaTeX package availability
  • Review PDF generation logs
  • Ensure sufficient resources for PDF generation
  • Check file permissions on output directories

Performance Issues

  • Review database query performance and add indexes if needed (for MySQL/PostgreSQL)
  • Check resource allocation in Klutch.sh (CPU and memory)
  • Review application logs for slow operations
  • Optimize PDF generation settings
  • Consider implementing caching

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

  • 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 AmuseWiki-specific details, see the official AmuseWiki Website
  • Learn about wiki management and documentation best practices

Conclusion

Deploying AmuseWiki to Klutch.sh with a Dockerfile provides a scalable, reliable wiki platform with persistent storage, automatic deployments, and production-ready configuration. By following this guide, you’ve set up a high-performance AmuseWiki instance with proper data persistence, security configurations, and the ability to create and manage wiki content.

AmuseWiki’s comprehensive wiki features, multiple markup language support, and publishing capabilities make it an excellent choice for documentation and knowledge management. Your application is now ready to create wiki pages, manage content, generate PDFs, and collaborate on documentation 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 content grows. With proper configuration, monitoring, and maintenance, AmuseWiki on Klutch.sh will provide a reliable, secure foundation for your wiki and documentation needs.