Skip to content
Author Nejat Hakan
eMail nejat.hakan@outlook.de
PayPal Me https://paypal.me/nejathakan


Music Streaming Server Ampache

Introduction to Ampache and Music Streaming

Welcome to the world of self-hosted music streaming with Ampache! In an era where streaming services dominate how we consume music, taking control of your own collection offers unique advantages in terms of ownership, privacy, flexibility, and cost. Ampache stands out as a mature, open-source, web-based audio and video streaming application and file manager that allows you to access your music and videos from anywhere, using almost any internet-enabled device. This section introduces Ampache, explores the motivations behind self-hosting your media, and clarifies the fundamental concepts you'll encounter.

What is Ampache?

Ampache is essentially your personal music (and video) cloud. Imagine having your entire digital music library, meticulously organized over the years, accessible through a web browser or dedicated mobile apps, just like Spotify or Apple Music, but running entirely on your own server.

At its core, Ampache performs several key functions:

  1. Cataloging: It scans designated directories on your server containing your media files (MP3, FLAC, Ogg Vorbis, AAC, Opus, etc.). It reads the metadata (tags) embedded within these files – artist, album, title, genre, year, track number, album art – and builds a structured database, often referred to as a "catalog." This database allows for efficient searching, browsing, and organization.
  2. Streaming: Ampache serves these media files over the network (your local network or the internet) to various clients. It can stream the original files directly or transcode them on-the-fly into different formats or bitrates. Transcoding is crucial for compatibility with specific devices or for reducing bandwidth usage when streaming over slower connections (like mobile data).
  3. Web Interface: It provides a comprehensive web-based user interface accessible through any modern browser. This interface allows users to browse their library, manage playlists, control playback, administer the server (if they have permissions), and manage user accounts.
  4. API Access: Ampache implements APIs, most notably the widely supported Subsonic API. This allows a vast ecosystem of third-party mobile apps (like DSub, Substreamer, play:Sub) and desktop clients (like Clementine, Supersonic) to connect to your Ampache server, providing native app experiences on different platforms.

Ampache is highly extensible and configurable, supporting multiple users, detailed permissions, themes, and various authentication methods. It's built primarily using PHP and typically relies on a standard web server (like Apache or Nginx) and a database backend (like MySQL/MariaDB or PostgreSQL) – the common components of a LAMP (Linux, Apache, MySQL, PHP) or LEMP (Linux, Nginx, MySQL, PHP) stack.

Why Self-Host Your Music?

In a world saturated with commercial streaming services, why bother setting up your own? The motivations are compelling, especially for enthusiasts, collectors, and privacy-conscious individuals:

  • Ownership and Control: Your music library is yours. Commercial services license music, and tracks can disappear from their catalogs due to licensing disputes or changing business strategies. With self-hosting, if you own the file, you control its availability. You decide what stays, what goes, and how it's organized.
  • Privacy: Commercial services track your listening habits extensively for recommendations, advertising, and data analysis. Self-hosting Ampache on your server keeps your listening data private and under your control. No third party is monitoring what, when, and where you listen.
  • Audio Quality: Many audiophiles prefer lossless formats like FLAC or ALAC, which are often not available or are offered at a premium tier on commercial services. Ampache handles these formats natively and can stream them directly (if bandwidth and client support allow) or transcode them losslessly or lossily as needed. You control the quality.
  • Cost-Effectiveness: While there's an initial investment in hardware (if you don't already have a server) and time for setup, there are no recurring subscription fees. Over the long term, especially if you already have a significant digital music collection, self-hosting can be more economical.
  • Customization and Flexibility: Ampache offers extensive configuration options. You can tailor transcoding settings, user permissions, interface themes, and integrate it with other services. Commercial platforms offer limited customization.
  • Access to Niche/Obscure Content: Your personal library might include bootlegs, live recordings, DJ mixes, or independent artists not available on commercial platforms. Ampache makes your entire collection streamable.
  • Learning Experience: Setting up and managing a server like Ampache is a fantastic way to learn about Linux, web servers, databases, networking, security, and media encoding – valuable skills in many technical fields.

Core Concepts

Understanding these terms is fundamental to working effectively with Ampache:

  • Server: This is the computer (physical or virtual) where Ampache software is installed and running. It hosts the Ampache application itself, the web server (Apache/Nginx), the PHP interpreter, the database (MySQL/MariaDB), and crucially, the storage location for your music files. It needs to be powered on and connected to the network for streaming to work.
  • Client: This is any application or device that connects to the Ampache server to browse the library and play music. Examples include:
    • Web Browser: Accessing the Ampache web interface directly (e.g., http://your-server-ip:port).
    • Mobile Apps: DSub (Android), Substreamer (iOS/Android), play:Sub (iOS), etc., connecting via the Subsonic API.
    • Desktop Apps: Clementine, Supersonic, Submariner (macOS), etc., also typically using the Subsonic API.
    • Media Players with UPnP/DLNA Support: While Ampache's core focus is its own protocol and the Subsonic API, some integrations might allow connections via DLNA, though this is less common for primary usage.
  • Catalog: In Ampache terminology, a catalog represents a source of media files. It's essentially a definition within Ampache that points to a specific directory (folder) on the server's filesystem where your music files are stored. Ampache scans the files within the path defined by the catalog to build its database. You can have multiple catalogs (e.g., one for MP3s, one for FLACs, one for audiobooks) if desired.
  • Transcoding: This is the process of converting audio (or video) files from one format or bitrate to another on-the-fly during streaming. Ampache uses external tools like ffmpeg to perform transcoding.
    • Why Transcode?
      • Bandwidth Conservation: Converting a large FLAC file (e.g., 30MB) to a lower-bitrate MP3 (e.g., 3MB) significantly reduces data usage, essential for mobile streaming or slower internet connections.
      • Device Compatibility: Some devices or players might not support certain formats (e.g., Opus or Ogg Vorbis). Transcoding can convert these to a widely supported format like MP3 or AAC.
      • Container/Codec Issues: Sometimes the container format (like MKV for videos) or specific codec needs changing for playback.
    • Downsides: Transcoding consumes CPU resources on the server. Heavy transcoding for multiple simultaneous users can strain server performance. It can also potentially reduce audio quality if converting from a lossless to a lossy format. Direct streaming (no transcoding) is preferred when bandwidth and client compatibility permit.

With these foundational concepts understood, you are ready to embark on the practical journey of setting up your own Ampache server.

1. Basic Ampache Setup

This section guides you through the initial steps of getting Ampache up and running. We'll cover the necessary prerequisites, discuss different installation approaches, walk through the first-time configuration wizard, and create your first music catalog so Ampache knows where to find your tunes. Our focus here is on getting a functional instance running, laying the groundwork for more advanced configurations later.

Prerequisites (Server OS, LAMP/LEMP Stack Basics)

Before installing Ampache, you need a server environment ready to host it. Ampache is flexible, but a typical setup involves:

  1. Server Operating System:

    • Linux: Highly recommended. Distributions like Debian, Ubuntu, CentOS, Fedora, or Arch Linux are common choices. Linux offers stability, performance, security, and excellent compatibility with the required software components. Most tutorials and community support focus on Linux. This guide will assume a Debian-based system (like Debian or Ubuntu) for specific commands, but the concepts apply broadly.
    • Windows/macOS: While possible (often using tools like XAMPP/WAMP/MAMP or Docker), deployment on these platforms is less common for dedicated self-hosting and may present unique challenges. We will focus on Linux.
    • Hardware: A Raspberry Pi (3B+ or later) can run Ampache for personal use, but performance (especially with transcoding) will be limited. For multiple users or transcoding, a system with at least 2 CPU cores and 2GB+ RAM is advisable. Disk space depends entirely on the size of your music library.
  2. Web Server: Ampache needs a web server to handle incoming HTTP(S) requests from clients (browsers, apps).

    • Apache (httpd): A veteran, highly configurable web server. Often used with mod_php.
    • Nginx (nginx): A modern, high-performance web server known for its efficiency, especially with concurrent connections. Typically used with PHP-FPM (FastCGI Process Manager).
    • Others (Lighttpd, Caddy): Also possible, but Apache and Nginx have the most extensive documentation and community support regarding Ampache.
  3. PHP: Ampache is written in PHP. You'll need PHP installed along with several specific extensions.

    • Version: Check the Ampache documentation for the recommended PHP version (e.g., PHP 7.4, 8.0, 8.1, or 8.2). Requirements change with Ampache versions.
    • Required Extensions: Common requirements include pdo_mysql (or pdo_pgsql for PostgreSQL), gd (for image processing like album art resizing), curl (for fetching external data), json, xml, intl, mbstring, and potentially others depending on features you intend to use (like ldap for LDAP authentication).
  4. Database Server: Ampache stores its catalog metadata, user information, playlists, and settings in a relational database.

    • MySQL/MariaDB: Most commonly used with Ampache. MariaDB is a community-developed fork of MySQL and is generally recommended.
    • PostgreSQL: Also supported, though less common in typical Ampache setups.
  5. Media Processing Tools (Optional but Recommended for Full Functionality):

    • ffmpeg: Essential for transcoding audio and video files. Without it, Ampache can only stream original files, limiting compatibility and bandwidth options.

LAMP/LEMP Stack: These prerequisites collectively form a standard web service stack:

  • LAMP: Linux + Apache + MySQL/MariaDB + PHP
  • LEMP: Linux + Nginx (pronounced "Engine-X") + MySQL/MariaDB + PHP(-FPM)

You typically install these components using your Linux distribution's package manager (e.g., apt for Debian/Ubuntu, yum/dnf for CentOS/Fedora).

Installation Methods (Package Manager vs. Manual)

There are several ways to install Ampache:

  1. Linux Distribution Package Manager (e.g., apt, dnf):

    • Pros: Easiest method. Handles dependencies automatically. Integrates well with the system's update process.
    • Cons: Versions in distribution repositories often lag behind the latest Ampache release. Might not be available in all distributions or might be significantly outdated. Limited control over installation specifics.
    • Example (Debian/Ubuntu, if available): sudo apt update && sudo apt install ampache ampache-common mysql-server php (Package names might vary).
  2. Manual Installation (Downloading Release Archive):

    • Pros: Access to the latest stable release or even development versions. Full control over installation location and configuration. Works on any system where prerequisites are met.
    • Cons: More complex. Requires manual setup of the web server configuration, database, and file permissions. Dependencies must be installed manually. Updates require repeating the download and setup process.
    • General Steps:
      1. Download the latest .zip or .tar.gz archive from the official Ampache website or GitHub releases page.
      2. Extract the archive into your web server's document root (e.g., /var/www/html/ampache or /usr/share/nginx/html/ampache).
      3. Create a dedicated database and database user for Ampache.
      4. Configure the web server (Apache VirtualHost or Nginx server block) to serve the Ampache directory.
      5. Set correct file permissions so the web server user can write to specific Ampache directories (e.g., config, cache, log).
      6. Access the Ampache URL in your browser to start the web-based configuration wizard.
  3. Docker / Docker Compose:

    • Pros: Encapsulates Ampache and its dependencies (potentially including web server, PHP, database) into isolated containers. Simplifies dependency management. Highly portable across different host systems. Easy to update (pulling a new image). Great for testing and deployment consistency.
    • Cons: Requires understanding Docker concepts. Can sometimes be harder to debug issues occurring inside the container. Networking setup (especially for external access) needs careful configuration.
    • Approach: Use the official Ampache Docker image or reputable community images. Often deployed using docker-compose for managing multi-container setups (Ampache app, database).
  4. Git Clone (for Developers/Testers):

    • Pros: Get the absolute latest development code. Easy to switch between branches.
    • Cons: Not recommended for production unless you are comfortable with potentially unstable code. Requires additional steps like installing Composer dependencies (composer install).

Recommendation for Beginners: If available and reasonably up-to-date, the package manager method is simplest. However, for learning, flexibility, and getting the latest features, Docker/Docker Compose is often the preferred method in modern self-hosting, and Manual Installation provides the deepest understanding of the components involved. We will use Docker for the first workshop.

Initial Configuration Wizard

Regardless of the installation method (except perhaps highly customized Docker images), your first interaction with a fresh Ampache instance will be through its web-based configuration wizard. Access it by navigating to your Ampache URL (e.g., http://your-server-ip/ampache or http://your-server-ip:port if using Docker with port mapping).

The wizard guides you through these crucial steps:

  1. Prerequisites Check: Ampache checks if all required PHP extensions are installed and if necessary directories are writable by the web server user. It will highlight any missing requirements that need to be addressed before proceeding. You might need to install missing PHP extensions (sudo apt install php8.1-gd php8.1-curl ...) and adjust directory permissions (sudo chown -R www-data:www-data /path/to/ampache/config, sudo chmod -R 755 /path/to/ampache/config). The exact user (www-data, apache, nginx) depends on your web server setup.
  2. Database Configuration: You'll need to provide the details for Ampache to connect to its database.
    • Database Type: Select MySQL/MariaDB or PostgreSQL.
    • Database Hostname: Usually localhost if the database is running on the same server. If using Docker Compose, it might be the name of the database service (e.g., db).
    • Database Name: The name of the database you created specifically for Ampache (e.g., ampache_db).
    • Database Username: The username you created with privileges on the Ampache database (e.g., ampache_user).
    • Database Password: The password for the Ampache database user.
    • Optional Port: If your database server runs on a non-standard port. Ampache will attempt to connect using these details and create the necessary tables.
  3. Ampache Configuration File Generation: Based on your database settings and other environment details, Ampache will generate its main configuration file (typically config/ampache.cfg.php). It might ask you to confirm the path or attempt to write it automatically if permissions allow.
  4. Administrator Account Creation: You need to create the first user account, which will have full administrative privileges.
    • Username: Choose a username (e.g., admin).
    • Password: Set a strong password.
    • Password Confirmation: Re-enter the password.
  5. Optional Settings: Depending on the Ampache version, the wizard might offer some initial basic settings, but most configuration happens after logging in.

Once the wizard completes successfully, you should be redirected to the Ampache login page, where you can log in using the administrator account you just created.

Creating Your First Music Catalog

With Ampache installed and the initial configuration done, it's time to tell it where your music lives.

  1. Prepare Your Music Directory:

    • Organize your music files in a directory on your server (e.g., /srv/music or /media/storage/music).
    • Crucially, ensure the user account that your web server (or Ampache process) runs as has read access to this directory and all the files and subdirectories within it. This is a very common point of failure. You might need commands like:
      # Example: Grant read access to the www-data group (common for Apache/Nginx on Debian/Ubuntu)
      sudo chown -R your_user:www-data /srv/music
      sudo find /srv/music -type d -exec chmod 750 {} \; # Read/execute for directories
      sudo find /srv/music -type f -exec chmod 640 {} \; # Read-only for files
      # Or, more permissively (less secure, use with caution):
      # sudo chmod -R 755 /srv/music
      
      Replace your_user with your regular user and www-data with the appropriate web server user. If using Docker, this involves mapping a host directory to a path inside the container, and ensuring permissions work across that boundary.
  2. Log in to Ampache: Access your Ampache instance via the web browser and log in with your admin account.

  3. Navigate to Catalog Management: Look for an administration section in the menu (often represented by a gear icon or "Admin"). Within the admin area, find "Catalogs" or "Manage Catalogs."

  4. Add New Catalog: Click the button to add a new catalog (e.g., "Add Catalog", "+").

  5. Configure Catalog Settings:

    • Catalog Name: Give it a descriptive name (e.g., "My Music Library", "FLAC Collection"). This name is shown in the Ampache interface.
    • Catalog Type: Select "local" for music stored on the same server as Ampache. Other types exist but are less common for basic setups.
    • Path: Enter the absolute path to your music directory on the server (e.g., /srv/music). This path is case-sensitive on Linux. If using Docker, this path must be the path inside the container that you mapped your music volume to.
    • Other Options (Defaults are usually okay initially):
      • Gather Art: Enable this to have Ampache look for album art files (like folder.jpg, cover.png) in album directories.
      • Catalog Rules: Leave empty for now (Advanced topic).
      • Scan Options: Choose how Ampache should scan (e.g., "Add, update and clean"). "Clean" removes entries for files that no longer exist.
  6. Save the Catalog: Click "Add Catalog" or "Save Catalog."

  7. Run the Catalog Scan: After saving, Ampache usually prompts you to scan the new catalog, or you might need to manually trigger it from the Catalog Management page. Click "Scan Now," "Update Catalog," or a similar button.

Ampache will now start scanning the specified path. It reads file metadata, looks for album art, and populates its database. The duration depends heavily on the size of your library and server performance. You can usually monitor the progress in the Ampache interface or logs. Once the scan is complete, you should be able to browse your music library through the Ampache web interface!

Workshop - Installing Ampache via Docker

This workshop provides a practical, step-by-step guide to installing Ampache using Docker and Docker Compose. This method isolates dependencies and simplifies setup.

Goal: Deploy Ampache and a MariaDB database using Docker Compose, perform the initial setup, and add a music catalog.

Prerequisites:

  1. A Linux server with Docker and Docker Compose installed. (Refer to official Docker documentation for installation instructions for your distribution).
  2. A directory on your host machine containing some music files (e.g., /home/your_user/my_music). Make a note of this path.
  3. Basic command-line familiarity.

Steps:

  1. Create a Project Directory:

    mkdir ~/ampache-docker
    cd ~/ampache-docker
    

  2. Create the docker-compose.yml File: Create a file named docker-compose.yml in the ~/ampache-docker directory using a text editor (like nano or vim):

    nano docker-compose.yml
    
    Paste the following content into the file. Read the comments carefully and adjust paths and passwords:

    version: "3.8"
    
    services:
      ampache:
        image: ampache/ampache:latest # Use the official Ampache image
        container_name: ampache_app
        restart: unless-stopped
        ports:
          - "8080:80" # Map host port 8080 to container port 80 (Ampache's default HTTP)
          # - "8443:443" # Uncomment later if you set up HTTPS inside the container
        environment:
          # Database Connection Details - MUST match the 'db' service settings
          - AMPACHE_DB_HOST=db # Service name of the database container
          - AMPACHE_DB_NAME=ampache_db # Database name
          - AMPACHE_DB_USER=ampache_user # Database user
          - AMPACHE_DB_PASSWORD=YourSecureDbPassword # CHANGE THIS! Use the same password as below
          # - TZ=Europe/Berlin # Optional: Set your timezone
        volumes:
          # Mount host directory for Ampache config
          - ./ampache_config:/config # Ampache configuration files
          # Mount host directory for Ampache web files (optional, for customization)
          # - ./ampache_web:/var/www/html
          # Mount your MUSIC library from the host into the container
          # IMPORTANT: Replace '/path/to/your/host/music' with the ACTUAL path on your server!
          - /path/to/your/host/music:/media/music:ro # ':ro' makes it read-only for safety
          # Mount a host directory for Transcoded media cache (optional but good)
          - ./ampache_transcodes:/media/transcodes
        depends_on:
          - db # Ensure the database starts before Ampache
    
      db:
        image: mariadb:10.11 # Use a specific MariaDB version
        container_name: ampache_db
        restart: unless-stopped
        environment:
          - MYSQL_ROOT_PASSWORD=AnotherSecureRootPassword # CHANGE THIS! Root password for DB admin
          - MYSQL_DATABASE=ampache_db # Database to create automatically
          - MYSQL_USER=ampache_user # User to create automatically
          - MYSQL_PASSWORD=YourSecureDbPassword # CHANGE THIS! Password for the user
          # - TZ=Europe/Berlin # Optional: Set your timezone
        volumes:
          # Mount host directory for persistent database storage
          - ./mariadb_data:/var/lib/mysql
    
    volumes:
      # Define the volumes used (ensures they exist)
      ampache_config:
      # ampache_web:
      mariadb_data:
      ampache_transcodes:
    
  3. Important Adjustments:

    • Passwords: Change YourSecureDbPassword (must be identical in both ampache and db services) and AnotherSecureRootPassword to strong, unique passwords.
    • Music Path: Critically, replace /path/to/your/host/music under ampache's volumes with the actual, absolute path to your music library on the host machine (e.g., /home/your_user/my_music).
    • Ports: We are mapping host port 8080 to the container's port 80. If port 8080 is already in use on your host, choose a different host port (e.g., 8888:80).
    • Timezone (Optional): Uncomment and set the TZ environment variable in both services if you want to specify your timezone.
  4. Save and Close: Save the docker-compose.yml file (Ctrl+X, then Y, then Enter in nano).

  5. Create Placeholder Directories (Optional but good practice): Docker will create these automatically, but doing it manually helps visualize:

    mkdir ampache_config mariadb_data ampache_transcodes
    
    Note: Do NOT create a ampache_web directory unless you uncommented that volume.

  6. Start the Containers: Run Docker Compose in detached mode (-d):

    docker-compose up -d
    
    Docker will download the ampache and mariadb images (this might take a few minutes) and then create and start the containers.

  7. Access the Ampache Web Wizard: Open your web browser and navigate to http://<your_server_ip>:8080. Replace <your_server_ip> with the actual IP address of your Linux server.

    • You should see the Ampache setup wizard.
    • Database Check: The wizard should detect the database connection details provided via environment variables (db as host, ampache_db, ampache_user, YourSecureDbPassword). Verify these look correct. It should connect automatically if passwords match. If it asks for details, enter them manually: Host=db, Name=ampache_db, User=ampache_user, Password=YourSecureDbPassword.
    • Create Admin User: Follow the prompts to create your Ampache admin username and password.
    • Complete the wizard.
  8. Log In: You should be redirected to the login page. Log in with the admin credentials you just created.

  9. Add Your Music Catalog:

    • Navigate to Admin -> Catalogs.
    • Click "Add Catalog".
    • Name: My Music (or any name you like).
    • Catalog Type: local.
    • Path: Enter /media/music. This is the path inside the Ampache container, as defined in the volumes section of your docker-compose.yml. Do not use the host path here.
    • Enable "Gather Art".
    • Click "Add Catalog".
    • On the next screen, click the "Update Now" button (or similar) for the catalog you just added.
  10. Verify: Wait for the scan to complete (monitor the status message). Once done, navigate back to the "Home" or "Browse" section. You should see your artists, albums, and tracks appearing! Try playing a song through the web interface.

Cleanup (If needed):

  • To stop the containers: cd ~/ampache-docker && docker-compose down
  • To stop and remove the containers and the associated volumes (deleting Ampache config and database data): cd ~/ampache-docker && docker-compose down -v

Congratulations! You have successfully installed and configured a basic Ampache instance using Docker, ready for further exploration.

2. Intermediate Ampache Usage

Now that you have a functional Ampache server with your music cataloged, let's delve into the features that make it a powerful personal streaming solution. This section covers managing users, exploring the playback and organizational capabilities of the web interface, connecting external clients using the Subsonic API, and basic techniques for keeping your music library up-to-date within Ampache.

User Management and Permissions

Ampache is designed for multi-user environments, allowing you to share your library with family or friends, each with their own account, playback history, playlists, and permissions.

Concepts:

  • Users: Individual accounts identified by a username and password. Each user has their own settings, stored playlists, playback statistics, and access rights.
  • Access Levels (Roles): Ampache uses a role-based access control system. Key default levels include:
    • Administrator: Full control over the Ampache instance, including system settings, user management, catalog configuration, and the ability to view/manage all users' data. The account created during the initial setup wizard is an administrator.
    • Catalog Manager: Can manage specific catalogs (add, update, delete media), but cannot change system-wide settings or manage users. Useful for delegating library updates.
    • User: Standard access level. Can browse the library, play music, create personal playlists, and manage their own profile. Cannot access administration functions. This is the typical level for regular users (family, friends).
    • Guest: Highly restricted access, often read-only or disabled by default.
  • Permissions: Beyond the basic access level, you can fine-tune permissions for individual users or groups (though group management is more advanced). This might include enabling/disabling:
    • Streaming: Can the user play music?
    • Downloading: Can the user download original music files? (Use with caution, especially if sharing outside your household).
    • Sharing: Can the user create public share links for tracks or playlists?
    • API Access: Can the user connect via the Subsonic API using third-party clients?
    • Catalog Access: If you have multiple catalogs, you can restrict users to specific ones.

Managing Users:

  1. Log in as Administrator: Access your Ampache web interface and log in with your admin account.
  2. Navigate to User Management: Go to Admin -> Users (or similar path).
  3. Adding a New User:
    • Click "Add User" or "+".
    • Username: Choose a unique username.
    • Password: Set a strong initial password (the user can usually change it later).
    • Full Name / Email (Optional): Add identifying information.
    • Access Level: Select the appropriate role (e.g., "User").
    • Permissions: Review and adjust specific permissions if needed (e.g., ensure "Allow API Access / Subsonic" is checked if they'll use mobile apps, decide whether to allow downloading).
    • Catalog Access: Assign access to the relevant music catalogs.
    • Click "Add User" or "Save".
  4. Editing an Existing User: Click the edit icon next to a username in the list to modify their details, password, access level, or permissions.
  5. Disabling/Deleting Users: You can typically disable an account temporarily or delete it permanently. Deleting a user often removes their associated playlists and statistics.

Use Cases:

  • Family: Create "User" accounts for family members, likely allowing streaming and API access, perhaps disabling downloads.
  • Friends: Create "User" accounts, perhaps with stricter controls (definitely disable downloads unless explicitly trusted, potentially rate-limit or disable API access if concerned about bandwidth).

Exploring the Web Interface (Playback, Playlists, Browsing)

The Ampache web interface is your primary portal for interacting with your music library directly from a computer. While layouts can vary slightly with themes and versions, the core functionalities remain consistent.

Key Areas:

  • Navigation Menu (Usually Left Sidebar or Top Bar):

    • Home: Dashboard often showing recently added albums, recently played tracks, statistics.
    • Browse: Explore your library by different categories:
      • Artists: List of all artists, clicking one shows their albums.
      • Albums: List of all albums, often sortable by name, year, date added.
      • Tracks/Songs: View all individual tracks (can be a very long list!).
      • Genres: Browse by genre tags from your files.
      • Years: Browse albums by release year.
      • Catalogs: If you have multiple catalogs, browse within a specific one.
    • Playlists: Manage your saved playlists.
    • Search: A search bar (usually prominent) to quickly find artists, albums, or tracks by name.
    • Admin/Settings: Access administrative functions (if logged in as admin) or user-specific settings.
  • Main Content Area: Displays the lists of artists, albums, tracks, or search results based on your navigation. Clicking on items usually drills down further (e.g., Artist -> Album -> Track List).

  • Playback Controls (Usually Bottom Bar or Top Bar):

    • Play/Pause Button: Controls the current track.
    • Previous/Next Track Buttons: Navigate the current play queue.
    • Volume Control: Adjust playback volume.
    • Seek Bar: Shows playback progress and allows seeking within the current track.
    • Repeat/Shuffle Toggles: Control playback mode.
    • Current Track Info: Displays artist, title, album, and often album art of the playing song.
    • Play Queue: Shows the list of upcoming tracks. You can usually add songs/albums to the queue, reorder tracks, and save the current queue as a playlist.

Common Actions:

  • Playing Music:
    • Click the play icon next to a track.
    • Click the play icon on an album cover to play the entire album (adds all tracks to the queue).
    • Click "Add to Queue" or a similar option to add tracks/albums without immediately interrupting playback.
  • Creating Playlists:
    • Static Playlists:
      1. Add desired tracks to the play queue.
      2. Go to the Play Queue view.
      3. Find an option like "Save Queue as Playlist."
      4. Give the playlist a name and save it.
      5. Alternatively, browse to tracks/albums and look for an "Add to Playlist" option (often via a context menu or "+" icon), allowing you to add items to new or existing playlists.
    • Dynamic Playlists (Smart Playlists): Ampache often supports creating playlists based on rules (e.g., "All tracks by Artist X released between Year Y and Year Z," "Random 50 tracks from Genre G not played in the last month"). Explore the Playlist section for options like "New Dynamic Playlist" or "Rule-Based Playlist." These are very powerful for music discovery within your own library.
  • Managing Playlists: In the Playlists section, you can view your saved playlists, play them, edit their contents (add/remove tracks), rename them, or delete them.

Spend time clicking around the web interface. Browse your library in different ways, create a few static and dynamic playlists, and familiarize yourself with the playback controls and queue management.

Connecting Mobile/Desktop Clients (Subsonic API)

While the web interface is functional, many users prefer dedicated apps for listening on their phones, tablets, or even desktops. Ampache achieves this compatibility primarily through its implementation of the Subsonic API.

What is the Subsonic API?

Subsonic was another popular open-source music streamer. While its development has changed course over the years, the Application Programming Interface (API) it defined became a de facto standard for self-hosted music streaming. Many different server projects (Ampache, Navidrome, Jellyfin, Plex sometimes) implement this API, and a wide range of client applications were developed to communicate using it.

How it Works:

  1. Enable API Access in Ampache: As an administrator, you need to ensure that API access (specifically Subsonic) is enabled globally (usually in Admin -> System Settings or API Clients) and enabled for the specific user accounts that will use it (Admin -> Users -> Edit User -> Permissions -> Allow API Access / Subsonic).
  2. Client Configuration: In your chosen client app (e.g., DSub on Android, Substreamer on iOS), you need to configure the connection to your Ampache server:
    • Server Address: The full URL to your Ampache instance. This must be accessible from the device where the client app is running.
      • If on the same local network: http://<your_server_ip>:<port> (e.g., http://192.168.1.100:8080).
      • If accessing over the internet: You'll need your public IP address or a domain name pointing to it, and you'll need to have configured port forwarding on your router (and potentially a reverse proxy for HTTPS, covered later). Example: https://myampache.mydomain.com.
    • Username: The Ampache username for the account.
    • Password: The Ampache password for that user. Some clients might also support API keys generated within Ampache for better security, but username/password is the most common method.
    • Protocol: Select HTTP or HTTPS depending on how your server is set up. HTTPS is strongly recommended for internet access.
    • Legacy Auth (Sometimes): Some clients might require you to enable "Password" or "Legacy Authentication" instead of using API keys, especially if direct password login is enabled in Ampache's Subsonic settings.
  3. Connection: The client app uses the provided details to connect to the Ampache server via the Subsonic API. It fetches the library structure (artists, albums, tracks), playlists, and initiates streaming requests. Ampache responds with the requested data or audio stream.

Popular Subsonic Clients:

  • Android: DSub (paid, highly recommended), Subsonic Music Streamer (official, may require premium), Ultrasonic, Audinaut, Substreamer
  • iOS: Substreamer, play:Sub, iSub (older, may not be updated)
  • Desktop: Clementine (Music Player with Subsonic support), Supersonic (Windows/macOS/Linux), Submariner (macOS), Ampache Desktop Player (less common), Web Browsers (via the Ampache UI)
  • Command Line: subcmd

Connecting a mobile client significantly enhances the usability of Ampache, allowing you to take your music library on the go.

Basic Catalog Management (Adding/Removing Music, Scanning)

Your music library isn't static. You'll add new albums, re-tag existing files, or remove music you no longer want. Ampache needs to be informed of these changes to keep its database synchronized with your actual files.

The Process:

  1. Modify Files on Disk: Add, remove, or modify your music files directly in the directory configured as your Ampache catalog path (e.g., /srv/music or the host directory mapped in Docker). Use your standard file manager, command-line tools (cp, mv, rm), or music management software (like MusicBrainz Picard for tagging).
  2. Trigger a Catalog Scan in Ampache: Ampache doesn't automatically detect filesystem changes in real-time (this would be very inefficient). You need to tell it to re-scan the catalog directory.
    • Log in to the Ampache web interface (usually requires Catalog Manager or Admin privileges).
    • Navigate to Admin -> Catalogs.
    • Find the catalog you want to update.
    • Click the "Update Now," "Scan," or similar button associated with that catalog.
    • Scan Options: You might see choices like:
      • Add & Update: Finds new files and updates metadata for existing ones. Doesn't remove entries for deleted files. Faster for just adding music.
      • Add, Update & Clean: Does the above, plus checks if files listed in the database still exist on disk. If not, it removes the corresponding entries from the database (cleans up). This is the most thorough option but can be slower.
      • Force Update: Re-reads metadata even if file modification times haven't changed. Useful if you've retagged files without changing the timestamp.
  3. Wait for Completion: Ampache will scan the directory again. New files will be added, metadata for changed files will be updated (if detected), and database entries for deleted files will be removed (if using a "Clean" scan).

Automation (Advanced):

For large libraries or frequent changes, manually triggering scans can be tedious. More advanced setups might involve:

  • Scheduled Scans: Some Ampache versions or configurations allow setting up automatic scans at regular intervals (e.g., nightly) via cron jobs executing a command-line scan script provided by Ampache.
  • Filesystem Monitoring (e.g., inotify): Setting up scripts that watch the music directory for changes and automatically trigger an Ampache scan via its command-line interface. This is complex to set up reliably.

For intermediate usage, manual scans via the web UI are sufficient. Remember to perform a "Clean" scan periodically to remove entries for deleted files.

Workshop - Setting Up User Access and Connecting DSub

This workshop guides you through creating a standard user account in Ampache and connecting to it using the popular DSub client on Android (principles are similar for other Subsonic clients on other platforms).

Goal: Create a non-admin user, grant appropriate permissions, and successfully connect and stream music using DSub.

Prerequisites:

  1. A functional Ampache instance (from the previous workshop or manually installed).
  2. Admin access to your Ampache web interface.
  3. An Android device with the DSub app installed (available on the Google Play Store; it's a paid app but worth it for many). If you don't have DSub, you can try another Subsonic client like Substreamer (often free with ads or a pro version).
  4. Your Android device must be able to reach your Ampache server over the network (either on the same Wi-Fi or via the internet if you've configured external access).

Steps:

  1. Create a New User in Ampache:

    • Log in to your Ampache web UI as the administrator.
    • Navigate to Admin -> Users.
    • Click "Add User".
    • Username: testuser (or any name you prefer).
    • Password: TestPassword123 (Choose a reasonably strong password; you can change it later).
    • Full Name (Optional): Test User.
    • Access Level: Select User.
    • Permissions: Scroll down to the permissions section. Ensure the following are checked (enabled):
      • Stream (Allow user to stream media)
      • Allow API Access / Subsonic (Crucial for DSub connection)
      • You might want to uncheck Download (Prevent user from downloading original files) for this example.
    • Catalog Access: Ensure the checkbox next to your main music catalog (e.g., "My Music") is checked, granting this user access to it.
    • Click "Add User".
  2. Verify User Creation: You should see testuser listed on the Users page.

  3. Configure DSub on Android:

    • Open the DSub app on your Android device.
    • You'll likely be presented with a server configuration screen upon first launch. If not, find the settings or server menu (often a gear icon or sidebar).
    • Tap "Add Server" or the "+" icon.
    • Server Name: My Ampache (This is just a label within DSub).
    • Server Address: Enter the full URL your Ampache server is accessible at from your phone.
      • If on the same Wi-Fi as the server (using Docker setup from Workshop 1): http://<your_server_ip>:8080 (e.g., http://192.168.1.100:8080). Find your server's local IP using ip addr on the server.
      • If accessing over the internet (requires port forwarding/domain name): https://your_ampache_domain.com or http://your_public_ip:<forwarded_port>. Using HTTPS is strongly recommended here.
    • Username: testuser
    • Password: TestPassword123 (the password you set for testuser).
    • Use Legacy Auth: Leave this unchecked initially. If connection fails, you might try checking it as a fallback (depends on Ampache API settings).
    • Test Connection: Tap the "Test Connection" button. DSub will attempt to contact your server using the Subsonic API.
      • Success: You should see a "Connection successful" message.
      • Failure: Double-check the Server Address (most common issue - can your phone actually reach that IP/domain and port?), Username, and Password. Ensure Allow API Access / Subsonic is enabled for testuser in Ampache. Check if a firewall on your server or router is blocking the connection. If using HTTPS, ensure the certificate is valid. If using HTTP locally, ensure your phone is on the correct Wi-Fi network.
  4. Save Server Configuration: Once the connection test is successful, save the server settings in DSub.

  5. Browse and Play:

    • DSub should now connect and start syncing your library information from Ampache.
    • Navigate through DSub's interface (Library, Artists, Albums, etc.). You should see the music from your Ampache catalog.
    • Select an album or track and press play.
    • Music should start streaming from your Ampache server to your phone!
  6. Troubleshooting (If Playback Fails):

    • Can you play music via the Ampache web interface using the testuser account? (Verifies basic user permissions).
    • Check Ampache logs (Admin -> System -> View Logs) for any errors related to streaming or API requests.
    • Check transcoding settings in Ampache (covered later) - perhaps the default settings are incompatible with DSub or your phone. Try disabling transcoding temporarily for testing.
    • Check network stability between your phone and the server.

You have now successfully set up multi-user access and experienced the convenience of using a dedicated mobile client with your self-hosted Ampache server.

3. Advanced Ampache Configuration and Features

With the basics mastered, it's time to unlock Ampache's full potential. This section explores more complex configurations, including optimizing streaming with transcoding, managing multiple libraries, setting up secure external access via a reverse proxy, understanding the API's capabilities, and hardening your server's security. These steps elevate your personal music cloud from a basic setup to a robust, flexible, and secure service.

Transcoding Configuration (Optimizing for Bandwidth/Devices)

Transcoding is Ampache's ability to convert media files on-the-fly before streaming them. This is crucial for adapting to different network conditions and client capabilities.

Why Configure Transcoding?

  • Bandwidth Management: Streaming large lossless files (FLAC, WAV) over mobile data or slow Wi-Fi can be impractical or expensive. Transcoding to a lower-bitrate lossy format (like MP3 or Opus at 128-192kbps) drastically reduces data consumption.
  • Device Compatibility: Some players (especially older ones, or web browsers using HTML5 audio) might not support all formats your library contains (e.g., Ogg Vorbis, Opus). Transcoding ensures playback by converting to a universally supported format like MP3 or AAC.
  • CPU vs. Bandwidth Trade-off: Transcoding consumes server CPU resources. Direct streaming (no transcoding) uses minimal CPU but maximum bandwidth. You need to configure transcoding to strike the right balance for your server hardware and network environment.

Key Components:

  • ffmpeg: The powerhouse behind Ampache's transcoding. This external command-line tool handles the actual audio/video conversion. You must have ffmpeg installed on your server (or within the Docker container) for transcoding to work. Verify installation with ffmpeg -version.
  • Ampache Transcoding Settings (Admin -> System -> Streaming): This is where you define transcoding profiles.
    • Transcoding Templates/Players: Ampache allows defining different "players" or "transcoding configurations." Each represents a specific target format and bitrate. Examples:
      • MP3 - 192kbps: Convert any input to an MP3 file with an average bitrate of 192kbps.
      • Opus - 96kbps: Convert to the efficient Opus codec at 96kbps (good for mobile).
      • Original/Passthrough: Do not transcode, stream the original file.
    • Configuration Details per Template:
      • Name: A descriptive name (e.g., "High Quality MP3", "Mobile Opus").
      • Type: Usually local (uses ffmpeg on the server).
      • Command: The actual ffmpeg command Ampache will execute. This uses placeholders for input (%f), output (%o), bitrate (%b), etc. Ampache provides defaults, but you can customize them heavily. Example (Simple MP3): ffmpeg -i %f -map 0:a:0 -b:a %bk -v 0 -f mp3 - (Outputs to stdout -, which Ampache streams).
      • Bitrate: The target bitrate in kbps (e.g., 192).
      • Mimetype: The MIME type of the output stream (e.g., audio/mpeg for MP3, audio/opus for Opus). This tells the client what kind of data it's receiving.
      • Downsampling: Optionally reduce the audio sample rate (e.g., from 48kHz to 44.1kHz) for further size reduction or compatibility.
  • Client-Side Selection: Most Subsonic clients (like DSub) allow the user to select a maximum bitrate or a specific transcoding format in the app's settings. When the client requests a track, it tells the server its preference.
  • Server-Side Rules: Ampache matches the client's request (or its default if no preference is sent) to one of the configured transcoding templates. If a match requires transcoding, Ampache invokes ffmpeg with the appropriate command and streams the output.

Configuration Steps:

  1. Install ffmpeg: Ensure ffmpeg is installed (sudo apt install ffmpeg or ensure it's in your Docker image).
  2. Access Ampache Streaming Settings: Log in as admin, go to Admin -> System -> Streaming.
  3. Review Default Templates: Examine the pre-configured transcoding templates. Understand what formats and bitrates they target.
  4. Add/Modify Templates (Optional):
    • You might want to add a template for a modern, efficient codec like Opus if one doesn't exist.
    • You might want to adjust the bitrates of existing templates (e.g., lower the default MP3 bitrate for mobile use).
    • You can create specialized templates (e.g., converting only specific input formats).
  5. Set Default Transcoding: Choose a default transcoding template that Ampache will use if a client doesn't specify a preference. A moderate MP3 setting (e.g., 192kbps) is often a safe default.
  6. Test with Clients: Configure your mobile/desktop client to request different maximum bitrates or formats and verify that Ampache transcodes correctly (you can often see ffmpeg processes running on the server using top or htop during playback). Check if playback works on various devices and network conditions.

Considerations:

  • CPU Load: Monitor your server's CPU usage during transcoding, especially if multiple users are streaming simultaneously. If the CPU is consistently maxed out, you may need to lower the transcoding quality, use more efficient codecs (like Opus), limit the number of simultaneous transcodes (if Ampache allows), or upgrade your server hardware.
  • Cache: Ampache might cache transcoded files (check ampache_transcodes volume in the Docker example) to avoid re-transcoding the same track multiple times with the same settings. Ensure the cache directory is writable and has sufficient space.

Advanced Catalog Options (Multiple Catalogs, Rules)

While a single catalog works for many, Ampache allows for more granular organization using multiple catalogs and defining rules within them.

Multiple Catalogs:

  • Purpose: Useful for logically separating different types of media or libraries with different characteristics.
  • Use Cases:
    • Format Separation: A catalog for your high-resolution FLAC collection and another for your lossy MP3s.
    • Genre/Type Separation: Separate catalogs for Music, Audiobooks, Podcasts, Soundtracks.
    • Source Separation: One catalog for locally stored music, another potentially for remote sources (though less common).
    • Permissions: Assign different users access to different catalogs (e.g., kids only get access to the "Children's Music" catalog).
  • Setup: Simply repeat the process from "Creating Your First Music Catalog" (Admin -> Catalogs -> Add Catalog) for each distinct library/directory you want to manage separately. Give each a unique name and point it to the correct path on the server (or inside the container).

Catalog Rules:

  • Purpose: Provide fine-grained control over which files within a catalog's path are actually included or excluded during a scan. Rules operate based on file paths, filenames, or other attributes.
  • Use Cases:
    • Excluding File Types: Prevent Ampache from cataloging non-music files (e.g., .txt, .log, .cue files) that might be mixed in with your music.
    • Excluding Specific Directories: Exclude subdirectories containing artwork, lyrics, or incomplete downloads (e.g., /path/to/music/artwork/, /path/to/music/_incomplete/).
    • Including Only Specific Formats: If a directory contains mixed formats, create a rule to only include, say, .flac files in a specific "FLAC Only" catalog.
  • Setup (Admin -> Catalogs -> Edit Catalog -> Rules):
    • Rules are typically based on regular expressions or simple wildcard patterns applied to the file path or name.
    • Rule Type: Include or Exclude.
    • Rule Condition: Often matches against the full file path.
    • Pattern: The regular expression or pattern to match (e.g., \.log$ to match files ending in .log, /artwork/ to match any file within an artwork subdirectory).
    • Order Matters: Rules are often processed in order. A file must pass all relevant rules (or match an include rule without matching a subsequent exclude rule) to be added to the catalog.
  • Example: To exclude all .txt files and everything inside any directory named scans:
    1. Rule 1: Type=Exclude, Condition=File Path, Pattern=\.txt$
    2. Rule 2: Type=Exclude, Condition=File Path, Pattern=/scans/

Catalog rules require careful planning and testing (using the preview or re-scanning after changes) to ensure they achieve the desired effect without accidentally excluding wanted media.

Reverse Proxy Setup (Nginx/Apache for HTTPS and Clean URLs)

Running Ampache directly exposed to the internet on its default port (like 8080 in our Docker example) has several disadvantages: it often uses plain HTTP (insecure), requires remembering the port number, and bypasses the features of a dedicated web server. A reverse proxy solves these issues.

What is a Reverse Proxy?

A reverse proxy is a web server (like Nginx or Apache) that sits in front of your Ampache application server. Clients connect to the reverse proxy, which then forwards the request to the Ampache backend (running on localhost or within a Docker network).

Benefits:

  1. HTTPS/SSL/TLS Encryption: The reverse proxy can handle SSL/TLS termination. Clients connect to the proxy using HTTPS (securely), and the proxy communicates with Ampache internally using plain HTTP (which is safe within the server or Docker network). This is essential for security, protecting login credentials and preventing eavesdropping. Let's Encrypt provides free SSL certificates.
  2. Clean URLs: Access Ampache via a standard domain name without needing a port number (e.g., https://ampache.yourdomain.com instead of http://your_ip:8080).
  3. Centralized Access Point: If you host multiple services, the reverse proxy can route traffic based on the domain name or path (e.g., ampache.yourdomain.com goes to Ampache, files.yourdomain.com goes to Nextcloud).
  4. Load Balancing (Advanced): Distribute requests across multiple Ampache instances.
  5. Caching (Advanced): Cache static assets (CSS, JS, images) at the proxy level for faster loading.
  6. Security Headers: Easily add security headers (like HSTS, CSP) at the proxy level.

Common Choices:

  • Nginx: Very popular for reverse proxying due to its performance and configuration simplicity.
  • Apache: Also capable using mod_proxy and mod_ssl.
  • Caddy: Modern web server known for automatic HTTPS.
  • Traefik: Cloud-native reverse proxy, integrates well with Docker.

We'll focus on Nginx, as it's widely used in self-hosting.

Nginx Configuration Example (Conceptual):

Assume Ampache is running and accessible at http://127.0.0.1:8080 (either directly installed or via Docker mapped to localhost:8080).

  1. Install Nginx: sudo apt update && sudo apt install nginx
  2. Install Certbot (for Let's Encrypt): sudo apt install certbot python3-certbot-nginx
  3. Configure Nginx Server Block: Create a configuration file for your Ampache site (e.g., /etc/nginx/sites-available/ampache):

    server {
        listen 80;
        server_name ampache.yourdomain.com; # Replace with your domain
    
        # Redirect HTTP to HTTPS (Certbot might handle this automatically)
        location / {
            return 301 https://$host$request_uri;
        }
    }
    
    server {
        listen 443 ssl http2; # Listen on HTTPS port
        server_name ampache.yourdomain.com; # Replace with your domain
    
        # SSL Certificate paths (Certbot will manage these)
        ssl_certificate /etc/letsencrypt/live/ampache.yourdomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/ampache.yourdomain.com/privkey.pem;
        include /etc/letsencrypt/options-ssl-nginx.conf; # Recommended SSL settings
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # Recommended DH params
    
        # Increase max body size for potential large file uploads/requests
        client_max_body_size 100M;
    
        location / {
            proxy_pass http://127.0.0.1:8080; # Forward requests to Ampache backend
    
            # Set headers to pass correct info to Ampache
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme; # Important for HTTPS detection
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Port $server_port;
    
            # Optional: Buffering settings (adjust as needed)
            proxy_buffering off; # Often recommended for streaming applications
            # proxy_buffer_size 128k;
            # proxy_buffers 4 256k;
            # proxy_busy_buffers_size 256k;
    
            # Optional: Timeouts (increase if needed for long operations)
            # proxy_connect_timeout 600;
            # proxy_send_timeout 600;
            # proxy_read_timeout 600;
            # send_timeout 600;
        }
    
        # Optional: Improve security headers
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        add_header X-Content-Type-Options nosniff always;
        add_header X-Frame-Options SAMEORIGIN always;
        # add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'; img-src 'self' data:;"; # Example CSP - needs tuning!
    }
    
  4. Enable the Site: sudo ln -s /etc/nginx/sites-available/ampache /etc/nginx/sites-enabled/

  5. Test Nginx Configuration: sudo nginx -t (Should report syntax is OK).
  6. Obtain SSL Certificate: sudo certbot --nginx -d ampache.yourdomain.com (Follow prompts, choose redirect option).
  7. Reload Nginx: sudo systemctl reload nginx

Now, accessing https://ampache.yourdomain.com should securely proxy requests to your Ampache instance running on port 8080. Remember to update your client app configurations to use the new HTTPS URL.

Ampache API and Integrations (Subsonic API Deep Dive)

We've discussed using the Subsonic API for client apps. Understanding its capabilities allows for deeper integration and potential automation.

Key Subsonic API Functions (Implemented by Ampache):

  • ping.view: Test connectivity.
  • getLicense.view: (Legacy Subsonic) Often just confirms connection.
  • getMusicFolders.view: List configured catalogs/folders.
  • getIndexes.view: Get the list of artists (or albums by folder structure).
  • getMusicDirectory.view: Get contents of a folder (albums by an artist, or tracks in an album).
  • getAlbumList.view / getAlbumList2.view: Get lists of albums (by type: random, newest, genre, etc.).
  • getAlbum.view: Get details and track list for a specific album ID.
  • getSong.view: Get details for a specific song ID.
  • getArtists.view: Get all artists.
  • getArtist.view: Get details for a specific artist ID.
  • stream.view: Request an audio stream for a song ID. Supports parameters like maxBitRate, format, timeOffset. This is where transcoding happens based on client request.
  • download.view: Request to download the original file for a song ID.
  • getCoverArt.view: Get album cover artwork for an album/song ID.
  • search2.view / search3.view: Search for artists, albums, or songs.
  • getPlaylists.view: Get the list of saved playlists.
  • getPlaylist.view: Get the tracks within a specific playlist.
  • createPlaylist.view: Create a new playlist.
  • updatePlaylist.view: Add/remove songs from a playlist.
  • deletePlaylist.view: Delete a playlist.
  • scrobble.view: Submit playback information (scrobbling) to Ampache (and potentially linked services like Last.fm if configured).
  • getChatMessages.view / addChatMessage.view: (Less common) Basic chat functions.
  • getUser.view: Get details about a specific user.

Authentication:

Requests typically include authentication parameters in the URL query string:

  • u: Username
  • p: Password (often hex-encoded md5(password)) or an API key.
  • t: Token (for salt-based authentication, more secure)
  • s: Salt (random string provided by server)
  • v: API version (e.g., 1.16.1)
  • c: Client identifier (e.g., DSub)
  • f: Response format (xml or json)

Potential Uses:

  • Custom Scripts: Write scripts (Python, Bash with curl, etc.) to interact with Ampache (e.g., automatically create playlists based on external events, sync playback status with other systems, perform complex library analysis).
  • Integration with Home Automation: Trigger Ampache playback or playlists via systems like Home Assistant.
  • Developing Custom Clients: Build specialized interfaces or clients tailored to specific needs.

Explore the official Subsonic API documentation (http://www.subsonic.org/pages/api.jsp - note that Ampache's implementation might have slight variations) to see the full range of parameters and possibilities. You can experiment by crafting API request URLs directly in your browser (after logging into Ampache first) or using tools like curl.

Security Hardening (HTTPS, Fail2ban, Updates)

Protecting your self-hosted Ampache server is crucial, especially if it's accessible from the internet.

Essential Security Measures:

  1. HTTPS Everywhere: As covered in the Reverse Proxy section, always use HTTPS for external access. Use Let's Encrypt via Certbot or your proxy's built-in ACME support for free, trusted certificates. Configure your reverse proxy to redirect all HTTP traffic to HTTPS. Enable HSTS (HTTP Strict Transport Security) headers to enforce browser use of HTTPS.
  2. Strong Passwords: Use strong, unique passwords for:
    • Ampache user accounts (especially the admin account).
    • The database user Ampache connects with.
    • The server's root/sudo user.
  3. Regular Updates: Keep all components updated:
    • Ampache: Monitor Ampache releases (website, GitHub) and update regularly to get security patches and bug fixes. The update process depends on your installation method (e.g., docker-compose pull && docker-compose up -d for Docker, download new release and replace files for manual install, apt update && apt upgrade for package manager). Always back up your config and database before updating.
    • Operating System: Keep your Linux distribution updated (sudo apt update && sudo apt dist-upgrade -y).
    • Web Server (Nginx/Apache), PHP, Database (MariaDB): Apply security updates provided by your distribution's package manager.
  4. Fail2ban: This intrusion prevention software monitors log files for patterns like repeated failed login attempts and automatically blocks the offending IP address using the system firewall (iptables or nftables).
    • Installation: sudo apt update && sudo apt install fail2ban
    • Configuration: Create a local configuration file (e.g., /etc/fail2ban/jail.local) to override defaults. Configure jails for:
      • sshd: Protects SSH access (usually enabled by default).
      • nginx-http-auth or apache-auth: Protects basic auth if used.
      • Ampache Login: This requires specific configuration as Ampache logs failed logins to its own log file or potentially the web server error log depending on setup. You'll need to:
        1. Identify Failed Login Log Entry: Find the exact log message Ampache (or Nginx/Apache error log) generates for a failed web UI or API login.
        2. Create a Fail2ban Filter: Define a filter (in /etc/fail2ban/filter.d/ampache.conf) with a regular expression (failregex) to match that log entry and capture the IP address (<HOST>).
        3. Enable the Jail: Define and enable a jail in jail.local that uses this filter, specifies the log file path, and sets block actions (e.g., port=http,https, banaction=iptables-multiport).
      • Example filter.d/ampache.conf (pattern depends heavily on Ampache version/logging):
        [Definition]
        failregex = ^.* \[client <HOST>\] FAILED LOGIN.*$
        # Adjust regex based on your actual log format!
        ignoreregex =
        
      • Example jail.local entry:
        [ampache]
        enabled = true
        port = http,https
        filter = ampache
        logpath = /path/to/ampache/logs/ampache.log # Or /var/log/nginx/error.log etc.
        maxretry = 5
        findtime = 600
        bantime = 3600
        
    • Restart Fail2ban: sudo systemctl restart fail2ban
    • Verify: Check sudo fail2ban-client status ampache after deliberately failing logins.
  5. Firewall: Configure your server's firewall (e.g., ufw on Ubuntu, firewalld on CentOS, or raw iptables/nftables) to only allow traffic on necessary ports (e.g., SSH (often rate-limited or on a non-standard port), HTTP/80 (for Let's Encrypt renewal and HTTP->HTTPS redirect), HTTPS/443). Block all other ports.
  6. File Permissions: Ensure file permissions are as restrictive as possible. The Ampache web root files should generally be owned by root and readable by the web server user (www-data), but not writable. Only specific directories (config, cache, log, transcodes) need write access by the web server user. Music directories only need read access for the web server user.
  7. Disable Unused Features: Turn off Ampache features you don't use (e.g., registration, guest access, certain API types) in the Admin settings.
  8. Database Security: Ensure the database only listens on localhost if not needed externally. Use a strong password for the ampache_user and grant it only the necessary privileges on the ampache_db database.

Security is an ongoing process, not a one-time setup. Stay vigilant about updates and monitor logs periodically.

Workshop - Configuring Nginx Reverse Proxy with Let's Encrypt

This workshop details setting up Nginx as a reverse proxy for your Docker-based Ampache installation (from Workshop 1), enabling HTTPS access via Let's Encrypt.

Goal: Access Ampache securely via https://your_domain_name without the port number.

Prerequisites:

  1. Ampache running via Docker Compose (from Workshop 1), accessible internally at http://127.0.0.1:8080. Ensure it's working before proceeding.
  2. A Linux server (can be the same one running Docker) with Nginx and Certbot installed (sudo apt update && sudo apt install nginx certbot python3-certbot-nginx).
  3. A registered domain name (e.g., yourdomain.com).
  4. DNS records configured for your domain: An A record pointing a subdomain (e.g., ampache.yourdomain.com) to your server's public IP address. Allow time for DNS propagation.
  5. Ports 80 and 443 open on your server's firewall (sudo ufw allow 'Nginx Full') and forwarded from your router to your server's local IP address if behind NAT.

Steps:

  1. Stop Existing Service on Port 80 (If Necessary): If Nginx is already serving a default page, it's fine. If another service (like Apache) is using port 80, stop it.

  2. Create Nginx Configuration File for Ampache: Create the file /etc/nginx/sites-available/ampache:

    sudo nano /etc/nginx/sites-available/ampache
    
    Paste the following basic HTTP configuration. Replace ampache.yourdomain.com with your actual subdomain.

    server {
        listen 80;
        server_name ampache.yourdomain.com; # <-- Replace with your domain
    
        # Location block for Let's Encrypt verification
        location /.well-known/acme-challenge/ {
            root /var/www/html; # Or another directory Nginx can write to
        }
    
        location / {
            # Temporary: We'll replace this with proxy settings later
            # For now, just return a simple message to test HTTP access
            return 200 'Nginx is configured for Ampache domain (HTTP)';
            # OR, if you want to test proxying immediately (without HTTPS):
            # proxy_pass http://127.0.0.1:8080;
            # proxy_set_header Host $host;
            # proxy_set_header X-Real-IP $remote_addr;
            # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            # proxy_set_header X-Forwarded-Proto $scheme;
        }
    }
    
  3. Enable the Nginx Site:

    sudo ln -s /etc/nginx/sites-available/ampache /etc/nginx/sites-enabled/
    # Optional: Remove default site if it conflicts
    # sudo rm /etc/nginx/sites-enabled/default
    

  4. Test Nginx Configuration:

    sudo nginx -t
    
    If it reports syntax OK, reload Nginx:
    sudo systemctl reload nginx
    
    Verification: Try accessing http://ampache.yourdomain.com in your browser. You should see the "Nginx is configured..." message (or your Ampache login if you enabled proxy_pass already). This confirms Nginx is handling requests for your domain on port 80.

  5. Obtain Let's Encrypt Certificate: Run Certbot using the Nginx plugin. It will automatically detect your server_name, obtain the certificate, and modify your Nginx configuration to use it and set up HTTPS.

    sudo certbot --nginx -d ampache.yourdomain.com # <-- Replace with your domain
    

    • Enter your email address for renewal notices.
    • Agree to the Terms of Service.
    • Choose whether to share your email (optional).
    • Crucially, when asked about redirecting HTTP to HTTPS, choose option 2 (Redirect). This ensures all traffic uses HTTPS. Certbot should report success and tell you where your certificate files are saved.
  6. Verify Certbot's Changes: Check your Nginx configuration file again:

    sudo nano /etc/nginx/sites-available/ampache
    
    You'll see Certbot has added listen 443 ssl, SSL certificate paths, and potentially the HTTP to HTTPS redirect block. It might look slightly different from the manual example earlier, but the core elements should be present.

  7. Refine Nginx Configuration with Proxy Settings: Now, edit the /etc/nginx/sites-available/ampache file again. Focus on the server { ... } block that listens on 443 ssl. Modify the location / { ... } block inside it to include the proxy_pass directive and necessary headers:

    server {
        listen 443 ssl http2; # Certbot likely set this up
        server_name ampache.yourdomain.com; # Your domain
    
        # SSL settings added by Certbot - LEAVE THESE AS IS
        ssl_certificate /etc/letsencrypt/live/ampache.yourdomain.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/ampache.yourdomain.com/privkey.pem;
        include /etc/letsencrypt/options-ssl-nginx.conf;
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem;
    
        # Add security headers (optional but recommended)
        add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
        add_header X-Content-Type-Options nosniff always;
        add_header X-Frame-Options SAMEORIGIN always;
    
        # Increase max body size
        client_max_body_size 100M;
    
        location / {
            # ** Replace Certbot's default location content with these proxy settings **
            proxy_pass http://127.0.0.1:8080; # Point to your Ampache Docker container
    
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
            proxy_set_header X-Forwarded-Proto $scheme; # Very important!
            proxy_set_header X-Forwarded-Host $host;
            proxy_set_header X-Forwarded-Port $server_port;
    
            # Recommended for streaming
            proxy_buffering off;
        }
    
        # Optional: Block access to sensitive files if Ampache webroot was exposed (less relevant with proxy_pass)
        # location ~ /\.ht {
        #    deny all;
        # }
    }
    
    # Certbot likely configured this HTTP redirect block - LEAVE AS IS
    server {
        listen 80;
        server_name ampache.yourdomain.com;
        if ($host = ampache.yourdomain.com) {
            return 301 https://$host$request_uri;
        }
        return 404;
    }
    
  8. Test and Reload Nginx Again:

    sudo nginx -t
    sudo systemctl reload nginx
    

  9. Final Verification:

    • Open your browser and navigate to https://ampache.yourdomain.com.
    • You should see the Ampache login page, served securely over HTTPS.
    • Your browser should show a valid lock icon, indicating a secure connection.
    • Log in and test playback.
    • Update your Subsonic client apps to use the new https://ampache.yourdomain.com URL.

Congratulations! You have successfully configured Nginx as a secure reverse proxy for Ampache using Let's Encrypt SSL certificates.

4. Troubleshooting Common Issues

Even with careful setup, you might encounter problems with your Ampache installation. This section outlines common issues, their potential causes, and systematic approaches to diagnosing and fixing them. Effective troubleshooting often involves checking logs, verifying configurations, and testing permissions.

Installation Problems (Permissions, Dependencies)

Symptoms:

  • Ampache setup wizard fails or shows errors.
  • Web server shows a 500 Internal Server Error or blank page instead of Ampache.
  • Wizard reports missing PHP extensions or non-writable directories.

Common Causes:

  1. Missing PHP Extensions: Ampache relies on specific PHP modules (e.g., pdo_mysql, gd, curl, xml, intl). If any are missing, Ampache core functions will fail.
  2. Incorrect File Permissions/Ownership: This is the most frequent cause. The user account that your web server (Nginx/Apache) or PHP-FPM process runs as (e.g., www-data, nginx, apache) needs:
    • Read access to all Ampache application files (PHP scripts, static assets).
    • Write access to specific directories required by Ampache: config/, cache/, log/, public/themes/ (for theme caching), and potentially others like channel/ or transcode cache directories if used.
  3. Incorrect Web Server Configuration: Nginx server block or Apache VirtualHost configuration might be incorrect (wrong root path, incorrect PHP processing setup, alias issues).
  4. Database Connection Failure: Incorrect database hostname, database name, username, or password provided during setup or in config/ampache.cfg.php. The database server might not be running or accessible.
  5. PHP Version Incompatibility: Using a PHP version not supported by your Ampache version.
  6. SELinux/AppArmor Issues (Less Common): Security modules might be blocking the web server from accessing files or making network connections, even if standard file permissions seem correct.

Troubleshooting Steps:

  1. Check Ampache Prerequisite Check: Carefully review the initial setup wizard's prerequisite check page. Install any missing PHP extensions (sudo apt install php<ver>-<extension>) and restart your web server/PHP-FPM (sudo systemctl restart nginx php<ver>-fpm).
  2. Check Web Server Error Logs: These are invaluable.
    • Nginx: /var/log/nginx/error.log (and potentially site-specific error logs like /var/log/nginx/ampache-error.log).
    • Apache: /var/log/apache2/error.log (or distribution-specific path). Look for specific PHP errors ("PHP Fatal error:", "PHP Parse error:") or permission denied errors.
  3. Check Ampache Logs: Look inside the Ampache log/ directory (if it was created and is writable) for ampache.log or similar files.
  4. Verify File Permissions:
    • Find the web server user: ps aux | egrep '(nginx|apache|httpd|php-fpm)' (look for the user in the process list). Common users: www-data, nginx, apache.
    • Check ownership and permissions of the Ampache installation directory (e.g., /var/www/ampache): ls -l /var/www/ampache
    • Recursively check permissions on required writable directories: ls -l /var/www/ampache/config etc.
    • Fix Permissions: Use chown and chmod carefully. Example for Nginx user www-data:
      # Set ownership of the entire directory (adjust user/group)
      sudo chown -R www-data:www-data /var/www/ampache
      # Set baseline permissions (read/execute for dirs, read for files)
      sudo find /var/www/ampache -type d -exec chmod 755 {} \;
      sudo find /var/www/ampache -type f -exec chmod 644 {} \;
      # Grant write access ONLY where needed (example for config)
      sudo chmod -R u+w /var/www/ampache/config # Grant write to owner (www-data)
      # Repeat u+w for cache/, log/, etc.
      
      Note: The exact commands might need adjustment based on your setup and security requirements.
  5. Verify Database Connection: Double-check the credentials in config/ampache.cfg.php. Try connecting to the database manually from the server using the same credentials: mysql -h <hostname> -u <ampache_user> -p <ampache_db>
  6. Check Web Server Configuration: Use sudo nginx -t or sudo apachectl configtest to validate syntax. Review the root or alias directives and PHP handling configuration (fastcgi_pass for Nginx, mod_php or PHP-FPM setup for Apache).
  7. Check SELinux/AppArmor: If applicable, temporarily set to permissive mode (sudo setenforce 0 for SELinux, sudo aa-complain /path/to/profile for AppArmor) to see if the issue resolves. If it does, you need to create appropriate security policies (consult SELinux/AppArmor documentation). Check audit logs (/var/log/audit/audit.log or /var/log/syslog).

Catalog Scanning Failures (File Formats, Permissions)

Symptoms:

  • Catalog scan starts but never finishes or finishes instantly without adding music.
  • Music files known to be in the catalog path do not appear in the Ampache library.
  • Scan log shows errors like "Permission denied," "Unsupported format," or database errors.

Common Causes:

  1. Filesystem Permissions (Again!): The web server user (running the scan process) must have read access to the music directory and all subdirectories and files within it. This is distinct from the Ampache application file permissions.
  2. Incorrect Catalog Path: Typo or incorrect case in the path specified in Ampache's catalog settings (Linux paths are case-sensitive). If using Docker, the path specified must be the path inside the container, not the host path.
  3. Unsupported File Formats/Codecs: Ampache might not recognize the file type or the specific audio codec used within the container (e.g., obscure formats, DRM-protected files).
  4. Corrupted Media Files or Tags: Malformed audio files or severely corrupted metadata tags (ID3, Vorbis Comments, etc.) can sometimes cause the scanner to crash or skip the file.
  5. Database Issues: Problems writing the scanned metadata to the Ampache database (disk space full, database errors, incorrect table schema).
  6. ffmpeg/ffprobe Issues: If Ampache relies on ffprobe (part of ffmpeg) to gather detailed media information, problems with the ffmpeg installation or its ability to parse the file can halt scanning.
  7. Catalog Rules: Misconfigured catalog rules might be unintentionally excluding the files you expect to see.

Troubleshooting Steps:

  1. Verify Music Directory Permissions:
    • Identify the web server user (as in Installation Troubleshooting).
    • Check read permissions on the music path (e.g., /srv/music):
      sudo -u www-data ls -l /srv/music/some_artist/some_album/ # Try listing contents as the web server user
      sudo -u www-data head -c 1 /srv/music/some_artist/some_album/track.mp3 > /dev/null # Try reading the start of a file
      
    • If commands fail with "Permission denied," fix the permissions. Ensure the web server user has read (r) and execute (x) permissions on all directories in the path, and read (r) permission on the files. A common fix is ensuring the user is in the correct group that owns the files, or using ACLs (Access Control Lists). Example (adding www-data to the your_music_group): sudo usermod -a -G your_music_group www-data. You might need to adjust directory/file group ownership (chgrp) and permissions (chmod g+rx for directories, chmod g+r for files).
  2. Check Ampache Logs: Examine log/ampache.log (or similar) specifically during or after a catalog scan. Look for errors mentioning specific file paths, permissions, or database issues. Increase log verbosity in Ampache settings if needed.
  3. Verify Catalog Path: Double-check the path in Admin -> Catalogs -> Edit Catalog. Ensure it's the correct absolute path, case-sensitive, and (if using Docker) the container path.
  4. Test with a Small Subset: Create a new temporary catalog pointing to a directory with only a few known-good MP3 files. If this scans correctly, the issue likely lies with specific files or the structure of your main library.
  5. Check File Formats: Ensure your files are in formats generally supported by Ampache (MP3, AAC, Ogg Vorbis, Opus, FLAC are usually safe).
  6. Check for Corrupted Files/Tags: Use a dedicated tagging tool (like MusicBrainz Picard, kid3-cli, or ffmpeg/ffprobe) to inspect the metadata of files that aren't appearing. Try re-saving the tags or, in extreme cases, re-encoding the file.
    # Use ffprobe to check a file's integrity and streams
    ffprobe -v error -show_format -show_streams "/srv/music/path/to/problematic/file.flac"
    
  7. Review Catalog Rules: Temporarily disable all catalog rules for the problematic catalog and re-scan. If files appear now, re-enable rules one by one to find the culprit.
  8. Check Database Status: Ensure the database server is running and the disk partition it uses isn't full (df -h). Check database logs if accessible.

Playback Issues (Transcoding, Network)

Symptoms:

  • Clicking play does nothing.
  • Playback starts but stops after a few seconds.
  • Audio is garbled, stuttering, or silent.
  • Error messages in the web UI or client app related to playback failure.

Common Causes:

  1. Transcoding Failure:
    • ffmpeg not installed or not found by Ampache (incorrect path in settings).
    • ffmpeg command defined in the transcoding template is incorrect or failing.
    • The specific codec needed for transcoding isn't supported by your ffmpeg build.
    • Insufficient server CPU resources to transcode in real-time.
    • Permissions issue writing to the transcode cache directory.
  2. Network Issues:
    • Insufficient bandwidth between the server and client (especially for high-bitrate or direct streaming).
    • Network latency or packet loss causing interruptions.
    • Firewall blocking the streaming connection (less common if browsing works, but possible with complex firewall rules).
    • Reverse proxy configuration issues (e.g., buffering settings, timeouts).
  3. Client/Browser Issues:
    • Browser doesn't support the audio format/codec being streamed (especially relevant for HTML5 player if no transcoding is selected).
    • Client app bug or incompatibility with the specific stream format.
  4. Ampache Configuration: Incorrect streaming settings (e.g., wrong MIME type specified for a transcode template).
  5. SSL/HTTPS Issues (with Reverse Proxy): Mixed content warnings, certificate errors, or reverse proxy not forwarding headers correctly can sometimes interfere with playback initiation.

Troubleshooting Steps:

  1. Test Direct Streaming vs. Transcoding:
    • Try playing a known-good MP3 file directly using the web UI or a client configured for "Original" quality or a very high bitrate (to discourage transcoding). Does it work?
    • Try forcing transcoding by selecting a low bitrate (e.g., 96kbps) in the client or web UI playback settings. Does that work?
    • This helps isolate whether the issue is with direct streaming or the transcoding process.
  2. Check ffmpeg (If Transcoding Fails):
    • Verify ffmpeg is installed and in the system PATH or specified correctly in Ampache settings.
    • Run ffmpeg -version on the server.
    • Check Ampache logs (log/ampache.log) for errors mentioning ffmpeg during playback attempts.
    • Monitor server CPU usage (top, htop) during a transcode attempt. Is it maxing out?
    • Check permissions on the transcode cache directory (if configured).
    • Manually test the ffmpeg command from the failing transcoding template on a sample file via the command line to see if it produces errors.
  3. Check Network:
    • Run a bandwidth test (e.g., speedtest-cli on server/client, or iperf3) between the client and server if possible.
    • Use ping and mtr (or traceroute) from the client to the server to check latency and packet loss.
    • Simplify the network path (e.g., test on local Wi-Fi vs. over the internet/VPN).
  4. Check Browser Developer Console: If using the web UI, open the browser's developer tools (F12), go to the "Network" tab, and try playing a track. Look for failed requests (e.g., 404 Not Found, 500 Internal Server Error) related to the audio stream URL. Check the "Console" tab for JavaScript errors.
  5. Check Reverse Proxy Logs & Config: If using a reverse proxy, check its access and error logs (/var/log/nginx/access.log, /var/log/nginx/error.log). Ensure proxy_buffering off; is set for the Ampache location block, as buffering can interfere with continuous streams. Check timeouts. Ensure X-Forwarded-Proto is set to https.
  6. Try Different Clients/Browsers: Does the problem occur in Firefox, Chrome, DSub, Clementine? If it works in one but not another, the issue is likely client-specific.
  7. Simplify Audio File: Try playing a very standard, widely compatible file (e.g., a CBR 128kbps MP3).

Client Connection Problems (API Keys, Firewall)

Symptoms:

  • Mobile/desktop client (DSub, Clementine, etc.) cannot connect to the server.
  • Error messages like "Connection refused," "Host not found," "Invalid username/password," "API error."

Common Causes:

  1. Incorrect Server URL: Typo, wrong protocol (HTTP vs. HTTPS), incorrect port, or using a local IP address when trying to connect from the internet (or vice-versa).
  2. Firewall Blocking: Server firewall or router firewall blocking the Ampache port (e.g., 8080 if direct, 443 if behind HTTPS reverse proxy).
  3. User Permissions: API access not enabled for the specific user in Ampache (Admin -> Users -> Edit User -> Permissions -> Allow API Access / Subsonic).
  4. Incorrect Username/Password: Simple typo in credentials entered into the client.
  5. Reverse Proxy Issues: Proxy not configured correctly, not running, or not forwarding requests properly to the Ampache backend. DNS resolution issues for the domain name.
  6. API Disabled Globally: Subsonic API support might be disabled in Ampache's system settings.
  7. SSL Certificate Issues: If using HTTPS, an invalid, expired, or self-signed certificate (unless the client is configured to ignore errors, which is insecure) will cause connection failure.
  8. Legacy Auth vs. API Key: Mismatch between client authentication method and server expectation.

Troubleshooting Steps:

  1. Verify Server Reachability: From the client device, try opening the Ampache server URL in a web browser.
    • If it works: The server is reachable, and the issue is likely with credentials, API permissions, or the client app itself.
    • If it fails: The problem is network-level (URL, DNS, firewall, server down).
  2. Check URL, Username, Password: Meticulously re-type the server URL (including http:// or https:// and the correct port, if needed), username, and password in the client settings. Remember usernames might be case-sensitive.
  3. Check Firewall: Ensure the necessary port (e.g., 443 for HTTPS via proxy) is allowed on the server's firewall (sudo ufw status) and forwarded on your router if connecting from the internet.
  4. Verify User API Permissions: Log in to Ampache as admin, go to Users, edit the user account, and confirm "Allow API Access / Subsonic" is checked.
  5. Check Global API Settings: Go to Admin -> System -> API Clients (or similar) and ensure the Subsonic provider is enabled.
  6. Check Ampache Logs: Look for failed login attempts or API errors around the time the client tries to connect.
  7. Check Reverse Proxy Logs: If using a proxy, check its logs for errors related to the connection attempt. Ensure the proxy is running (systemctl status nginx).
  8. Test with curl (Advanced): Use curl from the client machine (if possible) or another machine that should be able to reach the server to test the API endpoint directly:
    # Replace placeholders - use HTTP/port or HTTPS/domain as appropriate
    # Use -k for curl to ignore SSL errors (for testing self-signed certs ONLY)
    curl "https://ampache.yourdomain.com/rest/ping.view?u=testuser&p=TestPassword123&v=1.16.1&c=curl-test&f=xml"
    # Expected successful response (XML):
    # <?xml version="1.0" encoding="UTF-8"?>
    # <subsonic-response xmlns="http://subsonic.org/restapi" status="ok" version="1.16.1">
    # </subsonic-response>
    
    If curl fails, it confirms a network, firewall, proxy, or server-side issue. If curl succeeds but the app fails, the issue is likely within the app's specific configuration or handling.
  9. Try Legacy Auth: If the client has an option for "Legacy Authentication" or "Password Auth," try toggling it.

Workshop - Diagnosing and Fixing a Catalog Scan Issue

Scenario: You've added a new album directory (/srv/music/NewArtist/NewAlbum) containing FLAC files to your music library. You run a catalog update in Ampache ("Add, Update & Clean"), but the new album and artist do not appear in the library.

Goal: Systematically diagnose why the new music isn't being added and fix the underlying issue.

Assumptions:

  • Your Ampache server is running.
  • You have admin access to Ampache and SSH/command-line access to the server.
  • Your main music catalog in Ampache points to /srv/music.
  • The web server user is www-data.

Steps:

  1. Initial Verification (Sanity Check):

    • Check Path in Ampache: Log in to Ampache, go to Admin -> Catalogs -> Edit your music catalog. Verify the path is exactly /srv/music. Check for typos or case sensitivity issues.
    • Check Files Exist: On the server's command line, verify the files are actually there:
      ls -l /srv/music/NewArtist/NewAlbum/
      
      You should see your .flac files listed. Note the owner and group.
  2. Check Filesystem Permissions: This is the most likely culprit.

    • Test Read Access as www-data: Try to list the directory and read a file as the web server user:
      sudo -u www-data ls -l /srv/music/NewArtist/NewAlbum/
      sudo -u www-data head -c 1 /srv/music/NewArtist/NewAlbum/some_track.flac > /dev/null
      
    • Interpret Results:
      • If both commands succeed without error: Basic read permissions are likely okay. Proceed to Step 3.
      • If either command shows "Permission denied": This is the problem!
    • Fixing Permissions (if denied):
      • Examine the output of ls -l /srv/music/NewArtist/ and ls -l /srv/music/NewArtist/NewAlbum/. Who owns the directories and files? What are the permissions?
      • Let's assume the files are owned by your_user:your_group and have permissions like drwxr-xr-x (755) for directories and -rw-r--r-- (644) for files. For www-data to read them, it needs r and x on the directories and r on the files.
      • Option A (Recommended): Add www-data to the group. If your music files consistently belong to a group (e.g., media or your_group), add the www-data user to that group:
        # Replace your_group with the actual group name
        sudo usermod -a -G your_group www-data
        # Log out and log back in OR restart the server/service for group changes to take effect fully.
        # Then, ensure the group has read/execute on directories and read on files:
        sudo find /srv/music/NewArtist -type d -exec chmod g+rx {} \;
        sudo find /srv/music/NewArtist -type f -exec chmod g+r {} \;
        sudo chgrp -R your_group /srv/music/NewArtist # Ensure correct group ownership
        
      • Option B (Simpler but less ideal): Change Ownership. Make www-data the owner or group owner (less secure if other processes don't need write access):
        # Example: Change group ownership to www-data
        sudo chown -R your_user:www-data /srv/music/NewArtist
        sudo find /srv/music/NewArtist -type d -exec chmod 750 {} \; # rwxr-x---
        sudo find /srv/music/NewArtist -type f -exec chmod 640 {} \; # rw-r-----
        
      • After fixing permissions, re-run the test commands from step 2. They should now succeed.
  3. Check Ampache Logs During Scan:

    • In Ampache Web UI: Go to Admin -> System -> View Logs (or similar). Clear the log if possible.
    • Trigger the catalog scan again (Admin -> Catalogs -> Update Now for /srv/music). Choose "Add, Update & Clean".
    • Refresh the Ampache log viewer immediately after the scan finishes (or while it's running).
    • Look for any ERROR or WARNING messages related to /srv/music/NewArtist or specific .flac files. Common messages:
      • "Permission denied" (confirms step 2 if missed).
      • "Unsupported format" or errors mentioning ffmpeg/ffprobe.
      • "Skipping file due to rule..."
      • Database errors (e.g., "Unable to insert...").
  4. Address Log Findings:

    • Permission Errors: Go back to Step 2.
    • Format/FFmpeg Errors: Ensure ffmpeg is installed correctly. Try analyzing one of the FLAC files with ffprobe -v error -show_format -show_streams /path/to/file.flac. Does it show errors? The file might be corrupt, or your ffmpeg might lack FLAC support (unlikely but possible).
    • Rule Errors: Go to Admin -> Catalogs -> Edit Catalog -> Rules. Are there any rules defined that might accidentally exclude .flac files or the NewArtist directory? Temporarily disable all rules and try scanning again.
    • Database Errors: Check database status, disk space (df -h), and database logs.
  5. Re-Scan and Verify:

    • After addressing the likely cause identified in the previous steps (most often permissions), trigger the catalog scan one more time.
    • Once the scan completes, navigate to the "Artists" or "Albums" section in Ampache. Check if "NewArtist" and "NewAlbum" now appear. Try searching for them.

By following these steps, you systematically move from the most common issues (permissions, paths) to more specific ones (logs, file integrity, rules), allowing you to pinpoint and resolve the reason your new music wasn't being cataloged.

Conclusion

Setting up and managing Ampache offers a rewarding journey into the world of self-hosted music streaming. You've progressed from understanding the core concepts and performing a basic installation to mastering user management, client connections, transcoding, advanced cataloguing, secure remote access via reverse proxies, and essential troubleshooting techniques.

By hosting Ampache yourself, you gain unparalleled control over your music library, ensuring privacy, preserving audio quality, avoiding subscription fees, and accessing your entire collection from anywhere. While the initial setup requires effort, the result is a personalized, powerful, and flexible music streaming service tailored precisely to your needs.

The skills acquired – managing Linux systems, configuring web servers and databases, understanding network protocols and security principles, and working with APIs – are valuable assets in many technical domains. Ampache serves not only as a practical tool for music enjoyment but also as an excellent platform for continuous learning and experimentation within the broader self-hosting landscape. Keep exploring its features, stay updated with new releases, and enjoy the freedom of your personal music cloud.