Поиск по сайту:

Как установить платформу социальных сетей Mastodon на Debian 10


Это руководство существует для этих версий ОС

  • Debian 11 (Bullseye)
  • Debian 10 (Buster)

На этой странице

  1. Требования
  2. Начало работы
  3. Установите Node.js
  4. Установка и настройка PostgreSQL
  5. Установить Руби
  6. Настроить мастодонта
  7. Настройка Nginx для Mastodon
  8. Настройка службы Systemd для Mastodon
  9. Доступ к веб-интерфейсу Mastodon

Mastodon — это социальная сеть с открытым исходным кодом, очень похожая на Twitter. Вы можете следить за другими пользователями и публиковать сообщения и изображения с Mastodon. Он написан на Ruby и JavaScript, и каждый может использовать его конфиденциально и безопасно. Mastodon также предоставляет приложение для различных платформ, таких как Android и iOS.

В этом руководстве мы покажем вам, как установить Mastodon на Debian 10.

Требования

  • Сервер под управлением Debian 10.
  • На вашем сервере настроен пароль root.
  • Действительное доменное имя указано вместе с IP-адресом вашего сервера. В этом уроке мы будем использовать test.linuxbuz.com.

Начиная

Во-первых, рекомендуется обновить вашу систему до последней версии. Вы можете сделать это, выполнив следующую команду:

apt-get update -y
apt-get upgrade -y

После обновления вашей системы вам нужно будет установить некоторые зависимости, необходимые для Mastodon. Вы можете установить их все с помощью следующей команды:

apt-get install software-properties-common dirmngr apt-transport-https ca-certificates curl gcc g++ make imagemagick ffmpeg libpq-dev libxml2-dev libxslt1-dev file git-core libprotobuf-dev protobuf-compiler pkg-config autoconf bison build-essential libssl-dev libyaml-dev libreadline-dev libidn11-dev libicu-dev libjemalloc-dev zlib1g-dev libncurses5-dev libffi-dev libgdbm-dev -y

После установки всех зависимостей можно переходить к следующему шагу.

Установите Node.js

Mastodon требует, чтобы Node.js версии 8.x и Yarn были установлены в вашей системе. Чтобы установить Node.js, добавьте репозиторий Node.js на свой сервер с помощью следующей команды:

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

После добавления репозитория установите Node.js версии 8 с помощью следующей команды:

apt-get install nodejs -y

Затем загрузите и добавьте ключ Yarns GPG и включите репозиторий с помощью следующей команды:

curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | apt-key add -
echo "deb https://dl.yarnpkg.com/debian/ stable main" | tee /etc/apt/sources.list.d/yarn.list

После добавления обновите репозиторий и установите Yarn с помощью следующих команд:

apt-get update -y
apt-get install yarn -y

Как только вы закончите, вы можете перейти к следующему шагу.

Установите и настройте PostgreSQL.

Mastodon использует PostgreSQL для хранения своих данных. Вы можете установить последнюю версию PostgreSQL с помощью следующей команды:

apt-get install postgresql postgresql-contrib -y

После установки войдите в PostgreSQL с помощью следующей команды:

su - postgres
:~$ psql
psql (11.5 (Debian 11.5-1+deb10u1))
Type "help" for help.

Затем создайте пользователя для Mastodon с помощью следующей команды:

postgres=# CREATE USER mastodon CREATEDB;

Затем выйдите из оболочки PostgreSQL с помощью следующей команды:

postgres=#exit

Установить Руби

Mastodon использует Ruby on Rails для внутренних целей. Во-первых, вам нужно будет создать нового системного пользователя для запуска сервера Mastodon.

Вы можете создать его с помощью следующей команды:

adduser --disabled-login --gecos 'Mastodon Server' mastodon

После создания войдите в систему пользователя mastodon с помощью следующей команды:

su - mastodon

Затем клонируйте репозиторий rbenv с помощью следующей команды:

git clone https://github.com/rbenv/rbenv.git ~/.rbenv

Затем настройте rbenv и ruby-build с помощью следующих команд:

cd ~/.rbenv && src/configure && make -C src
echo 'export PATH="$HOME/.rbenv/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(rbenv init -)"' >> ~/.bashrc
exec bash
git clone https://github.com/rbenv/ruby-build.git ~/.rbenv/plugins/ruby-build

Когда вы закончите, установите последнюю версию Ruby с помощью следующей команды:

RUBY_CONFIGURE_OPTS=--with-jemalloc rbenv install 2.6.1

После установки вы должны получить следующий вывод:

Downloading ruby-2.6.1.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/2.6/ruby-2.6.1.tar.bz2
Installing ruby-2.6.1...

Installed ruby-2.6.1 to /home/mastodon/.rbenv/versions/2.6.1

Затем установите Ruby, доступный глобально, с помощью следующей команды:

rbenv global 2.6.1

Затем обновите гем и установите упаковщик с помощью следующей команды:

gem update --system
gem install bundler --no-document

Когда вы закончите, вы можете проверить Ruby с помощью следующей команды:

ruby --version

Настроить мастодонта

Сначала войдите в систему под пользователем mastodon и загрузите git-репозиторий mastodon с помощью следующей команды:

su - mastodon
git clone https://github.com/tootsuite/mastodon.git ~/live
cd ~/live

Затем проверьте последнюю ветку с помощью следующей команды:

git checkout $(git tag -l | grep -v 'rc[0-9]*$' | sort -V | tail -n 1)

Вы должны получить следующий результат:

Note: checking out 'v2.9.3'.

You are in 'detached HEAD' state. You can look around, make experimental
changes and commit them, and you can discard any commits you make in this
state without impacting any branches by performing another checkout.

If you want to create a new branch to retain commits you create, you may
do so (now or later) by using -b with the checkout command again. Example:

  git checkout -b 

HEAD is now at 06f906aca Bump version to 2.9.3

Затем установите все зависимости, необходимые для ruby и Node.js, с помощью следующей команды:

bundle install -j$(getconf _NPROCESSORS_ONLN) --deployment --without development test
yarn install --pure-lockfile

Теперь настройте Mastodon с помощью следующей команды:

RAILS_ENV=production bundle exec rake mastodon:setup

В процессе настройки вам будет задано несколько вопросов. Ответьте на все вопросы, как показано ниже:

Your instance is identified by its domain name. Changing it afterward will break things.
Domain name: test.linuxbuz.com

Single user mode disables registrations and redirects the landing page to your public profile.
Do you want to enable single user mode? No

Are you using Docker to run Mastodon? no

PostgreSQL host: /var/run/postgresql
PostgreSQL port: 5432
Name of PostgreSQL database: mastodon_production
Name of PostgreSQL user: mastodon
Password of PostgreSQL user: 
Database configuration works! ????

Redis host: localhost
Redis port: 6379
Redis password: 
Redis configuration works! ????

Do you want to store uploaded files on the cloud? No

Do you want to send e-mails from localhost? yes
E-mail address to send e-mails "from": Mastodon <>
Send a test e-mail with this configuration right now? no

This configuration will be written to .env.production
Save configuration? Yes

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? Yes

All done! You can now power on the Mastodon server ????

Do you want to create an admin user straight away? Yes
Username: admin
E-mail: 
You can login with the password: a9a78a4c2eb442d72eb946f94ebe9a00
You can change your password once you login.

Как только вы закончите, выйдите из пользователя mastodon с помощью следующей команды:

exit

Настройте Nginx для Mastodon

Далее вам нужно будет установить Nginx и Certbot в вашу систему. По умолчанию последняя версия Certbot недоступна в репозитории по умолчанию Debian 10. Итак, вам нужно будет добавить репозиторий Certbot в вашу систему.

Вы можете добавить его с помощью следующей команды:

add-apt-repository ppa:certbot/certbot

Затем обновите репозиторий и установите Certbot с помощью Nginx, выполнив следующую команду:

apt-get update -y
apt-get install nginx python-certbot-nginx -y

После установки обоих пакетов скопируйте файл конфигурации Nginx из каталога Mastodon в Nginx с помощью следующей команды:

cp /home/mastodon/live/dist/nginx.conf /etc/nginx/sites-available/mastodon.conf

Затем включите файл конфигурации виртуального хоста Mastodon с помощью следующей команды:

ln -s /etc/nginx/sites-available/mastodon.conf /etc/nginx/sites-enabled/

По умолчанию в файле конфигурации виртуального хоста Mastodon указан домен example.com. Поэтому вам нужно будет заменить домен example.com на ваше доменное имя в файле mastodon.conf. Вы можете заменить его следующей командой:

sed -i 's/example.com/test.linuxbuz.com/g' /etc/nginx/sites-enabled/mastodon.conf

Затем перезапустите службу Nginx, чтобы применить конфигурацию:

systemctl restart nginx

Затем загрузите бесплатный SSL-сертификат Lets Encrypt и настройте Nginx для использования этого сертификата, выполнив команду certbot:

certbot --nginx -d test.linuxbuz.com

Это загрузит бесплатный SSL-сертификат Lets Encrypt и настроит Nginx для вашего домена test.linuxbuz.com.

Ваш файл конфигурации Nginx для Mastodon теперь выглядит следующим образом:

cat /etc/nginx/sites-enabled/mastodon.conf

Вывод:

map $http_upgrade $connection_upgrade {
  default upgrade;
  ''      close;
}

proxy_cache_path /var/cache/nginx levels=1:2 keys_zone=CACHE:10m inactive=7d max_size=1g;

server {
    if ($host = test.linuxbuz.com) {
        return 301 https://$host$request_uri;
    } # managed by Certbot


  listen 80;
  listen [::]:80;
  server_name test.linuxbuz.com;
  root /home/mastodon/live/public;
  location /.well-known/acme-challenge/ { allow all; }
  location / { return 301 https://$host$request_uri; }


}

server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  server_name test.linuxbuz.com;

  ssl_protocols TLSv1.2;
  ssl_ciphers HIGH:!MEDIUM:!LOW:!aNULL:!NULL:!SHA;
  ssl_prefer_server_ciphers on;
  ssl_session_cache shared:SSL:10m;

  # Uncomment these lines once you acquire a certificate:
  # ssl_certificate     /etc/letsencrypt/live/test.linuxbuz.com/fullchain.pem;
  # ssl_certificate_key /etc/letsencrypt/live/test.linuxbuz.com/privkey.pem;

  keepalive_timeout    70;
  sendfile             on;
  client_max_body_size 80m;

  root /home/mastodon/live/public;

  gzip on;
  gzip_disable "msie6";
  gzip_vary on;
  gzip_proxied any;
  gzip_comp_level 6;
  gzip_buffers 16 8k;
  gzip_http_version 1.1;
  gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;

  add_header Strict-Transport-Security "max-age=31536000";

  location / {
    try_files $uri @proxy;
  }

  location ~ ^/(emoji|packs|system/accounts/avatars|system/media_attachments/files) {
    add_header Cache-Control "public, max-age=31536000, immutable";
    add_header Strict-Transport-Security "max-age=31536000";
    try_files $uri @proxy;
  }

  location /sw.js {
    add_header Cache-Control "public, max-age=0";
    add_header Strict-Transport-Security "max-age=31536000";
    try_files $uri @proxy;
  }

  location @proxy {
    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 https;
    proxy_set_header Proxy "";
    proxy_pass_header Server;

    proxy_pass http://127.0.0.1:3000;
    proxy_buffering on;
    proxy_redirect off;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;

    proxy_cache CACHE;
    proxy_cache_valid 200 7d;
    proxy_cache_valid 410 24h;
    proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504;
    add_header X-Cached $upstream_cache_status;
    add_header Strict-Transport-Security "max-age=31536000";

    tcp_nodelay on;
  }

  location /api/v1/streaming {
    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 https;
    proxy_set_header Proxy "";

    proxy_pass http://127.0.0.1:4000;
    proxy_buffering off;
    proxy_redirect off;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection $connection_upgrade;

    tcp_nodelay on;
  }

  error_page 500 501 502 503 504 /500.html;

    ssl_certificate /etc/letsencrypt/live/test.linuxbuz.com/fullchain.pem; # managed by Certbot
    ssl_certificate_key /etc/letsencrypt/live/test.linuxbuz.com/privkey.pem; # managed by Certbot
}

Настройка службы Systemd для Mastodon

Теперь Nginx установлен и настроен для обслуживания Mastodon. Далее вам нужно будет настроить служебный файл systemd для Mastodon. Для этого скопируйте шаблоны службы systemd из каталога Mastodon:

cp /home/mastodon/live/dist/mastodon-web.service /etc/systemd/system/
cp /home/mastodon/live/dist/mastodon-sidekiq.service /etc/systemd/system/
cp /home/mastodon/live/dist/mastodon-streaming.service /etc/systemd/system/

Затем запустите все службы и включите их запуск после перезагрузки с помощью следующей команды:

systemctl start mastodon-web
systemctl start mastodon-sidekiq
systemctl start mastodon-streaming
systemctl enable mastodon-web
systemctl enable mastodon-sidekiq
systemctl enable mastodon-streaming

Доступ к веб-интерфейсу Mastodon

Теперь откройте веб-браузер и введите URL-адрес https://test.linuxbuz.com. Вы будете перенаправлены на следующую страницу:

Теперь укажите свой адрес электронной почты и пароль администратора, которые вы создали ранее, и нажмите кнопку «Войти». Вы должны увидеть следующую страницу:

Теперь нажмите LETS GO! кнопка. Вы должны увидеть следующую страницу:

Теперь нажмите кнопку «Далее». Вы должны увидеть следующую страницу:

Теперь нажмите ЗАВЕРШИТЬ ОБУЧЕНИЕ! кнопка. Вы должны увидеть панель инструментов Mastodon на следующей странице:

Поздравляем! вы успешно установили и настроили Mastodon на сервере Debian 10. Теперь вы можете легко создать свою собственную социальную сеть с помощью Mastodon. Не стесняйтесь спрашивать меня, если у вас есть какие-либо вопросы.