How To Install Mastodon on Ubuntu 24.04 LTS
Mastodon has emerged as a popular decentralized social platform, offering a unique microblogging experience within the Fediverse. Its open-source nature attracts many enthusiasts who want more control and privacy. Installing Mastodon on Ubuntu 24.04 LTS provides a reliable environment and long-term support from Canonical. Ubuntu’s robust ecosystem, stability, and comprehensive documentation make it a prime choice for this setup.
This guide delves into every step required for configuring Mastodon on Ubuntu 24.04 LTS. Successful installation involves setting up server prerequisites, dependencies, databases, web servers, and system services. Configuration details entail domain name pointing, SSL certificates, environment variables, and user permission management. By following the step-by-step instructions, newcomers and experienced administrators alike can deploy a Mastodon instance that is efficient, secure, and ready to scale.
Although it is straightforward once the build process is complete, challenges can arise during installation or updates. Gathering detailed information and resolving potential conflicts in advance helps prevent downtime. An effectively configured Mastodon server fosters a stable and enjoyable user experience, allowing anyone to join the Fediverse. The following sections outline everything from the initial server preparation to post-installation best practices, ensuring confidence and clarity at each stage.
1. Introduction
Mastodon is a federated social media platform often compared to microblogging services, but with a distinctly user-centric approach. Instead of relying on a single network owner, it empowers communities to communicate across interconnected instances. This decentralized design is built on open protocols, such as ActivityPub, ensuring compatibility across multiple services. Installing Mastodon on Ubuntu 24.04 LTS merges the strengths of both technologies, granting a high degree of customization and reliability.
Ubuntu 24.04 LTS extends long-term support, guaranteeing stability for connected applications. Over the next several years, security patches and updates will keep the system safe. The synergy between Mastodon’s decentralized architecture and Ubuntu’s well-maintained operating system significantly reduces overhead in the long run.
A suitable server environment is crucial before installation. A domain name is required for federation. Adequate mail server support is necessary, since Mastodon depends on email confirmations for user registration. Familiarity with the Linux command line helps navigate the setup and troubleshooting processes. Additionally, installing Mastodon may demand basic knowledge of web servers, DNS configuration, and system security. This introduction sets the stage for deeper exploration in subsequent sections.
2. Prerequisites
Carefully reviewing prerequisites ensures that the hosting environment is prepared for a smooth Mastodon installation. Meeting system requirements, setting up DNS, and confirming email delivery capabilities prevent future issues. Thoroughly verifying each requirement saves time and resources by reducing configuration conflicts.
2.1 System Requirements
Mastodon typically performs best on servers with a minimum of 2 CPU cores and 4 GB of RAM. Sufficient storage is essential for user content (images, videos, and attachments). Depending on user capacity, scaling the storage configuration avoids potential resource bottlenecks. Ubuntu 24.04 LTS should be fully installed on a server or virtual machine for maximum compatibility.
A domain name is also vital. Ensure the domain’s DNS settings are pointed to the server’s IP address. Subdomains (e.g., mastodon.example.com) offer neat organization and are often used for Mastodon. The domain name remains important for SSL configuration and for enabling external communication with other Mastodon instances.
2.2 SMTP or Email Delivery Setup
Mastodon depends on outgoing emails for user sign-ups, password resets, and notifications. Many administrators opt for services such as Mailgun, SendGrid, or a self-managed SMTP server. Whichever route is chosen, confirm that it meets essential sending requirements. SPF, DKIM, and DMARC records boost reputation and reduce spam flags.
To avoid email deliverability problems, gather SMTP credentials in advance. The final Mastodon configuration includes these details for proper email routing. Authentication credentials should remain private and secure.
2.3 Root Access Verification
Gaining administrative privileges is often necessary to install packages, configure services, and manage system-level changes. Root access or sudo permissions allow full control over the server. Verify user permissions by running:
sudo -v
If no error messages appear, continue. Otherwise, modify user privileges or switch to a root account to ensure an uninterrupted installation.
3. Server Preparation
The server environment lays the groundwork for a stable Mastodon instance. Properly configured firewalls, updated systems, and fundamental security steps keep the server safe from threats. Investing extra time in these preparations pays off in the long term, minimizing interruptions or vulnerabilities.
3.1 System Updates and Upgrades
Begin by refreshing the server’s package index and upgrading any outdated software. Keeping Ubuntu 24.04 LTS current extends security protections and ensures stable packages. Use these commands:
sudo apt update
sudo apt upgrade -y
Depending on available updates, the process may take some time. Reboots are occasionally required to apply certain kernel-level upgrades. After this step, the foundation is up-to-date and secure.
3.2 Firewall Configuration
Ubuntu servers often come with UFW (Uncomplicated Firewall) installed. If not, install and enable UFW to control incoming traffic:
sudo apt install ufw -y
sudo ufw enable
Open relevant ports, such as SSH (22), HTTP (80), and HTTPS (443):
sudo ufw allow 22
sudo ufw allow 80
sudo ufw allow 443
sudo ufw status
Confirm that the firewall rules are in place, ensuring only necessary connections are permitted. Restricting improper inbound traffic helps maintain server integrity.
3.3 Essential Security Measures
Additional security steps offer extra reassurance in server protection. For instance, disabling password-based SSH logins and opting for key-based authentication reduces brute-force risks. Configuring fail2ban to limit repeated login attempts adds another layer of security. Regularly applying patches while maintaining secure credentials fosters a robust environment for Mastodon.
Administrators are also encouraged to monitor system logs for suspicious activity. Tools such as logwatch automate daily log scanning. Coupled with intrusion detection software, these measures fortify the server. A stable foundation at this stage prevents complications once the application stack is layered on top.
4. Database Setup
Mastodon uses PostgreSQL by default to handle data storage. Reliable performance and SQL compliance make PostgreSQL an excellent choice for large-scale social media applications. Correctly configuring the database ensures efficient user management, content indexing, and data retrieval.
4.1 Installing PostgreSQL
Install PostgreSQL from official Ubuntu repositories. The following commands fetch and set up the database:
sudo apt install postgresql postgresql-contrib -y
After installation, the PostgreSQL service should start automatically. If it does not, initiate it manually:
sudo systemctl enable postgresql
sudo systemctl start postgresql
4.2 User Creation and Database Initialization
Create a dedicated PostgreSQL user and database for Mastodon. Switch to the postgres user and run:
sudo -i -u postgres
createuser mastodon --createdb --pwprompt
createdb mastodon -O mastodon
When prompted, provide a secure password. Keeping separate credentials for Mastodon ensures an extra line of defense. Exit the postgres user shell once the process is done.
4.3 Security Permissions
Confirm that the newly created user and database permissions align with best practices. Adjust pg_hba.conf only if specialized authentication methods are needed. Otherwise, default configurations generally suffice for an initial Mastodon deployment.
If certain advanced security policies or multi-factor authentication are desired, tailor PostgreSQL’s settings accordingly. Implementation of roles and stricter access controls can also fortify an instance that handles large amounts of user data.
5. Core Installation
With the server prepared and PostgreSQL configured, the next stage focuses on downloading and setting up Mastodon’s core files. This part of the process sets the foundation for running the application, including the structure of directories, user permissions, and environment files.
5.1 Creating a Mastodon System User
Mastodon’s security model operates most efficiently with a dedicated system user. Separate privileges minimize the risks associated with running services as root. Create a user named mastodon as follows:
sudo adduser --system --home /home/mastodon --shell /bin/bash mastodon
sudo adduser mastodon sudo
Setting a dedicated home directory organizes the logs and files neatly. Some prefer not granting full sudo access, though this simplifies certain steps. Adjust permissions according to specific security requirements.
5.2 Downloading Source Code
Mastodon is available via its official Git repository. Switch to the mastodon user and clone the repository:
su - mastodon
git clone https://github.com/mastodon/mastodon.git live
cd live
Cloning into a live directory helps keep the application organized. The main branch typically contains the newest stable build, but check release notes if the environment requires a specific version.
5.3 Directory Structure
Within the live directory resides the Mastodon application. Sub-directories include app, config, public, and more. Familiarize yourself with these paths for troubleshooting. Logs and temporary data typically emerge in log and tmp folders, which can be monitored to track performance or detect issues.
6. Dependencies Installation
Mastodon uses Ruby on Rails with Node.js handling certain front-end tasks. Yarn is also needed to manage JavaScript packages effectively. Properly installing and configuring these dependencies is pivotal to performance and stability.
6.1 Ruby Installation and Configuration
Ubuntu repositories contain Ruby, but many prefer the flexibility of rbenv or rvm to control Ruby versions. To keep it straightforward, install Ruby from the package manager first:
sudo apt install ruby-full -y
Confirm the installation:
ruby -v
Ideally, the version aligns with Mastodon’s requirements. If a more recent version is needed, consider specialized version managers for an up-to-date stack.
6.2 Node.js Setup
Node.js supports front-end asset compilation for Mastodon. Acquire the latest Long-Term Support (LTS) version by enabling official NodeSource repositories, or install from Ubuntu’s repository if it meets the needed version. For instance:
sudo apt install nodejs -y
sudo apt install npm -y
Verify success by checking the installed version:
node -v
npm -v
Higher versions ensure that the asset pipeline runs more efficiently.
6.3 Introducing Yarn Package Management
Yarn is used for handling Mastodon’s JavaScript dependencies. Install Yarn and related components:
sudo npm install --global yarn
Switch back to the mastodon user if needed. Then, inside the live directory of Mastodon:
cd /home/mastodon/live
yarn install --pure-lockfile
This command can take some time, depending on network speed and system resources. Once completed, Mastodon’s front-end components are in place and ready to configure.
7. Mastodon Configuration
Mastodon configurations are controlled primarily via an .env.production
file. This environment file stores domain details, database credentials, and email server parameters. Properly populating this file is critical in ensuring the instance’s success and interoperability across the Fediverse.
7.1 Environment Setup
Rename the sample environment file to .env.production, then open and edit it:
cp .env.production.sample .env.production
nano .env.production
In the file, fill in crucial lines:
- LOCAL_DOMAIN (the domain/subdomain used, like mastodon.example.com)
- DB_HOST (usually localhost)
- DB_USER, DB_NAME, and DB_PASS from the earlier PostgreSQL setup
- SMTP_SERVER, SMTP_PORT, SMTP_LOGIN, SMTP_PASSWORD, and SMTP_FROM_ADDRESS
Mastodon also uses secret keys to encrypt sensitive data. If needed, run the built-in rake task:
RAILS_ENV=production bundle exec rake mastodon:generate_secrets
This step populates the environment file with automatically generated keys.
8. Web Server Setup
A properly configured web server ensures user connections are handled efficiently. Nginx typically manages HTTP and HTTPS traffic, acting as a reverse proxy for Mastodon’s internal services. An SSL/TLS certificate is also recommended for encryption, often from Let’s Encrypt.
8.1 Installing and Configuring Nginx
Install Nginx:
sudo apt install nginx -y
Then create a configuration file for Mastodon:
sudo nano /etc/nginx/sites-available/mastodon.conf
Populate it with directives to point to Mastodon’s Rails and streaming services:
server {
listen 80;
server_name mastodon.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
...
}
...
}
Adjust the server_name to match the domain. Once complete:
sudo ln -s /etc/nginx/sites-available/mastodon.conf /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
Verifying the configuration with nginx -t
avoids common syntax mistakes.
8.2 Enabling SSL/TLS Certificate
Obtain a certificate via Let’s Encrypt:
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d mastodon.example.com
Follow the interactive prompts and choose the redirect option. Successful SSL issuance reconfigures Nginx for HTTPS. Renewals occur automatically via certbot. Always confirm that the certificate is valid to maintain user trust and security.
9. Service Configuration
Mastodon relies on background workers and web processes to handle continuous user interactions. Using systemd ensures these processes run at startup and remain stable over time. A structured approach to creating and maintaining these services reduces complexity in managing multiple processes.
9.1 Systemd Service Creation
Create a service file named mastodon-web.service, for instance:
sudo nano /etc/systemd/system/mastodon-web.service
Insert content that specifies the environment and start command. A typical example includes:
[Unit]
Description=Mastodon (web)
After=network.target
[Service]
Type=simple
User=mastodon
WorkingDirectory=/home/mastodon/live
Environment="RAILS_ENV=production"
ExecStart=/usr/bin/bundle exec puma -C config/puma.rb
Restart=always
[Install]
WantedBy=multi-user.target
Repeat this process for streaming and sidekiq. For example, mastodon-streaming.service might have ExecStart=/usr/bin/npm run start
. The sidekiq service handles background jobs, so reference the sidekiq configuration from the Mastodon environment.
9.2 Background Workers Setup
Sidekiq manages tasks like email sending and content processing. A dedicated service file, such as mastodon-sidekiq.service, keeps it distinct from the web interface. Confirm that the user remains mastodon to maintain correct permissions.
[Unit]
Description=Mastodon (sidekiq)
After=network.target
[Service]
Type=simple
User=mastodon
WorkingDirectory=/home/mastodon/live
Environment="RAILS_ENV=production"
ExecStart=/usr/bin/bundle exec sidekiq
Restart=always
[Install]
WantedBy=multi-user.target
9.3 Service Activation
Enable and start the systemd services:
sudo systemctl enable mastodon-web mastodon-sidekiq mastodon-streaming
sudo systemctl start mastodon-web mastodon-sidekiq mastodon-streaming
Check the status to ensure all are successfully running:
systemctl status mastodon-web
systemctl status mastodon-sidekiq
systemctl status mastodon-streaming
If any failures appear, inspect logs for errors. Solutions might involve correcting environment file entries or adjusting the directory structure.
10. Final Steps
With the core services active, Mastodon is nearly ready for usage. A few extra tasks remain, such as database migrations, asset precompilation, and instance registration. These steps cement Mastodon’s functionality, ensuring the instance operates as expected.
10.1 Database Migrations and Precompiling Assets
While in the /home/mastodon/live directory:
RAILS_ENV=production bundle exec rails db:migrate
RAILS_ENV=production bundle exec rails assets:precompile
The above commands set up all tables and relationships, then prepare front-end files for optimal performance. Once finished, any final adjustments to the environment configurations can be applied.
10.2 Administrating the Instance
An administrative account is often needed to manage local users and moderate content. Once Mastodon is running, navigate to https://mastodon.example.com
and register a new account. After signing in, elevate privileges:
RAILS_ENV=production bundle exec rails c
User.find_by(email: "admin@example.com").update!(admin: true)
Swap out admin@example.com for the email used during sign-up. This step grants administrative ownership, providing access to the instance’s moderation and configuration capabilities within the web UI.
10.3 Federation Settings
Mastodon’s fediverse interactions commence once federation is enabled in the settings panel. In the admin area, configure content guidelines, user policies, and whether to allow open registrations. Fine-tuning these features fosters a community that balances accessibility with security. Additionally, review thresholds for reporting suspicious or malicious content.
11. Post-Installation
The Mastodon instance should now function, serving posts, user registrations, and federation requests. However, periodic housekeeping and monitoring fortify ongoing success. A few quick checks and best practices can help the instance remain stable over time.
11.1 Verification and Security Checks
Give the instance a test run by posting from the admin account, verifying emails arrive, and connecting with remote Mastodon servers. Monitoring server logs reveals any immediate issues. Securing backups of the database and environment file proves critical. In case of unexpected disruptions, restoring from a recent backup speeds recovery.
11.2 Ongoing Maintenance
Regularly updating Mastodon captures the latest security patches and feature enhancements. Many administrators schedule updates every few weeks, verifying changes in a staging environment before applying them in production. Observing the official Mastodon GitHub repository or release notes aids in identifying new improvements and potential security fixes.
11.3 Scaling and Troubleshooting
As user activity increases, additional server resources might be necessary. Scaling CPU, RAM, or migrating to more robust hosting can maintain a snappy user experience. Typical troubleshooting efforts include checking logs for database connection issues or investigating delayed job processing. Adjusting the puma worker count or sidekiq concurrency can alleviate performance constraints.
Congratulations! You have successfully installed Mastodon. Thanks for using this tutorial for installing Mastodon social network on Ubuntu 24.04 LTS system. For additional help or useful information, we recommend you check the Mastodon website.