- How to run a .NET Core console app as a service using Systemd on Linux (RHEL)
- .NET Core console application #
- .NET Core worker template #
- Adding .NET Core Systemd integration #
- Summary #
- Разворачиваем и демонизируем ASP.NET Core приложение под Linux в виде фонового сервиса
- Подготовка окружения
- Создание приложения
- Install .NET on Linux
- Unsupported releases
- Manual installation
- Install preview versions
- Alpine
- CentOS
- Debian
- Fedora
- openSUSE
- Red Hat
- Ubuntu
How to run a .NET Core console app as a service using Systemd on Linux (RHEL)
Niels Swimberghe — 1/31/2020 — .NET
This article walks us through running a .NET Core console application on systemd. After running a simple console app as a service, we’ll upgrade to the worker template which is designed for long running services/ daemons . Lastly, we’ll add the systemd package for increased integration with systemd.
To learn how to run ASP.NET Core services (web stuff) on Linux, check out «How to run ASP.NET Core as a service on Linux without reverse proxy, no NGINX or Apache».
- Red Hat Enterprise Linux (or a compatible Unix based OS)
- .NET Core 3.1 installed (Get started instructions from Red Hat)
- Sudo privileges
This walkthrough should work for most .NET Core supported Linux distributions, not just RHEL.
.NET Core console application #
Let’s start by making a new console application using the dotnet CLI:
Verify that the console app works by running ` dotnet run `. The output should be «Hello World!».
If the application works, we can publish it somewhere logical such as ‘/srv/HelloWorld’:
The published result contains an executable called ‘HelloWorld’ which will run the application. Let’s verify we can also run the published application:
To run services on Linux, Systemd uses ‘ service unit configuration ‘ files to configure services.
Let’s create the file ‘HelloWorld.service’ inside our project so we can store it in source control along with our code. Add the following content to the file:
Make sure to update the ‘User’ to your username. Refer to the comments in the file for a basic explanation. For more in depth information, read the freedesktop manual page or the Red Hat documentation.
Systemd expects all configuration files to be put under ‘/etc/systemd/system/’. Copy the service configuration file to ‘/etc/systemd/system/HelloWorld.service‘. Then tell systemd to reload the configuration files, and start the service.
Using the ` systemctl status ` command we can view the status of the service:
In addition to the status command, we can use the ‘journalctl’ command to read everything our service is printing to the console. Using the unit-flag (-u), we can filter down to our HelloWorld service.
The console app only logs «Hello world!» to the console and then exits. When querying the status, systemd reports the service is inactive (dead). That’s because the console app starts, runs, and immediately exits. That’s not very useful, so let’s add some code that will let the app run until told to stop. Update Program.cs with the following content:
Let’s publish the app again:
Now we have a minimal application that is continuously running until told to stop.
If the application stops due to a crash, systemd will not automatically restart the service unless we configure that. Add the ‘Restart’ & ‘RestartSec’ options to HelloWorld.service:
Copy the service file, reload, and restart the service:
Now the service will automatically restart in case of a crash. But when the OS reboots, the application will not automatically start. To enable automatic startup of the service on boot, run the following command:
This console app works fine, but Microsoft has provided the worker template which is a more robust solution for long running services/daemons. Let’s upgrade to using the worker template next.
.NET Core worker template #
Let’s create a new empty directory and create the worker using the dotnet CLI:
Verify the worker is functional using the command ` dotnet run `.
If the application works, publish it somewhere logical such as ‘/srv/Worker’:
Let’s verify we can also run the published application:
Create a s ervice unit configuration file called «Worker.service» inside our project:
Copy the service configuration file to ‘ /etc/systemd/system/Worker.service ‘ and tell systemd to reload the configuration files:
Using ‘journalctl’, we can verify that the application is contentiously running successfully. The following ‘journalctl’ command will follow the output of the application. Use Ctrl-C to exit the command.
The .NET Core worker now runs as a systemd service, but the integration between .NET Core and systemd can bi improved on by installing the systemd-integration.
Adding .NET Core Systemd integration #
Microsoft recently added a package to better integrate with systemd. The .NET Core application will notify systemd when it’s ready and when it’s stopping. Additionally, systemd will now understand the different log levels when the .NET Core application logs to output.
Using the dotnet CLI, add the ‘Microsoft.Extensions.Hosting.Systemd’ ( nuget ) package:
Next, we’ll need to add one line to the ‘Program.cs’, ` .UseSystemd() `:
Lastly, we need to update our service unit configuration file to specify ‘type=Notify’:
Let’s publish, reload, and restart the service:
With the Systemd integration in place, we can now use the priority-flag (-p) on ‘journalctl’ to filter the output according to the log levels below:
LogLevel | Syslog level | systemd name |
Trace/Debug | 7 | debug |
Information | 6 | info |
Warning | 4 | warning |
Error | 3 | err |
Critical | 2 | crit |
For example, the following command will only print output with log level 4 and below:
We won’t see much because there’s nothing being logged as a warning, error, or critical.
Update the ‘Worker.cs’ file to include ‘LogWarning’, ‘LogError’, ‘LogCritical’ and republish:
Republish and restart the service:
When we run the same ‘journalctl’ command, we can now see the warning output as bold white text, the error and critical output as red bold text.
The ‘UseSystemd’ function will not do anything when run outside of a systemd service.
The implementation checks if the OS is a Unix system and whether the parent process is systemd.
If not, the systemd integration is skipped.
Summary #
.NET Core has good support for running services on Linux. Using the worker template, we can create a long running service/daemon that integrates well with systemd. Using the systemd hosting integration, systemd is notified when the .NET Core application is ready & also understand the different log levels in .NET.
Источник
Разворачиваем и демонизируем ASP.NET Core приложение под Linux в виде фонового сервиса
Подготовка окружения
Для начала, добавим dotnet-репозиторий:
На выходе получаем примерно следующее:
Теперь обновим индекс наших пакетов:
Далее, мы можем просто установить dotnet-пакет при помощи apt-get:
Теперь можем смело приступать к созданию приложения
Создание приложения
При помощи команды dotnet new мы можем создать шаблон для нашего приложения, подобно шаблонам из Visual Studio. Подробная документация к команде.
На текущий момент (07.2017), команда dotnet new поддерживает следующие шаблоны:
Мы создадим веб-приложение ASP.NET Core:
На выходе консоль выдаст нам следующее сообщение:
Чтобы убедиться, что шаблон сгенерировался правильно, заглянем в содержимое папки при помощи команды ls -la .
Все необходимые папки для сборки приложения на месте, приступим! Для начала, восстановим все пакеты при помощи dotnet restore .
Теперь можем собрать приложение:
Запустим приложение с помощью:
Консоль говорит нам, что приложение запустилось по адресу localhost:5000/. Проверим:
Желающих подробнее узнать, как работает web-сервер отсылаю к официальному источнику.
Теперь убьём процесс нажав Ctrl + C и опубликуем приложение командой dotnet publish. Эта команда упаковывает приложение и все его зависимости для дальнейшего развёртывания (желающим интимных подробностей сюда).
В случае проблем с правами доступа Вам поможет команда sudo chmod и эта страница документации.
Развертывание на сервере.
Если мы хотим развернуть наше приложение под linux-сервером, необходимо настроить прокси и демонизировать процесс запуска приложения. Для проксирования мы будем использовать nginx, для демонизации процесса systemd. Краткое описание утилиты
Как следует из документации выше, с asp.net core в коробке идет kestrel — веб-сервер для asp.net приложений. Зачем нам тогда нужен прокси-сервер? Ответ даётся на официальной странице Microsoft:
Если вы выставляете ваше приложение в интернет, Вы должны использовать IIS, Nginx или Apache как обратный прокси-сервер.
Обратный прокси-сервер получает HTTP запросы из сети и направляет их в Kestrel после первоначальной обработки, как показано на след диаграмме:
Главная причина, по которой следует использовать обратный прокси сервер — безопасность. Kestrel относительно нов и ещё не имеет полного комплекта защиты от атак.
Ещё одна причина, по которой следует использовать обратный прокси-сервер — наличие на сервере нескольких приложений, использующих один порт. Kestrel не поддерживает разделение одного порта между несколькими приложениями.
Так же, использование обратного прокси-сервера может облегчить распределение нагрузки и поддержку SSL.
Как говорилось выше, в качестве прокси-сервера мы будем использовать nginx.
Т.к. в качестве прокси-сервера у нас используется не IIS, следует добавить следующие строки в метод Configure файла Startap.cs.
Здесь мы включаем поддержку ForwardedHeaders мидлвера из пакета. Microsoft.AspNetCore.HttpOverrides, который будет вставлять в Http-запрос заголовки X-Forwarded-For и X-Forwarded-Proto, использующиеся для определения исходного IP адреса клиента и передачи его прокси-серверу. Определение мидлверов и практическое использование так же будет рассмотрено в дальнейших частях этого гайда.
Если у Вас nginx не установлен, выполните следующую команду.
и запустите его командой:
Далее, нам необходимо сконфигурировать nginx для проксирования http-запросов.
Создадим файл /etc/nginx/sites-available/aspnetcore.conf. Папка sites-avalible укахывает nginx-у, какие веб-сайты доступны на текущем сервере для обработки. Добавим в него следующие строки:
Создадим символическую ссылку на aspnetcore.conf в папку sites-enabled, в которой отражаются запущенные nginx-ом сайты.
Nginx настроен на то, чтобы принимать запросы с localhost:8888. Перезапускаем nginx командой sudo service nginx restart , чтобы созданные нами конфигурационные файлы вступили в силу. Проверяем:
502-я ошибка говорит, что сервер перенаправляет нас в другое место и в этом месте что-то пошло не так. В нашем случае — я убил процесс с нашим веб-приложением, которое было ранее запущено командой dotnet run. Потому что могу 🙂
На самом деле, потому что запускать dotnet run в консоли и вечно держать эту вкладку открытой грустно. Именно поэтому процесс будем демонизировать, то есть настроем автозапуск после перезагрузки и автоматическую работу в фоне с помощью systemd.
Для этого создадим файл в директории /etc/systemd/system/ с расширением .service
Назовём его kestrel-test:
И положим в него следующее содержимое:
[Unit]
Description=Example .NET Web API Application running on Ubuntu
[Service]
WorkingDirectory=/home/robounicorn/projects/asp.net/core/test-lesson/bin/Debug/netcoreapp1.1/publish #путь к publish папке вашего приложения
ExecStart=/usr/bin/dotnet /home/robounicorn/projects/asp.net/core/test-lesson/bin/Debug/netcoreapp1.1/publish/test-lesson.dll # путь к опубликованной dll
Restart=always
RestartSec=10 # Перезапускать сервис через 10 секунд при краше приложения
SyslogIdentifier=dotnet-example
User=root # пользователь, под которым следует запускать ваш сервис
Environment=ASPNETCORE_ENVIRONMENT=Production
Теперь включим и запустим сервис при помощи следующих команд:
Проверим статус сервиса:
Если всё было сделано правильно, на эта команда выдаст нам следующее:
Источник
Install .NET on Linux
.NET is available on different Linux distributions. Most Linux platforms and distributions have a major release each year, and most provide a package manager that is used to install .NET. This article describes what is currently supported and which package manager is used.
The rest of this article is a breakdown of each major Linux distribution that .NET supports. All .NET releases remain supported until either the version of .NET reaches end-of-support or the Linux distribution reaches end-of-life.
For the best compatibility, choose a long-term release (LTS) version.
Unsupported releases
The following versions of .NET are вќЊ no longer supported. The downloads for these still remain published:
These unsupported versions aren’t detailed in the sections below and your mileage may vary if you try to install them.
Manual installation
If you don’t want to use a package manager to install .NET on Linux, you can install .NET in one of the following ways:
Be sure to check the appropriate distribution page for more information about any required dependencies that may be missing when you do a manual installation.
Install preview versions
Preview and Release Candidate versions of .NET aren’t available in package managers. You can install previews and release candidates of .NET manually.
Alpine
The following table is a list of currently supported .NET releases and the versions of Alpine they’re supported on. These versions remain supported until either the version of .NET reaches end-of-support or the version of Alpine reaches end-of-life.
- A вњ”пёЏ indicates that the version of Alpine or .NET is still supported.
- A вќЊ indicates that the version of Alpine or .NET isn’t supported on that Alpine release.
- When both a version of Alpine and a version of .NET have вњ”пёЏ, that OS and .NET combination is supported.
Alpine | .NET Core 2.1 | .NET Core 3.1 | .NET 5.0 |
---|---|---|---|
вњ”пёЏ 3.13 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
вњ”пёЏ 3.12 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
вњ”пёЏ 3.11 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
вњ”пёЏ 3.10 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вќЊ 5.0 |
вќЊ 3.9 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вќЊ 5.0 |
вќЊ 3.8 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вќЊ 5.0 |
CentOS
CentOS 7 uses Yum as a package manager and CentOS 8 uses DNF.
The following table is a list of currently supported .NET releases on both CentOS 7 and CentOS 8. These versions remain supported until either the version of .NET reaches end-of-support or the version of CentOS is no longer supported.
CentOS | .NET Core 2.1 | .NET Core 3.1 | .NET 5.0 |
---|---|---|---|
вњ”пёЏ 8 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
вњ”пёЏ 7 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
Debian
Debian uses APT (Advanced Package Tool) as a package manager.
The following table is a list of currently supported .NET releases and the versions of Debian they’re supported on. These versions remain supported until either the version of .NET reaches end-of-support or the version of Debian reaches end-of-life.
- A вњ”пёЏ indicates that the version of Debian or .NET is still supported.
- A вќЊ indicates that the version of Debian or .NET isn’t supported on that Debian release.
- When both a version of Debian and a version of .NET have вњ”пёЏ, that OS and .NET combination is supported.
Debian | .NET Core 2.1 | .NET Core 3.1 | .NET 5.0 |
---|---|---|---|
вњ”пёЏ 11 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
вњ”пёЏ 10 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
вњ”пёЏ 9 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
вќЊ 8 | вњ”пёЏ 2.1 | вќЊ 3.1 | вќЊ 5.0 |
Fedora
Fedora uses DNF as its package manager.
The following table is a list of currently supported .NET releases and the versions of Fedora they’re supported on. These versions remain supported until either the version of .NET reaches end-of-support or the version of Fedora reaches end-of-life.
- A вњ”пёЏ indicates that the version of Fedora or .NET is still supported.
- A вќЊ indicates that the version of Fedora or .NET isn’t supported on that Fedora release.
- When both a version of Fedora and a version of .NET have вњ”пёЏ, that OS and .NET combination is supported.
Fedora | .NET Core 2.1 | .NET Core 3.1 | .NET 5.0 |
---|---|---|---|
вњ”пёЏ 34 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
вњ”пёЏ 33 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
вњ”пёЏ 32 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
вќЊ 31 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вќЊ 5.0 |
вќЊ 30 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вќЊ 5.0 |
вќЊ 29 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вќЊ 5.0 |
вќЊ 28 | вњ”пёЏ 2.1 | вќЊ 3.1 | вќЊ 5.0 |
вќЊ 27 | вњ”пёЏ 2.1 | вќЊ 3.1 | вќЊ 5.0 |
openSUSE
openSUSE uses zypper as the package manager.
The following table is a list of currently supported .NET releases on openSUSE 15. These versions remain supported until either the version of .NET reaches end-of-support or the version of openSUSE is no longer supported.
openSUSE | .NET Core 2.1 | .NET Core 3.1 | .NET 5.0 |
---|---|---|---|
вњ”пёЏ 15 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
Red Hat
Red Hat Enterprise Linux (RHEL) uses yum (RHEL 7) and DNF (RHEL 8) as the package manager.
The following table is a list of currently supported .NET releases on both RHEL 7 and RHEL 8. These versions remain supported until either the version of .NET reaches end-of-support or the version of RHEL is no longer supported.
- A вњ”пёЏ indicates that the version of RHEL or .NET is still supported.
- A вќЊ indicates that the version of RHEL or .NET isn’t supported on that RHEL release.
- When both a version of RHEL and a version of .NET have вњ”пёЏ, that OS and .NET combination is supported.
RHEL | .NET Core 2.1 | .NET Core 3.1 | .NET 5.0 |
---|---|---|---|
вњ”пёЏ 8 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
вњ”пёЏ 7 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
For more information, see Install .NET on RHEL.
SLES uses zypper as the package manager.
The following table is a list of currently supported .NET releases on both SLES 12 SP2 and SLES 15. These versions remain supported until either the version of .NET reaches end-of-support or the version of SLES is no longer supported.
- A вњ”пёЏ indicates that the version of SLES or .NET is still supported.
- A вќЊ indicates that the version of SLES or .NET isn’t supported on that SLES release.
- When both a version of SLES and a version of .NET have вњ”пёЏ, that OS and .NET combination is supported.
SLES | .NET Core 2.1 | .NET Core 3.1 | .NET 5.0 |
---|---|---|---|
вњ”пёЏ 15 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
вњ”пёЏ 12 SP2 | вњ”пёЏ 2.1 | вњ”пёЏ 3.1 | вњ”пёЏ 5.0 |
For more information, see Install .NET on SLES.
Ubuntu
Ubuntu uses APT (Advanced Package Tool) as a package manager.
The following table represents the support status of Ubuntu and .NET.
Источник