bolt Valebyte VPS from $4/mo — NVMe, 60s deploy.

Get a VPS arrow_forward
eco Beginner Tutorial/How-to

Deploying Mastodon on a VPS

calendar_month Jul 17, 2026 schedule 20 min read visibility 3 views
info

Need a server for this guide? We offer dedicated servers and VPS in 50+ countries with instant setup.

Need a server for this guide?

Deploy a VPS or dedicated server in minutes.

Deploying Mastodon on a VPS: A Complete Guide to Installation and Configuration

TL;DR

In this detailed guide, we will step-by-step set up and deploy our own instance of the decentralized social network Mastodon version 4.4.0 on a Virtual Private Server (VPS) running Ubuntu 24.04 LTS. We will cover all stages, from choosing a suitable server and basic operating system preparation to installing necessary components, configuring the Caddy web server with automatic HTTPS, setting up PostgreSQL 17 and Redis 8 databases, and creating a backup and monitoring system to ensure stable operation.

  • Installing Mastodon 4.4.0 on Ubuntu 24.04 LTS using Ruby 3.4 and Node.js 22 LTS.
  • Configuring PostgreSQL 17 database and caching with Redis 8.
  • Automatic issuance and renewal of SSL certificates using Caddy.
  • Creating a reliable Mastodon data backup system.
  • Recommendations for choosing a VPS configuration and server maintenance.

What we are setting up and why

We will be deploying Mastodon — one of the most popular and functional decentralized social networks in the world. Mastodon is free, open-source software that allows users to create their own federated microblogging platforms, known as "instances". These instances can interact with each other, forming a unified, yet distributed network known as the Fediverse.

Unlike traditional centralized social networks such as X (formerly Twitter) or Facebook, Mastodon gives you full control over your data, community rules, and platform functionality. By deploying your own Mastodon instance on a VPS, you gain independence from corporate solutions, the ability to form a unique community according to your rules, and ensure a high level of privacy for your users.

Ultimately, you will get a fully functional Mastodon instance, accessible via your domain name, ready for user registration and integration with other Fediverse instances. This is an ideal solution for small teams, interest-based communities, personal blogs, or even for launching a public platform with thousands of users, if you are ready for scaling.

There are alternatives in the form of cloud solutions or managed hosting for Mastodon, which might seem simpler at first glance. However, a self-hosted option on a VPS offers maximum flexibility, control over resources and data, and long-term cost savings, especially if you plan to scale your instance or integrate it with other services. You avoid the limitations imposed by managed service providers and gain full root access for fine-tuning and optimization.

What VPS configuration is needed for this task

Choosing a suitable VPS for Mastodon depends on the anticipated load. Mastodon is a resource-intensive application, requiring significant amounts of RAM and a fast disk subsystem, especially with active use. The requirements below are relevant for 2026, considering trends in resource consumption growth.

Minimum requirements for a small instance (up to 50 active users)

  • CPU: 2 cores (modern Intel Xeon E5/E7 or AMD EPYC).
  • RAM: 4 GB DDR4. Most of the memory will be used by PostgreSQL, Redis, and the Ruby on Rails application itself.
  • Disk: 80 GB NVMe SSD. A fast disk is critically important for database performance and media file storage. HDD is not recommended.
  • Network: 100 Mbps symmetric channel. This will be sufficient for a small instance.

Recommended configuration for a medium instance (50-500 active users)

  • CPU: 4 cores (high-performance Intel Xeon Scalable or AMD EPYC).
  • RAM: 8-16 GB DDR4. This will allow comfortable handling of peak loads and caching more data.
  • Disk: 200-400 GB NVMe SSD. A significant increase in volume for media files and potential database growth.
  • Network: 1 Gbps symmetric channel. Necessary for fast media file loading and handling a large number of requests.

Specific VPS plan for the task (example)

To start working with Mastodon and maintain an instance for up to 100-200 active users, a VPS with the following characteristics will be the optimal choice:

Parameter Value
Processor 4 vCPU (modern Intel Xeon or AMD EPYC)
RAM 8 GB DDR4
Disk Space 200 GB NVMe SSD
Network Channel 1 Gbps

You can get a VPS with the specified characteristics to ensure stable operation of your Mastodon instance with room for growth.

When a dedicated server is needed, not a VPS

A dedicated server becomes necessary when your Mastodon instance starts serving thousands of active users, generates huge volumes of media files, or if you plan to run additional resource-intensive services on it. A dedicated server provides exclusive access to all physical resources (CPU, RAM, disk), which eliminates "noisy neighbors" and ensures maximum performance and stability. For Mastodon with more than 1000 active users, especially with a large amount of media content, a dedicated server with 8+ cores, 32+ GB RAM, and several TB of NVMe SSD will be a justified choice.

Location: what it affects

Choosing a VPS location has several important aspects:

  • Ping (latency): The closer the server is to your primary audience, the lower the ping will be and the faster the content will load. This is critically important for comfortable user interaction with the platform.
  • Legislation: Different countries have different data storage and privacy laws. Make sure the chosen location complies with your requirements and those of your community.
  • Cost: VPS prices can vary depending on the region.
  • CDN Availability: If you plan to use a CDN for media files, choose a location with good Points of Presence (PoP) for your chosen CDN provider.

Server Preparation

After gaining access to your new VPS with Ubuntu 24.04 LTS, the first step is to perform basic security configuration and install necessary utilities. All commands are executed as the root user or using sudo.

System Update

Always start by updating the package list and the system itself to ensure all components are up-to-date and have the latest security fixes.


sudo apt update             # Обновление списка доступных пакетов
sudo apt upgrade -y         # Обновление всех установленных пакетов до последних версий
sudo apt autoremove -y      # Удаление устаревших пакетов, которые больше не нужны
sudo apt clean              # Очистка кэша пакетов

Creating a new user with sudo privileges

Working as the root user is unsafe. Create a new user and grant them sudo privileges.


sudo adduser mastodonuser     # Создание нового пользователя, например, "mastodonuser"
sudo usermod -aG sudo mastodonuser # Добавление пользователя в группу sudo

Now, exit the root session and log in as the new user:


exit                        # Выход из текущей сессии root
ssh mastodonuser@ваш_ip_сервера # Вход под новым пользователем

Setting up SSH keys (recommended)

To enhance security, it is recommended to use SSH keys instead of passwords. If you haven't set them up yet, do so on your local machine, then copy the public key to the server.


# На вашей локальной машине:
ssh-keygen -t ed25519 -C "[email protected]" # Создание нового SSH-ключа (если нет)
ssh-copy-id mastodonuser@ваш_ip_сервера      # Копирование публичного ключа на сервер

After successfully copying the key, disable password authentication in /etc/ssh/sshd_config for the root user and allow only SSH keys for all users:


sudo nano /etc/ssh/sshd_config

Find and change the following lines:


#PasswordAuthentication yes
PasswordAuthentication no
PermitRootLogin no
ChallengeResponseAuthentication no
UsePAM yes

Save changes (Ctrl+X, Y, Enter) and restart the SSH service:


sudo systemctl restart sshd

Configuring the Firewall (UFW)

Enable the UFW firewall and allow only the necessary ports: SSH (22), HTTP (80), and HTTPS (443).


sudo apt install ufw -y     # Установка UFW, если не установлен
sudo ufw default deny incoming # Запретить все входящие соединения по умолчанию
sudo ufw default allow outgoing # Разрешить все исходящие соединения по умолчанию
sudo ufw allow OpenSSH      # Разрешить SSH (порт 22)
sudo ufw allow http         # Разрешить HTTP (порт 80)
sudo ufw allow https        # Разрешить HTTPS (порт 443)
sudo ufw enable             # Включить брандмауэр (подтвердите 'y')
sudo ufw status verbose     # Проверка статуса брандмауэра

Installing Fail2Ban

Fail2Ban helps protect the server from brute-force attacks by blocking IP addresses from which failed login attempts occur.


sudo apt install fail2ban -y # Установка Fail2Ban
sudo systemctl enable fail2ban # Включение автозапуска службы
sudo systemctl start fail2ban  # Запуск службы
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local # Создание локального конфига
sudo nano /etc/fail2ban/jail.local # Редактирование конфига для настройки

In the jail.local file, you can configure parameters, for example, increase the block time or change the number of attempts. For starters, standard settings are sufficient.


# В [DEFAULT] секции
bantime = 1h        # Время блокировки (1 час)
findtime = 10m      # Период, за который учитываются попытки (10 минут)
maxretry = 5        # Максимальное количество попыток до блокировки

Save changes and restart Fail2Ban:


sudo systemctl restart fail2ban

Installing basic utilities

Let's install a few useful utilities that may be needed during the setup process and further maintenance.


sudo apt install curl wget git htop unzip -y # Установка curl, wget, git, htop, unzip

Now your server is ready for the installation of the main Mastodon software.

Software Installation — Step-by-Step

Mastodon requires several key components to operate: a PostgreSQL database, a Redis cache server, a Ruby runtime environment, Node.js for the frontend, and the Caddy web server. We will use the current software versions available in 2026.

1. Installing PostgreSQL 17

Mastodon uses PostgreSQL as its primary database. We will install version 17, which will be current and stable in 2026.


# Добавление репозитория PostgreSQL 17
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" > /etc/apt/sources.list.d/pgdg.list'
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -

# Обновление списка пакетов и установка PostgreSQL 17
sudo apt update
sudo apt install postgresql-17 postgresql-client-17 -y

# Проверка статуса службы PostgreSQL
sudo systemctl enable postgresql
sudo systemctl start postgresql
sudo systemctl status postgresql

Let's create the database user and the database itself for Mastodon. Replace ваш_пароль_бд with a strong password.


sudo -u postgres psql -c "CREATE USER mastodon WITH PASSWORD 'ваш_пароль_бд';"
sudo -u postgres psql -c "CREATE DATABASE mastodon_production OWNER mastodon;"

2. Installing Redis 8

Redis is used by Mastodon for caching, queues, and other tasks requiring fast in-memory data access. We will install version 8.


# Установка Redis 8 из официального репозитория Ubuntu (или стороннего, если 8 не в LTS)
sudo apt install redis-server -y

# Проверка статуса службы Redis
sudo systemctl enable redis-server
sudo systemctl start redis-server
sudo systemctl status redis-server

Ensure that Redis is configured to listen only on local connections (which is the default), and that data persistence is enabled (appendonly yes in /etc/redis/redis.conf). This is important to prevent data loss in case of a restart.

3. Installing Nginx (for some configurations, but we use Caddy)

Although we will be using Caddy as the primary web server, Nginx is often used as a proxy or for serving static files. We will install it in case you want to use it in the future, but it is not mandatory for this guide.


sudo apt install nginx -y # Установка Nginx
sudo systemctl enable nginx # Включение автозапуска Nginx
sudo systemctl start nginx # Запуск Nginx
sudo ufw allow 'Nginx Full' # Разрешение HTTP/HTTPS через UFW для Nginx

4. Installing Ruby 3.4 and Bundler

Mastodon is written in Ruby on Rails. It requires a current version of Ruby, such as 3.4, and the Bundler dependency manager. We will use rbenv for managing Ruby versions, which is a good practice.


# Установка зависимостей для rbenv и Ruby
sudo apt install git curl autoconf bison build-essential libssl-dev libyaml-dev libreadline-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm-dev -y

# Установка rbenv
git clone https://github.com/rbenv/rbenv.git ~/.rbenv
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
source ~/.bashrc

git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build
echo 'export PATH="$HOME/.rbenv/plugins/ruby-build/bin:$PATH"' >> ~/.bashrc
source ~/.bashrc

# Установка Ruby 3.4.0
rbenv install 3.4.0
rbenv global 3.4.0
ruby -v # Проверка установленной версии Ruby

# Установка Bundler
gem install bundler --no-document

5. Installing Node.js 22 LTS and Yarn

Mastodon uses Node.js for compiling frontend assets and Yarn as a JavaScript package manager.


# Установка Node.js 22 LTS (используем nvm для гибкости)
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 22
nvm use 22
node -v # Проверка версии Node.js
npm -v  # Проверка версии npm

# Установка Yarn (классической версии 1.x)
npm install --global yarn
yarn -v # Проверка версии Yarn

6. Installing ImageMagick and FFmpeg

These utilities are necessary for Mastodon to process images, videos, and audio.


sudo apt install imagemagick ffmpeg libimage-exiftool-perl -y

7. Creating the Mastodon Directory

Let's create the directory where Mastodon will be installed and assign ownership to our user mastodonuser.


sudo mkdir -p /var/www/mastodon
sudo chown mastodonuser:mastodonuser /var/www/mastodon
cd /var/www/mastodon

8. Cloning the Mastodon Repository

We will download the Mastodon source code from the official GitHub repository. We will install version 4.4.0.


git clone https://github.com/mastodon/mastodon.git .
git checkout v4.4.0 # Переключение на стабильную версию 4.4.0

9. Installing Mastodon Dependencies

Let's install the Ruby gems and JavaScript dependencies required for Mastodon to function.


bundle install --without development test # Установка Ruby-гемов
yarn install --pure-lockfile             # Установка JavaScript-зависимостей

10. Compiling Frontend Assets

Let's compile the JavaScript and CSS files required for the Mastodon user interface.


RAILS_ENV=production bundle exec rails assets:precompile

At this stage, the main components are installed. Next, we will proceed to configuration.

Configuration

After installing all components, it is necessary to configure Mastodon, the database, the web server, and ensure HTTPS is working.

1. Configuring the Mastodon Environment File (.env.production)

Mastodon uses environment variables to store configuration, especially sensitive data such as passwords and API keys. Let's create the .env.production file.


cp .env.production.sample .env.production
nano .env.production

Here are the main parameters that need to be configured. Replace the values in angle brackets with your own:


# Основные настройки
LOCAL_DOMAIN=<ваш_домен>             # Например, mastodon.example.com
PUBLIC_WEB_BASE_URL=https://<ваш_домен> # Полный URL вашего инстанса

# Настройки базы данных PostgreSQL
DB_HOST=localhost
DB_PORT=5432
DB_USER=mastodon
DB_NAME=mastodon_production
DB_PASS=<ваш_пароль_бд>

# Настройки Redis
REDIS_HOST=localhost
REDIS_PORT=6379

# Настройки электронной почты (SMTP)
# Mastodon использует почту для регистрации, сброса паролей и уведомлений.
# Рекомендуется использовать внешний SMTP-сервис (SendGrid, Mailgun, Postmark и т.д.)
SMTP_SERVER=
SMTP_PORT=587
SMTP_LOGIN=<ваш_smtp_логин>
SMTP_PASSWORD=<ваш_smtp_пароль>
SMTP_FROM_ADDRESS=notifications@<ваш_домен>
# SMTP_AUTH_METHOD=plain
# SMTP_ENABLE_STARTTLS_AUTO=true

# Генерация секретных ключей (ВАЖНО!)
# Эти ключи должны быть уникальными и надёжными.
# Генерируйте их командой: bundle exec rake secret
SECRET_KEY_BASE=<сгенерированный_ключ_1>
OTP_SECRET=<сгенерированный_ключ_2>
DEVISE_SECRET=<сгенерированный_ключ_3>

# Ключи для подписи веб-пушей (VAPID)
# Генерируйте их командой: bundle exec rake mastodon:webpush:generate_vapid_key
VAPID_PRIVATE_KEY=<сгенерированный_приватный_ключ>
VAPID_PUBLIC_KEY=<сгенерированный_публичный_ключ>
VAPID_CONTACT_EMAIL=admin@<ваш_домен>

# S3-совместимое хранилище для медиафайлов (рекомендуется для масштабирования)
# Если не используете S3, Mastodon будет хранить файлы локально (по умолчанию).
# S3_ENABLED=true
# S3_BUCKET=<имя_вашего_бакета>
# AWS_ACCESS_KEY_ID=<ваш_access_key_id>
# AWS_SECRET_ACCESS_KEY=<ваш_secret_access_key>
# S3_REGION=<регион_бакета>
# S3_HOSTNAME= # Например, s3.eu-central-1.amazonaws.com
# S3_PROTOCOL=https
# S3_FORCE_PATH_STYLE=true # Для некоторых S3-совместимых хранилищ

To generate secret keys, execute the following commands in the Mastodon directory:


RAILS_ENV=production bundle exec rake secret
RAILS_ENV=production bundle exec rake secret
RAILS_ENV=production bundle exec rake secret
RAILS_ENV=production bundle exec rake mastodon:webpush:generate_vapid_key

Each time, copy the generated key to the corresponding variable in .env.production.

2. Initializing the Mastodon Database

Apply database migrations and create default records.


RAILS_ENV=production bundle exec rake db:migrate
RAILS_ENV=production bundle exec rake db:seed

3. Configuring the Caddy Web Server with HTTPS

Caddy is a modern web server that automatically issues and renews SSL/TLS certificates from Let's Encrypt. This significantly simplifies HTTPS configuration.


# Установка Caddy
sudo apt install -y debian-keyring debian-archive-keyring apt-transport-https
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/gpg.key' | sudo gpg --dearmor -o /usr/share/keyrings/caddy-stable-archive-keyring.gpg
curl -1sLf 'https://dl.cloudsmith.io/public/caddy/stable/debian.deb.txt' | sudo tee /etc/apt/sources.list.d/caddy-stable.list
sudo apt update
sudo apt install caddy -y

# Создание конфигурационного файла Caddy
sudo nano /etc/caddy/Caddyfile

Add the following configuration to /etc/caddy/Caddyfile, replacing ваш_домен with your actual domain:


# Домен вашего Mastodon инстанса
<ваш_домен> {
  # Автоматический HTTPS
  tls admin@<ваш_домен> # Укажите свой административный email для Let's Encrypt

  # Проксирование запросов к приложению Mastodon
  reverse_proxy /api/ localhost:3000
  reverse_proxy /oauth/ localhost:3000
  reverse_proxy /authorize/ localhost:3000
  reverse_proxy /interact/ localhost:3000
  reverse_proxy /main/ localhost:3000
  reverse_proxy /auth/ localhost:3000
  reverse_proxy /admin/ localhost:3000
  reverse_proxy /settings/ localhost:3000
  reverse_proxy /web/ localhost:3000
  reverse_proxy /dist/ localhost:3000
  reverse_proxy /packs/ localhost:3000
  reverse_proxy /assets/ localhost:3000
  reverse_proxy /system/ localhost:3000
  reverse_proxy /api/v/streaming/ localhost:4000 {
    header_up Host {host}
    header_up X-Real-IP {remote_ip}
    header_up X-Forwarded-For {remote_ip}
    header_up X-Forwarded-Proto {scheme}
    websocket
  }
  reverse_proxy /api/v/pleroma/oauth/ localhost:3000
  reverse_proxy /api/v/pleroma/web/ localhost:3000
  reverse_proxy /api/v/activitypub/web/ localhost:3000
  reverse_proxy /api/v/activitypub/oauth/ localhost:3000

  # Отдача статических файлов напрямую
  root  /var/www/mastodon/public
  file_server

  # Заголовок HSTS для безопасности
  header {
    Strict-Transport-Security "max-age=63072000; includeSubDomains; preload"
  }

  # Логирование (опционально)
  log {
    output file /var/log/caddy/mastodon_access.log
    format console
  }
}

Create the directory for Caddy logs if it does not exist:


sudo mkdir -p /var/log/caddy
sudo chown caddy:caddy /var/log/caddy

Check the Caddy configuration and restart the service:


sudo caddy validate --config /etc/caddy/Caddyfile
sudo systemctl reload caddy
sudo systemctl enable caddy
sudo systemctl start caddy
sudo systemctl status caddy

Ensure that your domain points to your VPS's IP address in your DNS settings (A-record).

4. Configuring Systemd for Mastodon

Mastodon consists of several processes (web, streaming, workers) that must run continuously. We will use Systemd to manage them.


sudo cp /var/www/mastodon/dist/mastodon-web.service /etc/systemd/system/
sudo cp /var/www/mastodon/dist/mastodon-sidekiq.service /etc/systemd/system/
sudo cp /var/www/mastodon/dist/mastodon-streaming.service /etc/systemd/system/

# Редактирование файлов служб для указания правильного пользователя
sudo sed -i 's/User=mastodon/User=mastodonuser/g' /etc/systemd/system/mastodon-web.service
sudo sed -i 's/Group=mastodon/Group=mastodonuser/g' /etc/systemd/system/mastodon-web.service
sudo sed -i 's/User=mastodon/User=mastodonuser/g' /etc/systemd/system/mastodon-sidekiq.service
sudo sed -i 's/Group=mastodon/Group=mastodonuser/g' /etc/systemd/system/mastodon-sidekiq.service
sudo sed -i 's/User=mastodon/User=mastodonuser/g' /etc/systemd/system/mastodon-streaming.service
sudo sed -i 's/Group=mastodon/Group=mastodonuser/g' /etc/systemd/system/mastodon-streaming.service

# Перезагрузка Systemd, включение и запуск служб
sudo systemctl daemon-reload
sudo systemctl enable mastodon-web mastodon-sidekiq mastodon-streaming
sudo systemctl start mastodon-web mastodon-sidekiq mastodon-streaming

# Проверка статуса служб
sudo systemctl status mastodon-web
sudo systemctl status mastodon-sidekiq
sudo systemctl status mastodon-streaming

5. Creating the First Administrator

After all services have started, create the first Mastodon administrator.


RAILS_ENV=production bundle exec rake mastodon:setup

Follow the on-screen instructions to create an administrator account. Select "yes" to create the administrator.

6. Verifying Functionality

Open your domain (e.g., https://ваш_домен) in your browser. You should see the Mastodon registration/login page. Verify that HTTPS is working and that the certificate is issued by Let's Encrypt.

You can also check accessibility via curl:


curl -I https://localhost:3000 # Проверка Mastodon Web
curl -I https://localhost:4000 # Проверка Mastodon Streaming
curl -I https://<ваш_домен>    # Проверка доступности через Caddy

If everything is configured correctly, you will see HTTP headers from Mastodon and Caddy.

Backups and Maintenance

Regular backups are a critically important element of any functioning system. For Mastodon, it is necessary to back up the database, media files, and configuration files.

What to Back Up

  • PostgreSQL Database: Contains all user records, posts, notifications, settings, etc. This is the most important part.
  • Media Files: Images, videos, and audio uploaded by users. By default, they are stored in /var/www/mastodon/public/system. If you are using S3-compatible storage, you do not need to back them up locally, as the S3 provider already ensures their preservation.
  • Configuration Files: .env.production and web server configuration files (/etc/caddy/Caddyfile).

Simple Auto-Backup Script (cron + restic)

Restic is an excellent tool for creating encrypted, deduplicated backups. It can store backups locally, on S3, SFTP, and other storage. Let's install it:


sudo apt install restic -y

Let's create a directory for backups and a script:


mkdir ~/backups
nano ~/backups/mastodon_backup.sh

Contents of ~/backups/mastodon_backup.sh (replace and ):


#!/bin/bash

# Path to the Restic repository (e.g., local folder or S3-compatible endpoint)
# Example for local folder: RESTIC_REPOSITORY="/mnt/backup_drive/mastodon_restic"
# Example for S3: RESTIC_REPOSITORY="s3:https://s3.your-region.amazonaws.com/your-bucket-name"
# Don't forget to configure environment variables for S3: AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY
export RESTIC_REPOSITORY=""
export RESTIC_PASSWORD="" # Strong password for backup encryption

# Temporary directory for DB dump
BACKUP_DIR="/tmp/mastodon_backup_temp"
mkdir -p "$BACKUP_DIR"

# PostgreSQL database dump
PGPASSWORD="" pg_dump -Fc -Z 9 -h localhost -U mastodon mastodon_production > "$BACKUP_DIR/mastodon_production.dump"

# Copy Mastodon config
cp /var/www/mastodon/.env.production "$BACKUP_DIR/.env.production"
cp /etc/caddy/Caddyfile "$BACKUP_DIR/Caddyfile"

# Perform backup with Restic
restic backup \
  --verbose \
  "$BACKUP_DIR" \
  /var/www/mastodon/public/system # If media files are stored locally, otherwise skip

# Clean up old backups (keep 7 daily, 4 weekly, 12 monthly, 1 yearly)
restic forget --prune \
  --keep-daily 7 \
  --keep-weekly 4 \
  --keep-monthly 12 \
  --keep-yearly 1

# Delete temporary files
rm -rf "$BACKUP_DIR"

echo "Mastodon backup completed at $(date)"

Make the script executable:


chmod +x ~/backups/mastodon_backup.sh

Initialize the Restic repository (run once):


restic init

Add the script to Cron for daily execution (e.g., at 3:00 AM):


crontab -e

Add the line:


0 3 * * * /home/mastodonuser/backups/mastodon_backup.sh >> /var/log/mastodon_backup.log 2>&1

Ensure that the user mastodonuser has write permissions to /var/log/mastodon_backup.log.

Where to Store

  • External S3-compatible object storage: The most reliable and scalable option. Ideal for storing large volumes of media files and DB backups. Examples: Amazon S3, DigitalOcean Spaces, Backblaze B2, MinIO.
  • Separate VPS: A small, inexpensive VPS with a large disk can be used to store backups via SFTP/SCP. This provides geographical separation.
  • Local disk: If no other options are available, backups can be stored on the same VPS, but on a separate logical volume or in a separate directory. However, this is the least reliable option, as you will lose both the VPS and the backups if the VPS is lost.

Updates: rolling vs maintenance window

Updating Mastodon and underlying software is an important part of maintenance. It is recommended to adhere to the following strategy:

  • OS and system software updates (PostgreSQL, Redis, Caddy): Perform these during a planned "maintenance window" when user activity is minimal. Always make a backup before major updates.
  • Mastodon Updates:
    • Minor updates (patches): Can usually be performed in a "rolling" fashion, i.e., with minimal downtime. They often do not require DB migrations or configuration changes.
    • Major updates (new versions, e.g., from 4.3 to 4.4): Require more thorough preparation, include DB migrations, asset recompilation, and may require configuration changes. Always plan a maintenance window for them, perform a full backup, and carefully read the changelog.

The Mastodon update process typically includes:


cd /var/www/mastodon
git pull origin main # Or git checkout vX.Y.Z for a specific version
bundle install --without development test
yarn install --pure-lockfile
RAILS_ENV=production bundle exec rake db:migrate
RAILS_ENV=production bundle exec rake assets:precompile
sudo systemctl restart mastodon-web mastodon-sidekiq mastodon-streaming

Always check the official Mastodon documentation for specific instructions on updating to a new version.

Troubleshooting + FAQ

This section contains answers to frequently asked questions and solutions to common problems that may arise during Mastodon deployment and operation.

What is the minimum suitable VPS configuration?

To run Mastodon with a minimal number of users (up to 50) and without large volumes of media content, the minimum configuration should include 2 CPU cores, 4 GB RAM, and 80 GB NVMe SSD. However, it is recommended to have a resource buffer, especially for RAM, to ensure stable operation during peak loads and future growth. If you plan for a more active instance, it's better to immediately aim for 4 CPU cores, 8 GB RAM, and 200 GB NVMe SSD.

What to choose – VPS or dedicated for this task?

For most beginner and medium Mastodon instances (up to several hundred active users), a VPS will be an optimal and cost-effective solution. It provides sufficient performance and flexibility. A dedicated server becomes necessary when your instance scales to thousands of active users, generates terabytes of media content, or requires maximum resource isolation and performance. Transitioning to a dedicated server is a logical step with significant community growth.

Why doesn't Mastodon start after setup?

Most often, this is due to incorrect configuration in .env.production or issues with the database/Redis. Check Systemd service logs: sudo journalctl -u mastodon-web, sudo journalctl -u mastodon-sidekiq, sudo journalctl -u mastodon-streaming. Ensure that all secret keys are generated and correctly inserted, and that PostgreSQL and Redis connection parameters are correct. Verify that PostgreSQL and Redis are running and accessible.

HTTPS not working or domain inaccessible.

Ensure that your DNS A-record for the domain points to your VPS's IP address. Verify that Caddy is running (sudo systemctl status caddy) and its configuration in /etc/caddy/Caddyfile contains no errors (sudo caddy validate --config /etc/caddy/Caddyfile). Make sure ports 80 and 443 are open in the firewall (sudo ufw status). Sometimes Let's Encrypt may issue errors due to incorrect DNS records or blocked ports.

Slow Mastodon performance or 502/503 errors.

This may indicate a lack of resources, especially RAM. Check memory usage with htop. Ensure that mastodon-sidekiq is running, as it handles background tasks and queues. If Sidekiq is overloaded, it can slow down the entire instance. Consider increasing the number of Sidekiq workers or upgrading the VPS to a more powerful plan. Also, check application logs for errors.

How to update Mastodon to a new version?

The detailed update process is described in the "Backups and Maintenance" section. Briefly: make a backup, stop Mastodon services, pull the new version from Git, install new dependencies, apply database migrations, compile assets, then start the services. Always read the official release notes for the specific version, as there may be specific steps.

How to create a new administrator user?

If you want to create an additional administrator or have lost access to the first one, you can do so by running the command in the Mastodon directory: RAILS_ENV=production bundle exec rake mastodon:create_account. You will be prompted to enter a username, email, and password, and then confirm that it will be an administrator account.

How to configure email sending?

SMTP settings are configured in the .env.production file. Ensure that you have specified the correct SMTP_SERVER, SMTP_PORT, SMTP_LOGIN, SMTP_PASSWORD, and SMTP_FROM_ADDRESS. You can test email sending by trying to register a new user or reset a password. If emails are not sent, check the mail service logs and Mastodon logs for SMTP server connection errors.

Conclusions and Next Steps

Congratulations! You have successfully deployed your own Mastodon instance on a VPS, configured all necessary components, and ensured its operation with automatic HTTPS and a backup system. You are now the owner of an independent social platform, ready to welcome users and interact with the Fediverse.

Next steps for developing your instance may include:

  • Scaling media file storage: If your instance grows, consider migrating media files to S3-compatible object storage to free up space on the VPS and improve reliability.
  • Performance monitoring: Set up monitoring tools (e.g., Prometheus + Grafana) to track CPU, RAM, disk usage, as well as Mastodon metrics, to respond to issues promptly.
  • Fine-tuning and optimization: Explore additional configuration parameters for Mastodon, PostgreSQL, and Redis to optimize performance for your specific workload.

Was this guide helpful?

Mastodon Deployment on VPS: A Complete Installation and Configuration Guide
support_agent
Valebyte Support
Usually replies within minutes
Hi there!
Send us a message and we'll reply as soon as possible.