Gotify - простой сервер для отправки и получения push-сообщений.

Предпосылки

  • Сервер с Ubuntu 22.04 в качестве ОС
  • Права пользователя: пользователь root или обычный пользователь с привилегиями sudo

Шаг 1. Обновите систему

Свежая установка Ubuntu 22.04 требует обновления пакетов до последних доступных версий.

sudo apt-get update -y && sudo apt-get upgrade -y

Шаг 2. Установите PostgreSQL

Установите пакет Postgres вместе с пакетом -contrib, который добавляет некоторые дополнительные утилиты и функции:

sudo apt install postgresql postgresql-contrib

После установки запустите и включите службу PostgreSQL.

sudo systemctl enable postgresql.service && sudo systemctl start postgresql.service

Шаг 3. Создание базы данных

Нам нужно создать базу данных для Gotify для работы.

sudo -u postgres psql -c "CREATE USER gotify WITH PASSWORD 'yourpassword';"
sudo -u postgres psql -c "CREATE DATABASE gotify_db OWNER gotify;"
sudo -u postgres psql -c "GRANT ALL PRIVILEGES ON DATABASE gotify_db TO gotify;"

Шаг 4. Установите Gotify

Мы установим Gotify в /var/www/gotifypush, измените путь, где это необходимо, если вы хотите установить его в другом месте.

sudo mkdir -p /var/www/gotifypush
sudo useradd -r gotify
sudo chown -R gotify /var/www/gotifypush

Установите правильное разрешение папки

sudo chmod 775 /var/www/gotifypush

Загрузите последний двоичный файл со страницы Github https://github.com/gotify/server/releases.

wget https://github.com/gotify/server/releases/download/v2.2.4/gotify-linux-amd64.zip

Разархивируйте архив.

unzip gotify-linux-amd64.zip

Сделайте бинарный исполняемый файл.

sudo chmod +x /var/www/gotifypush/gotify-linux-amd64

Создайте новый файл с именем config.yml

sudo nano config.yml

Просто добавьте эту конфигурацию ниже

Выйти из настроек SSL | Добавьте свой домен в настройках стрима | Добавьте пользователя базы данных и перейдите в настройки базы данных | Обновите пользователя-администратора своей учетной записи и перейдите в настройки пользователя по умолчанию, а также обновите каталог установки gotify.

server:
  listenaddr: "" # the address to bind on, leave empty to bind on all addresses
  port: 9004 # the port the HTTP server will listen on

  ssl:
    enabled: false # if https should be enabled
    redirecttohttps: false # redirect to https if site is accessed by http
    listenaddr: "" # the address to bind on, leave empty to bind on all addresses
    port: 443 # the https port
    certfile: # the cert file (leave empty when using letsencrypt)
    certkey: # the cert key (leave empty when using letsencrypt)
    letsencrypt:
      enabled: false # if the certificate should be requested from letsencrypt
      accepttos: false # if you accept the tos from letsencrypt
      cache:  # the directory of the cache from letsencrypt
      hosts: # the hosts for which letsencrypt should request certificates
      - push.example.com
  
  responseheaders: # response headers are added to every response (default: none)
    Strict-Transport-Security: max-age=31536000
    X-Xss-Protection: 1; mode=block

  cors: # Sets cors headers only when needed and provides support for multiple allowed origins. Overrides Access-Control-* Headers in response headers.
    alloworigins:
      # - "example.com"
    allowmethods:
      # - "GET"
      # - "POST"
    allowheaders:
      # - "Authorization"
      # - "content-type"

  stream:
    allowedorigins: # allowed origins for websocket connections (same origin is always allowed)
  #    - ".+.example.com"
  #    - "push.example.com"

database: # for database see (configure database section)
  dialect: postgres
  connection: host=localhost port=5432 user=gotify dbname=gotify_db password=yourpassword

defaultuser: # on database creation, gotify creates an admin user
  name: admin # the username of the default user
  pass: admin # the password of the default user
passstrength: 10 # the bcrypt password strength (higher = better but also slower)
uploadedimagesdir: /var/www/gotifypush/data/images # the directory for storing uploaded images
pluginsdir: /var/www/gotifypush/data/plugins # the directory where plugin resides

Затем создайте новый файл bash с именем start.sh в каталоге.

#!/bin/bash

./gotify-linux-amd64

Сделайте исполняемый файл.

sudo chmod +x /var/www/gotifypush/start.sh

Общий список файлов в папке установки Gotify var/www/gotifypush

- config.yml
- start.sh
- gotify-linux-amd64

Шаг 5. Настройте службу systemd для запуска Gotify/сервера навсегда

sudo nano /etc/systemd/system/gotifypush.service
[Unit]
Description=Start Gotify - a simple server for sending and receiving messages
Requires=network.target
After=network.target

[Service]
Type=simple
User=gotify
WorkingDirectory=/var/www/gotifypush
ExecStart=/bin/bash /var/www/gotifypush/start.sh
Restart=always
RestartSec=3

[Install]
WantedBy=multi-user.target

CTRL + X и Enter, чтобы сохранить конфигурацию файла службы. Далее Включить службу systemd для сервера Gotify

sudo systemctl daemon-reload
sudo systemctl enable gotifypush.service
sudo systemctl start gotifypush.service

Проверить состояние

sudo systemctl status gotifypush.service

Restart

sudo systemctl restart gotifypush.service

Шаг 6. Настройте Nginx в качестве обратного прокси

sudo apt-get -y install nginx

Создайте обратный конфигурацию прокси-сервера для Gotify.

sudo nano /etc/nginx/sites-available/gotifypush.conf

Заполните файл следующей конфигурацией.

server {
  listen 443 ssl;

  # Here goes your domain / subdomain
  server_name push.example.com;

  ssl_certificate path/to/certificate;
  ssl_certificate_key path/to/certificate;

  location / {
    # We set up the reverse proxy
    proxy_pass         http://127.0.0.1:9004/;
    proxy_http_version 1.1;

    # Ensuring it can use websockets
    proxy_set_header   Upgrade $http_upgrade;
    proxy_set_header   Connection "upgrade";
    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 http;
    proxy_redirect     http:// $scheme://;

    # The proxy must preserve the host because gotify verifies the host with the origin
    # for WebSocket connections
    proxy_set_header   Host $http_host;

    # These sets the timeout so that the websocket can stay alive
    proxy_connect_timeout   1m;
    proxy_send_timeout      1m;
    proxy_read_timeout      1m;
  }
}

Включите конфигурацию обратной прокси-сервера

sudo ln -s /etc/nginx/sites-available/gotifypush.conf /etc/nginx/sites-enabled/gotifypush.conf

Проверка конфигурации и перезагрузите службу Nginx.

sudo nginx -t
sudo systemctl restart nginx.service

Обновление Gotify

Обновления до последней версии Gotify просто загрузите и замените двоичный файл.

Остановите службу gotify

sudo systemctl stop gotifypush.service

Переименовать старую версию

sudo mv gotify-linux-amd64 gotify-linux-amd64-old

Загрузите последний двоичный файл со страницы Github https://github.com/gotify/server/releases.

Загрузите последнюю версию gotify и переместите ее в /var/www/gotifypush каталог

wget https://github.com/gotify/server/releases/download/<Latest-Release>/gotify-linux-amd64.zip

Разархивируйте архив.

unzip gotify-linux-amd64.zip

Сделайте бинарный исполняемый файл.

sudo chmod +x /var/www/gotifypush/gotify-linux-amd64

Проверьте свою установку — вы должны увидеть, что в вашей системе установлена ​​последняя версия Gotify.

./start.sh

Удалите загруженные ресурсы и старую версию Gotify

rm -rf gotify-linux-amd64.zip LICENSE licenses gotify-linux-amd64-old
sudo systemctl start gotifypush.service
sudo systemctl daemon-reload
sudo systemctl restart gotifypush.service
sudo systemctl restart nginx.service

Если ваш тест установки пройден, нажмите CTRL + C, чтобы остановить и запустить службу systemd

Подведение итогов

Собственно на этом всё. Если вам понравился этот пост о том, как установить Gotify на Ubuntu 22.04, поделитесь им с друзьями в социальных сетях. Спасибо.