Deploying an Ampache App
Introduction
Ampache is an open-source web-based audio and video streaming server that allows you to access your music and video collection from anywhere. Built with PHP and running on Apache, Ampache provides a comprehensive solution for organizing, streaming, and managing your media library with support for multiple clients and protocols.
Ampache is renowned for its:
- Music Streaming: Stream your music collection from anywhere with web-based access
- Video Support: Support for video files in addition to audio
- Multiple Clients: Support for various music clients including Subsonic, Plex, and more
- Web Interface: Intuitive web interface for browsing and managing your library
- Playlist Management: Create and manage playlists with ease
- User Management: Multi-user support with access control and permissions
- Catalog Management: Organize media with multiple catalogs and rules
- Transcoding: Automatic transcoding for different formats and bitrates
- API Access: RESTful API and XML-RPC API for integration
- Tag Support: Support for ID3 tags and metadata management
Common use cases include personal music streaming servers, family media libraries, music collection management, remote music access, multi-user music services, media organization, and music discovery platforms.
This comprehensive guide walks you through deploying Ampache on Klutch.sh using a Dockerfile, including detailed installation steps, MySQL/MariaDB database configuration, persistent storage setup, and production-ready best practices for hosting a music streaming server.
Prerequisites
Before you begin, ensure you have the following:
- A Klutch.sh account
- A GitHub account with a repository for your Ampache project
- A MySQL or MariaDB database (can be deployed separately on Klutch.sh or use an external database)
- Docker installed locally for testing (optional but recommended)
- Basic understanding of PHP, Apache, and media streaming
- Sufficient storage capacity for your music and video collection
Installation and Setup
Step 1: Create Your Project Directory
First, create a new directory for your Ampache deployment project:
mkdir ampache-klutchcd ampache-klutchgit initStep 2: Clone or Prepare Ampache Source
You can either clone the official Ampache repository or use the official Docker image:
# Option 1: Clone the official Ampache repositorygit clone https://github.com/ampache/ampache.gitcd ampache
# Option 2: Use the official Ampache Docker image as base# We'll create a custom Dockerfile based on the official imageStep 3: Create the Dockerfile
Create a Dockerfile in your project root directory. This will define your Ampache container configuration:
FROM php:8.2-apache
# Install system dependencies and PHP extensions required by AmpacheRUN apt-get update && apt-get install -y \ git \ curl \ libpng-dev \ libjpeg-dev \ libfreetype6-dev \ libzip-dev \ libicu-dev \ libonig-dev \ libxml2-dev \ libcurl4-openssl-dev \ libldap2-dev \ ffmpeg \ flac \ vorbis-tools \ imagemagick \ unzip \ zip \ && docker-php-ext-configure gd --with-freetype --with-jpeg \ && docker-php-ext-install -j$(nproc) \ pdo_mysql \ mysqli \ gd \ intl \ zip \ opcache \ mbstring \ xml \ curl \ ldap \ && rm -rf /var/lib/apt/lists/*
# Enable Apache modulesRUN a2enmod rewrite headers
# Set working directoryWORKDIR /var/www/html
# Download and install AmpacheARG AMPACHE_VERSION=6.0.0RUN curl -L "https://github.com/ampache/ampache/releases/download/${AMPACHE_VERSION}/ampache-${AMPACHE_VERSION}_all.zip" -o ampache.zip \ && unzip ampache.zip \ && mv ampache-${AMPACHE_VERSION}_all/* . \ && rm -rf ampache.zip ampache-${AMPACHE_VERSION}_all \ && chown -R www-data:www-data /var/www/html \ && chmod -R 755 /var/www/html
# Create directories for persistent dataRUN mkdir -p /var/lib/ampache/config \ /var/lib/ampache/art \ /var/lib/ampache/logs \ /var/lib/ampache/playlists \ /var/lib/ampache/upload \ && chown -R www-data:www-data /var/lib/ampache \ && chmod -R 755 /var/lib/ampache
# Configure PHP for productionRUN echo "memory_limit = 512M" > /usr/local/etc/php/conf.d/memory.ini && \ echo "upload_max_filesize = 100M" > /usr/local/etc/php/conf.d/uploads.ini && \ echo "post_max_size = 100M" >> /usr/local/etc/php/conf.d/uploads.ini && \ echo "max_execution_time = 300" > /usr/local/etc/php/conf.d/execution.ini
# Configure ApacheRUN echo '<VirtualHost *:8080>\n\ DocumentRoot /var/www/html\n\ <Directory /var/www/html>\n\ AllowOverride All\n\ Require all granted\n\ </Directory>\n\ ErrorLog ${APACHE_LOG_DIR}/error.log\n\ CustomLog ${APACHE_LOG_DIR}/access.log combined\n\</VirtualHost>' > /etc/apache2/sites-available/000-default.conf
# Change Apache port to 8080RUN sed -i 's/Listen 80/Listen 8080/' /etc/apache2/ports.conf
# Expose port 8080EXPOSE 8080
# Set environment variablesENV APACHE_DOCUMENT_ROOT=/var/www/htmlENV PHP_MEMORY_LIMIT=512M
# Health checkHEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \ CMD curl -f http://localhost:8080/ || exit 1
# Start ApacheCMD ["apache2-foreground"]Note: This Dockerfile uses PHP 8.2 with Apache and includes all necessary dependencies for Ampache including FFmpeg for transcoding. Ampache runs on port 8080, which will be your internal port in Klutch.sh.
Step 4: Create Configuration Template
Create an ampache.cfg.php.example file with configuration options:
ampache.cfg.php.example:
<?php// Ampache Configuration Template// Copy this to /var/lib/ampache/config/ampache.cfg.php and fill in your values
define('CONFIG_FILE', '/var/lib/ampache/config/ampache.cfg.php');
// Database Configuration$db_hostname = getenv('DB_HOST') ?: 'localhost';$db_port = getenv('DB_PORT') ?: 3306;$db_name = getenv('DB_NAME') ?: 'ampache';$db_username = getenv('DB_USER') ?: 'ampache';$db_password = getenv('DB_PASSWORD') ?: '';
// Application Configuration$web_path = getenv('AMPACHE_WEB_PATH') ?: '/';$local_web_path = getenv('AMPACHE_LOCAL_WEB_PATH') ?: 'https://example-app.klutch.sh';
// Paths$upload_dir = '/var/lib/ampache/upload';$art_dir = '/var/lib/ampache/art';$playlist_dir = '/var/lib/ampache/playlists';$log_dir = '/var/lib/ampache/logs';
// Music Catalog Path$catalog_path = getenv('AMPACHE_CATALOG_PATH') ?: '/var/lib/ampache/music';
// Security$secret_key = getenv('AMPACHE_SECRET_KEY') ?: 'change-this-in-production';
// Transcoding$transcode_music = getenv('AMPACHE_TRANSCODE') ?: 'true';$transcode_cmd = 'ffmpeg';Step 5: Create Environment Configuration Template
Create a .env.example file with required environment variables:
# Database ConfigurationDB_HOST=your-mysql-hostDB_PORT=3306DB_NAME=ampacheDB_USER=ampacheDB_PASSWORD=your-secure-password
# Application ConfigurationAMPACHE_WEB_PATH=/AMPACHE_LOCAL_WEB_PATH=https://example-app.klutch.shAMPACHE_SECRET_KEY=your-secret-key-here
# PathsAMPACHE_CATALOG_PATH=/var/lib/ampache/musicAMPACHE_UPLOAD_DIR=/var/lib/ampache/uploadAMPACHE_ART_DIR=/var/lib/ampache/artAMPACHE_PLAYLIST_DIR=/var/lib/ampache/playlistsAMPACHE_LOG_DIR=/var/lib/ampache/logs
# TranscodingAMPACHE_TRANSCODE=true
# PHP ConfigurationPHP_MEMORY_LIMIT=512M
# TimezoneTZ=UTCStep 6: Create Database Initialization Script
Create a script to initialize the database schema:
scripts/init_db.sh:
#!/bin/bashset -e
echo "Initializing Ampache database..."
# Wait for MySQL/MariaDB to be readyuntil mysqladmin ping -h "$DB_HOST" -P "$DB_PORT" -u "$DB_USER" -p"$DB_PASSWORD" --silent; do >&2 echo "MySQL is unavailable - sleeping" sleep 1done
echo "MySQL is ready"
# Create database if it doesn't existmysql -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
echo "Database initialization complete"echo "Ampache will create the schema automatically on first setup"Step 7: 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.*.ymlDockerfile*.zipStep 8: Test Locally (Optional)
Before deploying to Klutch.sh, you can test your Ampache setup locally:
# Build the Docker imagedocker build -t my-ampache .
# Run the container (assuming you have a MySQL database running)docker run -d \ --name ampache-test \ -p 8080:8080 \ -e DB_HOST=host.docker.internal \ -e DB_PORT=3306 \ -e DB_NAME=ampache \ -e DB_USER=ampache \ -e DB_PASSWORD=password \ -e AMPACHE_LOCAL_WEB_PATH=http://localhost:8080 \ -v $(pwd)/music:/var/lib/ampache/music \ -v $(pwd)/config:/var/lib/ampache/config \ my-ampache
# Check if the application is runningcurl http://localhost:8080/Note: For local development with a database, you can use Docker Compose to run both Ampache and MySQL together. Docker Compose is only for local development; Klutch.sh does not support Docker Compose for deployment.
Step 9: Push to GitHub
Commit your Ampache project files to your GitHub repository:
git add .git commit -m "Initial Ampache Docker setup for Klutch.sh"git branch -M maingit remote add origin https://github.com/yourusername/ampache-klutch.gitgit push -u origin mainDeploying to Klutch.sh
Now that your Ampache 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., “Ampache Music Server”).
-
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 (Ampache is a web application)
- Internal Port: Set to
8080(the port your Ampache container listens on, as defined in your Dockerfile)
-
Set Environment Variables
Add the following environment variables for your Ampache configuration:
Database Configuration:
DB_HOST: Your database host (if using a Klutch.sh MySQL/MariaDB 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 be3306for MySQL/MariaDB)DB_NAME: Your database name (e.g.,ampache)DB_USER: Database usernameDB_PASSWORD: Database password
Application Configuration:
AMPACHE_WEB_PATH: Set to/AMPACHE_LOCAL_WEB_PATH: Your Klutch.sh app URL (e.g.,https://example-app.klutch.sh)AMPACHE_SECRET_KEY: Generate usingopenssl rand -base64 32(a long random string)
Storage Paths:
AMPACHE_CATALOG_PATH: Set to/var/lib/ampache/musicAMPACHE_UPLOAD_DIR: Set to/var/lib/ampache/uploadAMPACHE_ART_DIR: Set to/var/lib/ampache/artAMPACHE_PLAYLIST_DIR: Set to/var/lib/ampache/playlistsAMPACHE_LOG_DIR: Set to/var/lib/ampache/logs
Transcoding:
AMPACHE_TRANSCODE: Set totrueto enable transcoding
PHP Configuration:
PHP_MEMORY_LIMIT: Set to512Mor higher for large libraries
Timezone:
TZ: Your timezone (e.g.,UTCorAmerica/New_York)
-
Attach Persistent Volumes
Ampache requires persistent storage for several directories to ensure data persists across deployments:
Music Catalog Volume:
- Mount Path:
/var/lib/ampache/music - Size: Start with 100GB minimum (500GB+ recommended for large music collections)
This volume stores:
- Your music and video files
- Media library content
- All media files
Art Volume:
- Mount Path:
/var/lib/ampache/art - Size: Start with 10GB minimum (50GB+ recommended for large libraries with album art)
This volume stores:
- Album artwork
- Artist images
- Media thumbnails
Config Volume:
- Mount Path:
/var/lib/ampache/config - Size: 1GB (for configuration files)
Playlists Volume (Optional):
- Mount Path:
/var/lib/ampache/playlists - Size: 5GB (for playlist data)
Upload Volume (Optional):
- Mount Path:
/var/lib/ampache/upload - Size: 10GB (for user uploads)
Logs Volume (Optional):
- Mount Path:
/var/lib/ampache/logs - Size: 10GB (for application logs)
Note: For production instances with large music collections, allocate sufficient storage. Music libraries can be very large, so plan storage capacity accordingly.
- Mount Path:
-
Configure Additional Settings
- Region: Select the region closest to your users for optimal performance
- Compute Resources: Ampache can be resource-intensive, especially for transcoding; allocate at least:
- CPU: 4+ cores recommended (8+ cores for production with transcoding)
- Memory: 2GB minimum (4GB+ recommended, 8GB+ for large libraries with transcoding)
- 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 Ampache container
- Assign a URL for external access
Note: The first deployment may take several minutes as it builds the Docker image, downloads Ampache, and sets up the application.
-
Complete Initial Setup
Once deployment is complete, you’ll receive a URL like
example-app.klutch.sh. Visit this URL to access your Ampache instance and complete the initial setup:- Configure database connection
- Set up your music catalog path
- Create admin account
- Configure transcoding settings
- Set up your media library
-
Access Your Application
After completing the setup, you can access your Ampache instance at
https://example-app.klutch.shand start managing your music library.
Sample Code: Getting Started with Ampache
Here are some examples to help you interact with your Ampache instance:
Example 1: JavaScript Client - API Authentication
// Frontend JavaScript example for Ampache API
async function authenticateAmpache(username, password) { try { const authString = btoa(`${username}:${password}`); const response = await fetch('https://example-app.klutch.sh/server/xml.server.php', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': `Basic ${authString}` }, body: 'action=handshake&auth=' + authString });
if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
const data = await response.text(); console.log('Authentication successful'); return data; } catch (error) { console.error('Error authenticating:', error); throw error; }}Example 2: Fetching Albums
async function getAlbums(authToken) { try { const response = await fetch( `https://example-app.klutch.sh/server/xml.server.php?action=albums&auth=${authToken}`, { method: 'GET', headers: { 'Content-Type': 'application/xml', 'Accept': 'application/xml' } } );
if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); }
const xml = await response.text(); console.log('Albums:', xml); return xml; } catch (error) { console.error('Error fetching albums:', error); throw error; }}Example 3: Python Client Example
import requestsimport base64import xml.etree.ElementTree as ET
class AmpacheClient: def __init__(self, base_url, username, password): self.base_url = base_url self.username = username self.password = password self.auth_token = None
def authenticate(self): """Authenticate and get API token""" auth_string = base64.b64encode(f'{self.username}:{self.password}'.encode()).decode()
response = requests.post( f'{self.base_url}/server/xml.server.php', headers={ 'Content-Type': 'application/x-www-form-urlencoded', 'Authorization': f'Basic {auth_string}' }, data=f'action=handshake&auth={auth_string}' ) response.raise_for_status()
# Parse XML response to get auth token root = ET.fromstring(response.text) self.auth_token = root.find('auth').text if root.find('auth') is not None else None return self.auth_token
def get_albums(self): """Get all albums""" if not self.auth_token: raise ValueError("Not authenticated. Call authenticate() first.")
response = requests.get( f'{self.base_url}/server/xml.server.php', params={'action': 'albums', 'auth': self.auth_token} ) response.raise_for_status() return response.text
def get_artists(self): """Get all artists""" if not self.auth_token: raise ValueError("Not authenticated. Call authenticate() first.")
response = requests.get( f'{self.base_url}/server/xml.server.php', params={'action': 'artists', 'auth': self.auth_token} ) response.raise_for_status() return response.text
def search(self, query): """Search for music""" if not self.auth_token: raise ValueError("Not authenticated. Call authenticate() first.")
response = requests.get( f'{self.base_url}/server/xml.server.php', params={'action': 'search', 'filter': query, 'auth': self.auth_token} ) response.raise_for_status() return response.text
# Example usageclient = AmpacheClient('https://example-app.klutch.sh', 'admin', 'password')
# Authenticateclient.authenticate()print("Authenticated successfully")
# Get albumsalbums = client.get_albums()print("Albums retrieved")
# Search for musicresults = client.search('rock')print("Search completed")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
AMPACHE_SECRET_KEYvalues using secure random generators - Database Security: Use strong database passwords and enable SSL connections
- Access Control: Implement proper user access control and permissions
- Regular Updates: Keep Ampache and dependencies updated with security patches
- Backup Strategy: Regularly backup your database and media files
- Input Validation: Always validate and sanitize user input
- File Upload Security: Implement proper file type validation for uploads
Performance Optimization
- Database Optimization: Regularly optimize MySQL/MariaDB database
- Transcoding Settings: Configure transcoding settings based on your needs
- Caching: Enable PHP opcache and configure appropriate caching
- CDN Integration: Consider using a CDN for static assets
- Resource Monitoring: Monitor CPU, memory, and storage usage
- Media Organization: Organize media files efficiently for better performance
- Index Optimization: Ensure proper database indexes for queries
Media Management Best Practices
- Storage Planning: Plan storage capacity based on your media collection size
- Backup Strategy: Implement regular backups of media files and database
- Catalog Organization: Organize media with proper folder structures
- Metadata Management: Maintain proper metadata for all media files
- Transcoding Configuration: Configure transcoding based on client needs
- Library Maintenance: Regularly update and maintain your media library
Monitoring and Maintenance
Monitor your Ampache 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
- Transcoding Performance: Monitor transcoding performance and resource usage
Regular maintenance tasks:
- Backup Database: Regularly backup your MySQL/MariaDB database
- Backup Media: Backup media files from persistent volumes
- Update Dependencies: Keep PHP and Ampache updated
- Review Logs: Review application and error logs regularly
- Security Audits: Perform regular security audits
- Database Maintenance: Regularly run database maintenance tasks
- Library Updates: Regularly update your media library catalog
Troubleshooting
Application Not Loading
- Verify the app’s Traffic Type is HTTP
- Check that the internal port is set to
8080and matches your Dockerfile - Review build and runtime logs in the Klutch.sh dashboard
- Ensure Apache starts correctly (check the CMD in Dockerfile)
- Verify all required PHP extensions are installed
Database Connection Issues
- Verify database environment variables are set correctly
- For Klutch.sh MySQL/MariaDB apps, use the app URL as the host and port
8000externally - Check that the database is accessible from your Ampache app
- Verify database credentials and permissions
- Ensure the database exists and is accessible
Media Not Playing
- Verify media files are in the correct catalog path
- Check file permissions on media files
- Review transcoding configuration
- Ensure FFmpeg is properly installed and configured
- Check media file formats are supported
Transcoding Issues
- Verify FFmpeg is installed and working
- Check transcoding settings in Ampache configuration
- Review resource allocation (CPU and memory)
- Check transcoding logs for errors
- Ensure sufficient resources for transcoding operations
Performance Issues
- Review database query performance and add indexes if needed
- Check resource allocation in Klutch.sh (CPU and memory)
- Monitor transcoding resource usage
- Review application logs for slow operations
- Optimize media catalog organization
- Consider increasing PHP memory limit
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 Ampache-specific details, see the official Ampache Website
- Learn about music streaming and media management best practices
Conclusion
Deploying Ampache to Klutch.sh with a Dockerfile provides a scalable, reliable music streaming server with persistent storage, automatic deployments, and production-ready configuration. By following this guide, you’ve set up a high-performance Ampache instance with proper data persistence, security configurations, and the ability to stream your music and video collection from anywhere.
Ampache’s comprehensive media management features, multi-client support, and transcoding capabilities make it an excellent choice for hosting your personal music streaming server. Your application is now ready to organize, stream, and manage your media library 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 media collection grows. With proper configuration, monitoring, and maintenance, Ampache on Klutch.sh will provide a reliable, secure foundation for your music streaming needs.