How to Install Mastodon on Debian 11 Server

This tutorial is going to show you how to install Mastodon on Debian 11 server. Mastodon is an open-source decentralized social network. It’s like Twitter, but decentralized. You can set up a Mastodon instance on your server and connect to other Mastodon instances.

Mastodon Features

  • Total data control. You can download all your posts and migrate to another instance.
  • Never worry about account termination by a central organization.
  • Each Mastodon instance can set its own rules.
  • 500 character limit per post.
  • Mobile-friendly, responsive web design. Users can read or post from laptop, tablet and phone.
  • 100% free open source. No paid commercial version with better or more complete features.
  • Official mobile apps for Mastodon are available for iOS and Android
  • And many more.

Mastodon is written with React.js and Ruby on Rails, using PostgreSQL as the back-end database management system.

Prerequisites

Here’s what you should prepare before setting up your own Mastodon instance.

1. A domain name. You need a domain name, so other people can access your Mastodon instance. I registered my domain name at NameCheap because the price is low and they give whois privacy protection free for life.

2. A server. To run Mastodon, you need a server with at least 2GB RAM. If you are looking for a virtual private server (VPS), I recommend Kamatera VPS, which features:

  • 30 days free trial.
  • Starts at $4/month (1GB RAM)
  • High-performance KVM-based VPS
  • 9 data centers around the world, including the United States, Canada, UK, Germany, The Netherlands, Hong Kong, and Isreal.
  • CPU and RAM hot-add. You can temporarily upgrade the server CPU and RAM for free without a reboot.

Follow the tutorial linked below to create your Linux VPS server at Kamatera.

3. SMTP Service. You need to use an SMTP server to send emails for account registration and various other notifications. You can set up your own email server (which takes some time), or use a free SMTP relay service (easier).

Once the above requirements are met, follow the steps below to install Mastodon.

Step 1: Configure PostgreSQL Database Server

Log into your server via SSH. PostgreSQL is available in the default Debian repository. However, the PostgreSQL team always strives to make performance improvements with every new version, so we will install the latest version of PostgreSQL from the upstream repository.

Add the upstream repository.

echo "deb [signed-by=/etc/apt/keyrings/postgresql.asc] http://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list

Import the PostgreSQL public key.

sudo mkdir -p /etc/apt/keyrings/

wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo tee /etc/apt/keyrings/postgresql.asc

Update repository index and install PostgreSQL.

sudo apt update

sudo apt install -y postgresql postgresql-contrib

PostgreSQL database server will automatically start and listens on 127.0.0.1:5432, as can be seen with the following command.

sudo ss -lnpt | grep postgres

mastodon postgresql debian

If you don’t see any output from the above command, it’s probably because PostgreSQL server isn’t running. You can start PostgreSQL server by issuing the following command.

sudo systemctl start postgresql

The postgres user is created on the OS during the installation process. It’s the super user for PostgreSQL database server. We can use sudo to switch to the postgres user and log into the PostgreSQL console.

sudo -u postgres -i psql

Create a database for Mastodon.

CREATE DATABASE mastodon;

Create a database user.

CREATE USER mastodon;

Set a password for this user.

ALTER USER mastodon WITH ENCRYPTED PASSWORD 'your_preferred_password';

Give this user permission to create database.

ALTER USER mastodon createdb;

Set this user as the owner of Mastodon database.

ALTER DATABASE mastodon OWNER TO mastodon;

Log out from the PostgreSQL console.

\q

debian-postgresql-create-database-for-mastodon

Step 2: Install Ruby

Mastodon requires Ruby 2.5+. Debian 11 repository includes the ruby package, so run the following command to install it.

sudo apt install ruby ruby-dev

To check your Ruby version number, run

ruby -v

Sample output:

ruby 2.7.4p191 (2021-07-07 revision a21a3b7d23) [x86_64-linux-gnu]

Step 3: Download and Configure Mastodon on Debian 11

Create the mastodon user.

sudo adduser mastodon --system --group --disabled-login

Install the git tool.

sudo apt install git

Run the following command to clone the Mastodon code repository from Github.

git clone https://github.com/tootsuite/mastodon.git

Create the /var/www/ directory, if it’s not already created.

sudo mkdir -p /var/www/

Move the mastodon directory to /var/www/.

sudo mv mastodon/ /var/www/

Change the owner to mastodon.

sudo chown mastodon:mastodon /var/www/mastodon/ -R

Change directory and check out the latest stable release of Mastodon. You can go to the Github releases page to see the latest stable version. I’m now using v3.5.3.

cd /var/www/mastodon/

sudo -u mastodon git checkout v3.5.3

Install bundler: the Ruby dependency manager.

sudo gem install bundler

Install Node.js.

curl -sL https://deb.nodesource.com/setup_16.x | sudo bash -

sudo apt install nodejs

Install Yarn, a Node.js package manager.

echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -

sudo apt update

sudo apt -y install yarn

Install required packages to compile source code.

sudo apt install redis-server optipng pngquant jhead jpegoptim gifsicle nodejs imagemagick ffmpeg libpq-dev libxml2-dev libxslt1-dev file g++ libprotobuf-dev protobuf-compiler pkg-config gcc autoconf bison build-essential libssl-dev libyaml-dev libreadline6-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm-dev libidn11-dev libicu-dev libjemalloc-dev

Then install dependency packages for Mastodon.

sudo -u mastodon bundle config deployment 'true'

sudo -u mastodon bundle config without 'development test'

sudo -u mastodon bundle install -j$(getconf _NPROCESSORS_ONLN)

Run the setup wizard.

sudo -u mastodon RAILS_ENV=production bundle exec rake mastodon:setup

First, it will ask you a series of questions.

  • Domain name: Choose a domain name to use for your Mastodon instance. For example, I use social.linuxbabe.com.
  • Enable single user mode: If you want visitors to be able to register on your Mastodon instance, then don’t enable single user mode.
  • Are you using Docker to run Mastodon: No.
  • PostgreSQL host: 127.0.0.1
  • PostgreSQL port: 5432
  • PostgreSQL database: mastodon
  • PostgreSQL user: mastodon
  • PostgreSQL user password: enter the password for the mastodon user which is created in step 1.
  • Redis host: 127.0.0.1
  • Redis port: 6379
  • Redis password: Just press Enter, because there’s no password for Redis.
  • Do you want to store uploaded files on the cloud? If you want to store user-uploaded files in S3 object storage, then you can choose Yes. I just want to store files on my own server, so I choose No.
  • Do you want to send emails from localhost? If this is your mail server, or you have set up an SMTP relay, then you can choose Yes. If you choose No, then you need to enter your SMTP server login credentials.
  • E-mail address to send e-mails “from”: You can press Enter to use the default sender email address.
  • Send a test e-mail with this configuration right now? Choose Yes to send a test email.
  • Send test e-mail to: Enter the test email address.
  • Save configuration? Choose Yes.

debian-mastodon-Create-a-configuration-file

Next, Choose Yes to set up the database.

Now that configuration is saved, the database schema must be loaded.
If the database already exists, this will erase its contents.
Prepare the database now? y

Finally, choose Yes to compile CSS/JS assets.

The final step is compiling CSS/JS assets.
This may take a while and consume a lot of RAM.
Compile the assets now? (Y/n) y

debian-mastodon-setup-wizard

Hint: If Mastodon fails to compile, you should upgrade the server to 2 CPU cores and 3G RAM. If you use Kamatera VPS, it allows you to temporarily upgrade the server CPU and RAM for free without a reboot (Hot Add). Then run the following command again to compile Mastodon CSS/JS assets. Make sure you change back to the original server specs, so Kamatera won’t charge extra dollars for CPU/RAM hot add.

sudo -u mastodon RAILS_ENV=production bundle exec rake mastodon:setup

Once that’s done, you can create an admin user.

Do you want to create an admin user straight away? Yes
Username: super_admin
E-mail: [email protected]
You can login with the password: 0b8c9359a98059aWg0yhPyVP3eeOn6715eeb

Step 4: Start Mastodon

Mastodon provides convenient systemd service templates. We can copy them to the /etc/sysetmd/system/ directory.

sudo cp /var/www/mastodon/dist/mastodon*.service /etc/systemd/system/

Then we need to make some changes to the .service files. Change the working directory from /home/mastodon/live/ to /var/www/mastodon/.

sudo sed -i 's/home\/mastodon\/live/var\/www\/mastodon/g' /etc/systemd/system/mastodon-*.service

Change /home/mastodon/.rbenv/shims/bundle to /usr/local/bin/bundle.

sudo sed -i 's/home\/mastodon\/.rbenv\/shims/usr\/local\/bin/g' /etc/systemd/system/mastodon-*.service

Reload systemd for the changes to take effect.

sudo systemctl daemon-reload

Start the 3 systemd services.

sudo systemctl enable --now mastodon-web mastodon-sidekiq mastodon-streaming

Check status. Make sure they are all in active (running) state.

sudo systemctl status mastodon-web mastodon-sidekiq mastodon-streaming

Wait a few seconds, then run the following command to check if Mastodon is listing on port 3000.

sudo ss -lnpt | grep 3000

If Mastodon is running properly, it should output:

LISTEN 0   1024   127.0.0.1:3000    0.0.0.0:*    users:(("ruby2.7",pid=43543,fd=5),("ruby2.7",pid=43535,fd=5),("ruby2.7",pid=43520,fd=5))

If port 3000 thousand is already taken by another process, you need to edit the /etc/systemd/system/mastodon-web.service file.

sudo nano etc/systemd/system/mastodon-web.service

Find the following line.

Environment="PORT=3000"

Change the port number like 3001, so Mastodon will be listening on port 3001. Reload systemd and restart Mastodon.

sudo systemctl daemon-reload

sudo systemctl restart mastodon-web

Step 5: Configure Nginx Reverse Proxy

Install Nginx web server from the default Debian 11 software repository.

sudo apt install nginx

Copy the Nginx template configuration file.

sudo cp /var/www/mastodon/dist/nginx.conf /etc/nginx/conf.d/mastodon.conf

Edit the new file.

sudo nano /etc/nginx/conf.d/mastodon.conf

Find the following line in both the port 80 server block and port 443 server block.

server_name example.com;

Change the server name. Don’t forget to add DNS A record for the domain name.

server_name social.example.com;

Find the following line in both the port 80 server block and port 443 server block.

root /home/mastodon/live/public;

Change it to:

root /var/www/mastodon/public;

Find the following two lines.

 # ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
# ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;

Change them to the following, so Nginx will tempoarily use a self-signed TLS certificate. We will obtain a valid Let’s Encrypt certificate later.

ssl_certificate /etc/ssl/certs/ssl-cert-snakeoil.pem;
ssl_certificate_key /etc/ssl/private/ssl-cert-snakeoil.key;

Save and close the file. Create the cache directory.

sudo mkdir -p /var/nginx/cache/

Then test Nginx configuration.

sudo nginx -t

If the test is successful, reload Nginx for the changes to take effect.

sudo systemctl reload nginx

Now you should be able to see the Mastodon forum at http://social.example.com.

Step 7: Enable HTTPS

To encrypt HTTP traffic, we can enable HTTPS by installing a free TLS certificate issued from Let’s Encrypt. Run the following command to install Let’s Encrypt client (certbot) on Debian 11 server.

sudo apt install certbot python3-certbot-nginx

Next, run the following command to obtain and install TLS certificate.

sudo certbot --nginx --agree-tos --redirect --hsts --staple-ocsp --email [email protected] -d social.example.com

Where

  • --nginx: Use the nginx plugin.
  • --agree-tos: Agree to terms of service.
  • --redirect: Force HTTPS by 301 redirect.
  • --hsts: Add the Strict-Transport-Security header to every HTTP response. Forcing browser to always use TLS for the domain. Defends against SSL/TLS Stripping.
  • --staple-ocsp: Enables OCSP Stapling. A valid OCSP response is stapled to the certificate that the server offers during TLS.
  • --email: an email address is required to receive important email notification for your TLS certificates.

The certificate should now be obtained and automatically installed.

mastodon letsencrypt https

And you can access Mastodon forum via HTTPS (https://social.example.com).

mastodon login page

And you can login using the admin account created in step 3. After login, you should change the password.

Hint: My Mastodon account: https://social.linuxbabe.com/@super_admin

Can’t Send Emails?

If Mastodon fails to send emails, you can find out what went wrong by going to the https://social.example.com/sidekiq/retries URL, assuming you are logged in as the admin user.

It will show you the failed emails and why email sending failed.

mastodon SMTP error

As you can see from the above screenshot, localhost:25 refused connection from my Mastodon installation. It turned out that I moved Mastodon to a bigger server but forgot to set up SMTP relay. Once SMTP relay is configured, email sending is working again.

If there are still problems in SMTP, please check the Postfix mail log file.

sudo tail /var/log/mail.log

or

sudo vim /var/log/mail.log

How to Back Up and Restore Mastodon Database

Dump the database into a tar archive.

sudo -u postgres -i pg_dump -F t mastodon > mastodon_pgsql.tar

Restore the database.

sudo -u postgres -i pg_restore --clean --dbname=mastodon /path/to/the/mastodon_pgsql.tar

To back up the /var/www/mastodon/ folder, I recommend using Duplicati.

Troubleshooting Mastodon Runtime Error

If the Mastodon web page isn’t working, you should check the sysetmd journals.

sudo journalctl -eu mastodon-web

sudo journalctl -eu mastodon-sidekiq

sudo journalctl -eu mastodon-streaming

How to Upgrade Mastodon

Note: Mastodon v4.0.2 isn’t compatible with Debian 11 currently. You should upgrade to Debian 12, which will be released in 2023. In the meantime, you can continue using Mastodon v3.5.x, which is supported with bug fixes and security updates.

First, back up the database as mentioned above. Then go to the Mastodon web root directory.

cd /var/www/mastodon/

Fetch new release tags.

sudo -u mastodon git fetch --tags

Sample output:

 * [new tag]             v3.5.4                                                          -> v3.5.4
 * [new tag]             v3.5.5                                                          -> v3.5.5
 * [new tag]             v4.0.0                                                          -> v4.0.0
 * [new tag]             v4.0.0rc1                                                       -> v4.0.0rc1
 * [new tag]             v4.0.0rc2                                                       -> v4.0.0rc2
 * [new tag]             v4.0.0rc3                                                       -> v4.0.0rc3
 * [new tag]             v4.0.0rc4                                                       -> v4.0.0rc4
 * [new tag]             v4.0.1                                                          -> v4.0.1
 * [new tag]             v4.0.2                                                          -> v4.0.2

Upgrade to v4.0.2

sudo -u mastodon git checkout v4.0.2

Migrate the database.

sudo -u mastodon RAILS_ENV=production bundle exec rake db:migrate

Compile the assets.

sudo -u mastodon bundle install -j$(getconf _NPROCESSORS_ONLN)

sudo -u mastodon RAILS_ENV=production bundle exec rails assets:precompile

Migrate the database again.

sudo -u mastodon RAILS_ENV=production bundle exec rake db:migrate

Once that’s done. Restart Mastodon.

sudo systemctl restart mastodon-web mastodon-sidekiq mastodon-streaming

Conclusion

I hope this article helped you install Mastodon forum software on Debian 11. As always, if you found this post useful, then subscribe to our free newsletter to get more tips and tricks. Take care 🙂

Rate this tutorial
[Total: 13 Average: 4.7]

25 Responses to “How to Install Mastodon on Debian 11 Server

  • Duffman
    2 years ago

    Perfect Instructions LinuxBabe A++

    My Pro Tip – If you can not get the 3 Mastodon Systemd Services to work, it is because you did not follow the instructions LinxuBabe.com spent a lot of time on preparing for you, this is not a joke, please re-read the instructions and make sure you follow them this time.

    Delete your DB and start over. I am writing this from experience and not to criticize you.

    Thank You for Supporting and Teaching the FOSS Community LinuxBabe!

  • JohnnyD
    2 years ago

    Excellent instructions A+++

  • worked like a charm, for the most part. Had to drop my mastodon and template1 databases and make them new because they were SQL_ASCII encoding and mastodon needs UTF-8. I followed this instruction to do it:

    https://www.shubhamdipt.com/blog/how-to-change-postgresql-database-encoding-to-utf8/

    checking the database encoding and referring to this or a similar site if the encoding of the database isn’t utf-8 would be a good addition to section 1 of this great instruction

    I installed mastodon in a debian 11 lxc on proxmox 7.2, maybe this has something to do with the encoding discrepancy

    • Christian
      2 years ago

      Phil,
      did you run the Promox in a server center or at home? Tried many times to install in a LXC but have a pfsense with HAProxy in front which even manages the SSL certs. Cant’t access the mastodon website with the nginx server config provided by mastodon. Very frustarting. All howtos are made for installing in a data center…

      • Christian, you and I are having the exact same experience.
        Debian 11 CT on Proxmox 7.2 running on a box in my basement, behind pfSense HA proxy with Acme cert.
        On my last go, I was able to connect to the server (Ubuntu 20.04), but was only getting the frustrated mastodon gif.
        Have you had any luck?
        Now I am trying again, but hitting this UTF8 issue. Need to check Phil’s link, but saw your situation and said “Hey! This guy is in my exact same place!”

        @[email protected]

  • John Devine
    2 years ago

    How do I upgrade to V4.0.0rc1 please?

    • Xiao Guoan (Admin)
      2 years ago

      It’s not recommended to upgrade to v4.x on Debian 11. V4.x now requires libffi8, which isn’t available on Debian 11.

      Mastodon v3.5.x will be supported with security updates and bug fixes for some time. When Debian 12 is released, you can upgrade it to v4.x.

      • adrian boliston
        2 years ago

        i have just installed v4.0.2 on debian 11 and it appears to be running ok

  • Wolfram
    2 years ago

    Thank you for your excellent instructions.

    It worked like a charm. My postgresql settings were already UTF-8. I installed it with german language settings.

    VM on proxmox 7.2 and debian bullseye (8 GB / 4 CPU)

  • If debian is updated to version 12, can you explain how we should update? Because the github points to the \live directory and we are using the /public directory with this installation. I’m afraid something will go wrong?

  • Simply Per-fect! ⭐️⭐️⭐️⭐️⭐️
    Thank you so much. 🙋‍♂️

  • adrian boliston
    2 years ago

    i am wondering if using the postgres upstream repository is always the best thing as i was getting problems with backups for the database

    "pg_dump: error: server version: 15.1 (Debian 15.1-1.pgdg110+1); pg_dump version: 13.8 (Debian 13.8-0+deb11u1)
    pg_dump: error: aborting because of server version mismatch"
    
    • Xiao Guoan (Admin)
      2 years ago

      Install postgresql-client-15

      sudo apt install postgresql-client-15
      • adrian boliston
        2 years ago

        it just says:
        postgresql-client-15 is already the newest version (15.1-1.pgdg110+1).

  • Great instructions. I have one issue. I cannot add themes or change the base color of an existing theme. Have you seen this with any other installation?

  • Does not work (install)
    After succesfull
    sudo -u mastodon bundle config deployment ‘true’
    sudo -u mastodon bundle config without ‘development test’

    The…
    sudo -u mastodon bundle install -j$(getconf _NPROCESSORS_ONLN)

    ends with the error

    Your Ruby version is 2.5.5, but your Gemfile specified >= 2.6.0, < 3.1.0

    /It is a standard Debian 11 server/

  • Hi There,
    Thanks for the great Instruction, I installed mastodon on a fresh gcp vm instance debian 11 and its running but the pages are not loaded properly.
    I already checked the mastodon user got access permissions to /var/www/mastodon and ../public
    I even checked the utf-8 of postgres
    Can you help on the issue

    • in addition, the nginx conf is already edited as the instruction, however it did not have the root /home/mastodon/live/public; line in order to change to “root /var/www/mastodon/public;” in port 443 section. I added the line and got error, so I ignored the line.

      here is the errors of the inspect of the first page …
      it may help to solve the issue I hope

      • I’ve been having this exact problem running on an Azure VM, but when I install to a fresh Debian11 instance in my home VMWare lab, everything works fine.

        Something to do with Cloud networking maybe?

        • Jesse
          2 years ago

          Figured it out…

          root /var/www/mastodon/public;

          Appears in two different places. If you only change the first one, the above results are exactly what you’ll get.

          Make sure it’s the same in both places, and it should be fine.

  • Has anyone managed to get Elasticsearch installed and working? I used the Elasticsearch install from the official docs, but it is not starting and for not very clear reasons.

    root@mastodon:~# systemctl start elasticsearch
    Job for elasticsearch.service failed because a fatal signal was delivered to the control process.
    See “systemctl status elasticsearch.service” and “journalctl -xe” for details.
    root@mastodon:~# journalctl -xe
    — Subject: A start job for unit elasticsearch.service has failed
    — Defined-By: systemd
    — Support: https://www.debian.org/support

    — A start job for unit elasticsearch.service has finished with a failure.

    — The job identifier is 497 and the job result is failed.
    Jan 07 16:10:09 mastodon systemd[1]: elasticsearch.service: Consumed 12.209s CPU time.
    — Subject: Resources consumed by unit runtime
    — Defined-By: systemd
    — Support: https://www.debian.org/support

    — The unit elasticsearch.service completed and consumed the indicated resources.

    Can anyone point me in the right direction? I have no experience with installing Elasticsearch. The /var/log/elasticsearch/gc.log is nearly empty and shows no errors.

    Thanks,
    @[email protected] 😉

    • Solution to Elasticsearch not starting is at the bottom of this page:
      https://github.com/felx/mastodon-documentation/blob/master/Running-Mastodon/Elasticsearch-guide.md

  • i cannot change the profile picture of the user why?

  • How on earth do I upgrade ruby to v.3.0 for the 4.2 upgrade having used this guide? D: Seems debian just installs 2.7 via apt and I can’t figure out how to change my install to use the rbenv install

Leave a Comment

  • Comments with links are moderated by admin before published.
  • Your email address will not be published.
  • Use <pre> ... </pre> HTML tag to quote the output from your terminal/console.
  • Please use the community (https://community.linuxbabe.com) for questions unrelated to this article.
  • I don't have time to answer every question. Making a donation would incentivize me to spend more time answering questions.

The maximum upload file size: 2 MB. You can upload: image. Links to YouTube, Facebook, Twitter and other services inserted in the comment text will be automatically embedded. Drop file here