웹사이트 검색

Ubuntu 18.04 LTS에서 Docker를 사용하여 Mastodon 소셜 네트워크를 설치하는 방법


이 튜토리얼은 다음 OS 버전에 대해 존재합니다.

  • Ubuntu 22.04(Jammy Jellyfish)
  • Ubuntu 18.04(Bionic Beaver)

이 페이지에서

  1. 전제 조건
  2. 1단계 - 종속성 설치
  3. 2단계 - 방화벽 구성\n
  4. 3단계 - Docker 설치
  5. 4단계 - Docker Compose 설치
  6. 5단계 - Mastodon 설치
  7. 6단계 - Nginx 설치 및 구성
  8. 7단계 - Lets Encrypt 설치 및 구성
    1. SSL 인증서 자동 갱신 설정

    Mastodon은 무료 분산형 오픈 소스 소셜 네트워크입니다. Twitter의 대안으로 만들어졌습니다. 트위터 사람들이 서로를 팔로우하고 메시지, 이미지 및 비디오를 게시할 수 있는 것처럼. 그러나 Twitter와 달리 콘텐츠에 대한 중앙 저장소나 권한이 없습니다.

    대신 Mastodon은 각각 커뮤니티의 다양한 구성원을 실행하는 수천 개의 서로 다른 서버에서 작동합니다. 한 서버에 등록된 사용자는 다른 네트워크의 사용자에게 쉽게 연결하고 인스턴스 간에 서로를 따를 수 있습니다.

    누구나 자신만의 마스토돈 서버 인스턴스를 설치할 수 있습니다. 이 튜토리얼은 Docker를 사용하여 Ubuntu 18.04가 설치된 서버에서 Mastodon 인스턴스를 설정하는 방법을 알려줍니다.

    전제 조건

    • An Ubuntu 18.04 based server with a non-root sudo user.

    • Ensure your system is up to date.

      $ sudo apt update
      $ sudo apt upgrade
      
    • Mastodon sends email notifications to users. One option to make it work is to set up your own mail server. You can do it on the same server as you will be installing mastodon or on a different server. Doing it is out of the scope of this guide.

      We will recommend you to use a 3rd party Transactional mail service like Mailgun, Sendgrid, Amazon SES or Sparkpost. The instructions in the guide will be using Mailgun as your SMTP provider.

    • Make sure you have a domain name pointing to the server. For this tutorial, we will be using example.com as the domain.

    1단계 - 종속성 설치

    Mastodon을 설치하기 전에 서버에 제대로 설치하는 데 필요한 특정 소프트웨어가 있는지 확인해야 합니다. 다음 명령을 실행하여 종속성을 설치합니다.

    $ sudo apt update
    $ sudo apt install ca-certificates curl ufw apt-transport-https software-properties-common git -y
    

    위의 소프트웨어 중 일부는 사전 설치되어 있을 수 있습니다.

    Git을 설치했으므로 진행하기 전에 구성해야 합니다.

    $ git config --global user.name "Your Name" 
    $ git config --global user.email ""
    

    2단계 - 방화벽 구성

    이전 단계에서 ufw(복잡하지 않은 방화벽)를 설치했습니다. Mastodon 설치를 진행하기 전에 구성해야 합니다.

    잠기지 않도록 방금 생성한 SSH와 포트를 활성화합니다.

    $ sudo ufw allow OpenSSH
    

    ufw 방화벽을 활성화합니다.

    $ sudo ufw enable
    

    또한 Mastodon이 작동하려면 http 및 https를 활성화해야 합니다.

    $ sudo ufw allow http
    $ sudo ufw allow https
    

    방화벽의 상태를 확인하십시오.

    $ sudo ufw status
    

    다음과 같은 출력이 표시되어야 합니다.

    Status: active
    
    To                         Action      From
    --                         ------      ----
    OpenSSH                    ALLOW       Anywhere                  
    80/tcp                     ALLOW       Anywhere                  
    443/tcp                    ALLOW       Anywhere                  
    OpenSSH (v6)               ALLOW       Anywhere (v6)             
    80/tcp (v6)                ALLOW       Anywhere (v6)             
    443/tcp (v6)               ALLOW       Anywhere (v6)             
    

    3단계 - 도커 설치

    시스템에 Dockers GPG 키를 추가합니다.

    $ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
    

    다운로드한 키의 지문을 확인합니다.

    $ sudo apt-key fingerprint 0EBFCD88
    

    다음과 같은 출력이 표시되어야 합니다.

    pub   rsa4096 2017-02-22 [SCEA]
          9DC8 5822 9FC7 DD38 854A  E2D8 8D81 803C 0EBF CD88
    uid           [ unknown] Docker Release (CE deb) <>
    sub   rsa4096 2017-02-22 [S]
    

    도커 저장소를 추가합니다.

    $ sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
    

    패키지 데이터베이스를 업데이트하십시오.

    $ sudo apt update
    

    Docker-CE를 설치합니다. CE는 Docker의 Community Edition입니다.

    $ sudo apt install docker-ce -y
    

    지금 Docker를 설치해야 합니다. 실행 중인지 확인합니다.

    $ sudo systemctl status docker
    

    출력은 다음과 유사해야 합니다.

    ? docker.service - Docker Application Container Engine
       Loaded: loaded (/lib/systemd/system/docker.service; enabled; vendor preset: enabled)
       Active: active (running) since Tue 2019-10-22 18:26:29 UTC; 25min ago
         Docs: https://docs.docker.com
     Main PID: 3574 (dockerd)
        Tasks: 8
       CGroup: /system.slice/docker.service
       ??3574 /usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
    

    종료하려면 q를 누르세요.

    sudo 없이 docker를 실행할 수 있도록 제한된 Linux 사용자 계정을 docker 그룹에 추가합니다.

    sudo usermod -aG docker $USER
    

    $USER 변수는 현재 로그인한 사용자를 선택하여 도커 그룹에 추가합니다. 현재 해당 사용자로 로그인하지 않은 경우 $USER를 실제 사용자 이름으로 바꾸십시오.

    방금 추가한 사용자로 전환합니다. 이미 로그인한 경우에도 권한을 다시 로드하려면 다시 전환해야 합니다.

    $ su - ${USER}
    

    내장 "Hello World" 프로그램을 실행하여 모든 것이 제대로 실행되고 있는지 확인하십시오.

    $ docker run hello-world
    

    Docker가 설치되어 있고 제대로 작동하고 있음을 알려주는 다음 출력이 표시되어야 합니다.

    Unable to find image 'hello-world:latest' locally
    latest: Pulling from library/hello-world
    1b930d010525: Pull complete 
    Digest: sha256:c3b4ada4687bbaa170745b3e4dd8ac3f194ca95b2d0518b417fb47e5879d9b5f
    Status: Downloaded newer image for hello-world:latest
    
    Hello from Docker!
    This message shows that your installation appears to be working correctly.
    

    4단계 - Docker Compose 설치

    이 단계를 건너뛰고 진행할 수 있지만 Docker Compose를 설치하면 특히 둘 이상의 서버에서 수행하려는 경우 Mastodon을 훨씬 쉽게 실행할 수 있습니다.

    $ sudo curl -L "https://github.com/docker/compose/releases/download/1.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
    

    이 자습서를 작성할 당시에는 1.24.1이 Docker Compose의 현재 안정적인 릴리스입니다. Github 페이지에서 최신 릴리스 버전을 확인할 수 있습니다.

    docker compose 바이너리에 실행 권한을 적용합니다.

    $ sudo chmod +x /usr/local/bin/docker-compose
    

    Docker Compose에 명령 완성을 추가합니다.

    $ sudo curl -L https://raw.githubusercontent.com/docker/compose/1.24.1/contrib/completion/bash/docker-compose -o /etc/bash_completion.d/docker-compose
    

    설치가 성공했는지 확인하십시오.

    $ docker-compose --version
    

    다음 출력을 인쇄합니다.

    docker-compose version 1.24.1, build 4667896b
    

    5단계 - 마스토돈 설치

    Mastodons 리포지토리를 서버에 복제합니다.

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

    방금 파일을 복사한 디렉토리로 이동합니다.

    $ cd mastodon
    

    Mastodon은 샘플 구성 파일과 함께 제공됩니다. Mastodon이 작동하도록 이름을 바꿔야 합니다.

    $ cp .env.production.sample .env.production
    

    구성 파일에 대한 비밀 키를 생성해야 합니다. 하지만 그 전에 Docker 이미지를 빌드해야 합니다.

    $ docker-compose build
    

    이제 이미지가 성공적으로 빌드되었으므로 Mastodon을 구성하는 데 필요한 여러 키를 생성해야 합니다.

    먼저 SECRET_KEY_BASE를 생성합니다.

    $ SECRET_KEY_BASE=$(docker-compose run --rm web bundle exec rake secret)
    

    구성 파일에 위의 키를 삽입합니다.

    $ sed -i -e "s/SECRET_KEY_BASE=/&${SECRET_KEY_BASE}/" .env.production
    

    OTP_SECRET를 생성하고 구성 파일에 삽입합니다.

    $ OTP_SECRET=$(docker-compose run --rm web bundle exec rake secret)
    $ sed -i -e "s/OTP_SECRET=/&${OTP_SECRET}/" .env.production
    

    PAPERCLIP_SECRET를 생성하고 구성 파일에 삽입합니다.

    $ PAPERCLIP_SECRET=$(docker-compose run --rm web bundle exec rake secret)
    $ sed -i -e "s/PAPERCLIP_SECRET=/&${PAPERCLIP_SECRET}/" .env.production
    

    VAPID_PRIVATE_KEY 및 VAPID_PUBLIC_KEY에 대한 값을 생성합니다.

    $ docker-compose run --rm web bundle exec rake mastodon:webpush:generate_vapid_key
    

    .env.production 파일을 엽니다.

    $ sudo nano ./.env.production
    

    파일에서 VAPID_PRIVATE_KEY 및 VAPID_PUBLIC_KEY를 검색하고 이전 명령의 출력을 복사합니다.

    LOCAL_DOMAIN 변수를 찾아 그 값을 example.com에서 Mastodon 설치를 위해 선택한 도메인 이름으로 변경합니다.

    SMTP 공급자로부터 받은 값을 입력합니다.

    SMTP_SERVER = smtp.mailgun.org
    SMTP_PORT = 587
    SMTP_LOGIN = username
    SMTP_PASSWORD = password
    SMTP_FROM_ADDRESS = 
    

    완료되면 Ctrl + X를 누르고 파일을 저장하십시오.

    위에서 수행한 모든 변경 사항을 구현하려면 Docker 이미지를 다시 빌드해야 합니다.

    $ docker-compose build
    

    데이터베이스를 설정합니다.

    $ docker-compose run --rm web rails db:migrate
    

    Mastodons 자산을 사전 컴파일합니다.

    $ docker-compose run --rm web rails assets:precompile
    

    다음 명령을 실행하여 컨테이너를 실행합니다.

    $ docker-compose up -d
    

    6단계 - Nginx 설치 및 구성

    가이드의 다음 단계는 Mastodons 웹사이트가 작동하도록 Nginx 서버를 설치하는 것입니다.

    다음 명령을 실행하여 Nginx 서버를 설치합니다.

    $ sudo apt install nginx -y
    

    Nginx는 기본 사이트가 구성된 상태로 제공됩니다. 그것을 제거하십시오.

    $ sudo rm /etc/nginx/sites-available/default
    

    또한 기본 사이트에 대한 symlink를 제거하십시오.

    $ sudo rm /etc/nginx/sites-enabled/default
    

    Mastodon용 Nginx 구성 파일을 만듭니다.

    $ sudo touch /etc/nginx/sites-available/mastodon
    

    Mastodons 구성에 대한 symlink를 만듭니다.

    $ sudo ln -s /etc/nginx/sites-available/mastodon /etc/nginx/sites-enabled/mastodon
    

    Nano 편집기에서 Mastodons 구성을 엽니다. (원하는 편집기를 선택할 수 있습니다.)

    $ sudo nano /etc/nginx/sites-available/mastodon
    

    다음 텍스트를 복사하여 붙여넣습니다.

    map $http_upgrade $connection_upgrade {
      default upgrade;
      ''      close;
    }
    
    server {
      listen 80;
      listen [::]:80;
      server_name example.com;
      root /home/user/mastodon/public;
      # Useful for Let's Encrypt
      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 example.com;
    
      ssl_protocols TLSv1.2;
      ssl_ciphers HIGH:!MEDIUM:!LOW:!aNULL:!NULL:!SHA;
      ssl_prefer_server_ciphers on;
      ssl_session_cache shared:SSL:10m;
    
      ssl_certificate     /etc/letsencrypt/live/example.com/fullchain.pem;
      ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    
      keepalive_timeout    70;
      sendfile             on;
      client_max_body_size 80m;
    
      root /home/user/mastodon/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";
        try_files $uri @proxy;
      }
      
      location /sw.js {
        add_header Cache-Control "public, max-age=0";
        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 off;
        proxy_redirect off;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection $connection_upgrade;
    
        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;
    }
    

    위의 구성에서는 Lets encrypt를 SSL 공급자로 사용하고 있다고 가정합니다. 다른 SSL 서비스를 사용하는 경우 키 위치를 편집하고 자습서의 다음 섹션을 건너뛰어야 합니다.

    7단계 - Lets Encrypt 설치 및 구성

    Nginx가 중지되었는지 확인합니다.

    $ sudo systemctl stop nginx
    

    Certbot 리포지토리를 추가합니다.

    $ sudo add-apt-repository ppa:certbot/certbot
    

    시스템 패키지를 업데이트합니다.

    $ sudo apt update
    

    Certbot 도구를 설치합니다.

    $ sudo apt install certbot
    

    인증서를 두 번 생성해야 합니다. 한 번은 TLS SNI 방법을 사용하고 두 번째는 webroot 방법을 사용합니다.

    sudo certbot certonly --standalone -d example.com
    

    이제 webroot 방법을 사용하여 인증서를 만듭니다. 이를 위해서는 Nginx가 실행 중이어야 합니다.

    sudo systemctl start nginx
    sudo certbot certonly --webroot -d example.com -w /home/user/mastodon/public/
    

    이 도구는 인증서를 유지할 것인지 갱신할 것인지 묻습니다. 갱신 옵션을 선택합니다.

    SSL 인증서 자동 갱신 설정

    Encrypt 인증서의 유효 기간은 90일입니다. 그 후에는 다시 갱신해야 합니다. 이를 위해 크론 작업을 생성하여 자동으로 수행할 수 있습니다.

    크론 작업을 만듭니다.

    $ sudo nano /etc/cron.daily/letsencrypt-renew
    

    다음을 복사하여 파일에 붙여넣습니다.

    #!/usr/bin/env bash
    certbot renew
    systemctl reload nginx
    

    Ctrl + X를 누르고 메시지가 표시되면 Y를 입력하여 파일을 저장하고 종료합니다.

    스크립트를 실행 가능하게 만들고 스크립트가 매일 실행되도록 cron 데몬을 다시 시작하십시오.

    $ sudo chmod +x /etc/cron.daily/letsencrypt-renew
    $ sudo systemctl restart cron
    

    8단계 - Mastodon 사용자 생성

    브라우저에서 마스토돈 사이트를 방문하십시오. 다음 화면이 표시됩니다.

    원하는 사용자 이름, 이메일 주소 및 암호를 입력하여 Mastodon 인스턴스에 새 계정을 만듭니다. 다른 Mastodon 서버의 사용자와 연결하는 데 필요한 전체 사용자 이름은 howtoforge@example.com.입니다.

    Mastodon은 가입을 확인하기 위해 확인 메일을 보내드립니다.

    가입을 수동으로 확인할 수도 있습니다. 이를 위해서는 Docker 인스턴스에 SSH로 연결해야 합니다. 현재 Docker 인스턴스를 모두 나열합니다.

    $ docker ps
    

    아래와 같은 출력이 표시됩니다.

    CONTAINER ID        IMAGE                 COMMAND                  CREATED             STATUS                  PORTS                      NAMES
    32f2c4cd2598        tootsuite/mastodon    "/tini -- bash -c 'r…"   16 hours ago        Up 16 hours (healthy)   127.0.0.1:3000->3000/tcp   mastodon_web_1
    76beca2b858d        tootsuite/mastodon    "/tini -- node ./str…"   16 hours ago        Up 16 hours (healthy)   127.0.0.1:4000->4000/tcp   mastodon_streaming_1
    08f7a42b75ac        tootsuite/mastodon    "/tini -- bundle exe…"   16 hours ago        Up 16 hours                                        mastodon_sidekiq_1
    bacaa8c09a85        redis:5.0-alpine      "docker-entrypoint.s…"   17 hours ago        Up 17 hours (healthy)                              mastodon_redis_1
    62e9b2175a53        postgres:9.6-alpine   "docker-entrypoint.s…"   17 hours ago        Up 17 hours (healthy)                              mastodon_db_1
    

    필요한 변경을 수행하려면 스트리밍 컨테이너에 액세스해야 합니다. mastodon_streaming_1 컨테이너에 SSH로 연결합니다.

    $ docker exec -it mastodon_streaming_1 /bin/bash
    

    그러면 컨테이너 내부에서 Bash 셸이 시작됩니다.

    다음 명령을 실행하여 새로 만든 사용자 이름을 승인합니다.

    :~$ RAILS_ENV=production bin/tootctl accounts modify howtoforge --confirm
    

    다음 명령을 실행하여 새로 만든 계정을 관리자로 만듭니다.

    :~$ RAILS_ENV=production bin/tootctl accounts modify howtoforge --role admin
    

    컨테이너를 종료합니다.

    :~$ exit
    

    사용자 이름과 암호를 사용하여 인스턴스에 로그인하면 다음 화면이 표시됩니다.

    Lets Go를 클릭하면 다음 페이지로 이동하여 Mastodon 작동 방식에 대한 몇 가지 기본 사항을 알 수 있습니다.

    Finish Tutorial(튜토리얼 완료)를 클릭하면 마음껏 콘텐츠를 게시할 수 있는 Mastodons 홈페이지가 나타납니다.

    기본 설정 메뉴에서 설정 및 관리 영역에 액세스할 수 있습니다.

    9단계 - 유지보수

    Mastodon 인스턴스의 성능 및 로그를 보려면 https://example.com/sidekiq/로 이동하십시오.

    여기에서 Mastodon 인스턴스와 관련된 다양한 프로세스 및 예약된 작업 목록을 볼 수 있습니다. Dead 또는 Retries 섹션에서 실패한 작업을 확인할 수도 있습니다. 또한 인스턴스의 메모리 사용량도 알려줍니다.

    https://example.com/pghero/에서 인스턴스 데이터베이스의 상태를 확인할 수 있습니다.

    데이터베이스 유지 관리를 수행하고 SQL 쿼리를 실행하고 사용하지 않는 인덱스를 제거할 수 있습니다.

    어떤 이유로 사이트가 전혀 로드되지 않는 경우 Docker에서 생성된 로그를 확인할 수 있습니다.

    이를 위해 먼저 용기를 닫으십시오.

    $ docker-compose down
    

    각 컨테이너에서 생성된 로그를 볼 수 있도록 연결된 상태에서 Docker Compose를 실행합니다.

    $ docker-compose up
    

    10단계 마스토돈 업그레이드

    Mastodon 디렉터리로 전환합니다.

    $ cd /home/user/mastdon
    

    저장소에서 업데이트 다운로드

    $ git fetch
    

    어떤 이유로 docker-compose.yml 파일을 변경한 경우 먼저 다음 명령을 실행해야 합니다.

    $ git status
    

    이것은 당신에게 그것에 대한 모든 변경 사항을 알려줄 것입니다. 파일이 수정된 경우 먼저 변경 사항을 숨깁니다.

    $ git stash
    

    최신 마스토돈 버전을 확인하세요. 릴리스 페이지에서 최신 버전을 확인하십시오.

    $ git checkout <version/tag>
    

    이전에 git stash를 실행한 경우 다음 명령을 실행하여 docker-compose.yml 파일에 대한 변경 사항을 다시 실행합니다.

    $ git stash pop
    

    도커 이미지를 빌드합니다.

    $ docker-compose build
    

    데이터베이스 마이그레이션을 수행합니다.

    $ docker-compose run --rm web rails db:migrate
    

    Mastodons 자산을 사전 컴파일합니다.

    $ docker-compose run --rm web rails assets:precompile
    

    다음 명령을 실행하여 컨테이너를 실행합니다.

    $ docker-compose up -d
    

    이것이 이 튜토리얼의 전부입니다. Mastodon에 대해 자세히 알아보려면 해당 문서를 따르십시오.