Nginx net core linux

Nginx net core linux

ASP.NET Core is a fully open source, high-performance, and cross-platform framework. ASP.NET Core runs anywhere you need it to (Windows, Mac, Linux). If you compare hosting apps on Windows vs Linux, Linux hosting is usually cheaper. At the time of writing this post, you can find a cheap Linux VPS for as little as $3.5 a month.

In this article, we will be using Linux VPS, having CentOS 7 installed, ASP.Net Core 2.0 application and Nginx as the reverse proxy. I will try to cover most of the details for basic web hosting including some safety measures, this post might get a little long, bear with me, please. The hosting process is broken into following steps:

  1. Get Linux VPS Setup Linux Host
  2. Install .NET Core
  3. Deploying ASP.Net Core application
  4. Configure Nginx as the reverse proxy

Step 1. Setup Linux Host

You can pick any VPS provider of your choice and any distribution of Linux, in this post I am using a $3.5 CentOS 7 64-bit VPS with 1 CPU core and 1 GB Ram from RamNode(affiliate link). Why CentOS and why not any other distribution? CentOS is a free clone of Red Hat Enterprise Linux. It is considered more stable, secure and supports most of the control panels (including the most popular one — cPanel) so it is preferred distribution for businesses and in the hosting industry.

Once you get VPS, you will receive an IP and root password which you will use to connect to the VPS. You need an SSH client to connect to Linux VPS. There are free SSH clients available, SmartTTY and Putty are very common ones. I will be using SmartTTY for this demo.

Install and open SmartTTY and enter the IP, port, username, and password.

Click connect, it should open the terminal window:

Now that we have connected to the VPS via SSH, next we will configure the Linux host.

We could simply install .NET Core, Nginx and run the application, but it is strongly recommended to first follow some basic common practices of initial server setup to cover our bases. I will cover the bare minimum steps which you should do for each of the Linux servers. This will apply for some basic security protection on the server. For example, change the default root login, change default SSH port etc. If you are hosting your app just for fun, you can skip the rest of the configuration and jump directly to step 2 Install .NET Core.

Change the default password for root. Use passwd command to change the default password provided by the VPS provider.

You will be asked to enter the password twice.

Create a new «Sudo» user. We will use this new user to login to the server from next time onwards, and disable root login because root is standard username hackers can easily guess.

  • Use the adduser command to add a new user, replace username with the user you want to create:
  • Use the passwd command to change the password for the user you created:

You will be prompted for a new password and confirm the password.

    Add user to wheel group by using the usermod command:

    In CentOS, by default members of wheel group have sudo privileges.

    Verify the new user has sudo access:
    Switch user by using «su» command

List the contents of /root directory, which is only accessible to root user.

You will be prompted to enter the account password, once you enter that, the command should run with root privileges.

Now we can use this new user to perform all tasks we could with root user. Just remember to add sudo to commands.

Change default SSH port, disable root login and allow the new user to login via SSH. SSH default port number is 22 and everybody knows it, including the hackers, it is not safe. Changing the default SSH port number is the basic step towards security, for production servers, in my opinion, the best way to protect SSH server is to implement password-less login using certificates and encryption. You can find many articles on how to implement password-less login into SSH server, I am going to focus on just changing the default port 22 to something else in this post. To change the SSH default port, we need to edit «sshd_config» file. You can use any editor of your choice, I am going to use Nano editor:
Install nano:

Eidt «sshd_config» file:

Find the following line:

Remove # symbol and change the default port 22 to something else, 20020 for example:

Remove the # symbol and change yes to no:

At the end of the file, add this line, obviously, replace the username with the user you created:

Save and close the file, do not exit the session yet, allow port 20020 on firewall first, otherwise, you will not be able to login into the VM.

Restart SSH service:

Allow port 20020 on the firewall:

If you get «firewall-cmd: command not found» error, install and enable firewalld and run the command again, here are the commands to just do that:

Reload firewall config:

Now you should be able to login into the VM using the new SSH port with the new user, and login for root user is disabled via SSH.

Step 2. Install .NET Core

Run following commands to install .NET Core in CentOS

Register the Microsoft signature key:

Add the dotnet product feed:

Install the .NET Core SDK and add dotnet to PATH:

Verify installation by running:

Step 3. Deploying ASP.NET Core application

I am going to use an existing application, publish it and copy that over to VPS. Publish the application by using the following command:

Copy the output contents over to the VPS using any SFTP or FTP tool. I am using WinSCP to copy the published code. You can run the application by using the dotnet command on the command prompt, you need a monitor to run it and keep it running. Let’s create a service for that:

Create the service definition file:

Add following content to the service file:

Now you need to enable the service and run it:

The status command should show the service as running if the configuration was correct. Now, our web application is running, kestrel by default listens on port 5000, so our application is available on http://localhost:5000.

Kestrel is good for serving dynamic content, but it is not a fully featured web-server. A reverse proxy server allows you to offload work like serving static content, cashing requests, compressing requests, and SSL termination from the HTTP server. In the next step, we will configure Nginx as the reverse proxy.

Step 4. Configure Nginx as Reverse Proxy

Almost all major Linux distro comes with Apache by default, since we are going to use Nginx only and Apache configuration might cause issues when Nginx is installed, we will turn Apache off. This will stop all the existing sites hosted in Apache. If you have any sites hosted in Apache. Since we do not have any site installed on Apache, we will stop and disable the Apache. Stop command will stop the Apache and disable command will make sure Apache does not start on next reboot:

Add Nginx repository, install Nginx, Start and Enable:

Enabling Nginx will make sure it is started on every reboot.

Check the status of Nginx service:

If you are running a firewall, run following commands to allow HTTP and HTTPS traffic:

You can verify right away that Nginx installed by browsing your server’s public IP address in any browser. E.g.

You should see a default Nginx page saying «Welcome to nginx». If you see this page, nginx is installed correctly.

I am changing the nginx config file directly, ideally, for production, you should create a separate config file. Open nginx config file:

Update the config file:

Verify and reload the config:

All set, now your website should be available when you type the IP of the server:

Have any questions, suggestions or feedback? Please leave a comment below.

Источник

Разворачиваем и демонизируем 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

Теперь включим и запустим сервис при помощи следующих команд:

Проверим статус сервиса:

Если всё было сделано правильно, на эта команда выдаст нам следующее:

Источник

.NET Core with NGINX on Linux

Having .NET Core with NGINX on Linux is easier that you might imagine. In this article I will talk about my experience related to NGINX and what it takes to configure it for the first time. If you come from an IIS/Windows world like me, where you know everything by heart, the declarative approach in NGINX might be a bit odd.

I already have Kestrel, why do I need something else?

Kestrel is the default server implementation for ASP.NET Core, and it is super fast, cross-platform, customizable and it can run on its own. It looks like it is the perfect server, but it was lacking a lot of features related to security. Another thing about Kestrel is that “used as an edge server without a reverse proxy server doesn’t support sharing the same IP and port among multiple processes”.

Although is not required, it is recommend to have a reverse proxy in front of Kestrel because it will give you an extra layer of configuration and defense and integrates smoothly with the existing infrastructure.

What is NGINX?

NGINX is an open source software for web serving, load balancing, media streaming, that also has reverse proxy capabilities. One of the goals behind NGINX was to create the fastest web server out there. Now, is one of the most popular servers out there.

Installing NGINX on Linux

Depending on your Linux distribution the package manager might differ. I had Red Hat sudo yum install nginx did the trick. After a successful installation you will find the files and folders for NGINX under /etc/nginx path on the server looking pretty much like this( without the highlighted folders)

nginx structure

One of the most important files out there is the nginx.conf file that will contain or reference other configurations for your web apps. Bear in mind that, in order to be able to start NGINX server this configuration will have to be valid.

Configuring NGINX for all your apps

Now, I’ve cleaned up a bit the default nginx.conf and it looks like this:

Exit fullscreen mode

For easier formatting, I used Visual Studio Code with 2 extensions: Nginx configuration and Nginx Formatter.

At line 28, I’ve added an include statement because I want to place all my configurations for different website in separate files, in sites_enabled folder.

After that, I’ve created the sites_enabled folder, and the certs folder (that will contain certificates). In the sites_enabled folder, I’ve created a file named myapi.conf and inside it, I’ve added this:

Exit fullscreen mode

In the configuration file I have 2 ‘location’ sections, one for an UI app, and one for the API. The two apps I want to be served from the same ‘domain’ but on a different path:

  • the ui app from the root like /myapp
  • the api from something deeper in the hierarchy like: /myapp/api

Once this is done, you can test the nginx configuration by running nginx -t -c /etc/nginx/nginx.conf in the terminal. If that is successful, you can go ahead, start NGINX server

Useful NGINX commands

sudo nginx service start

sudo nginx service restart

sudo nginx service status

In summary

We looked at how to configure .NET Core with NGINX on Linux, but the same configs will work on Windows also. The only thing you need to do besides configure NGINX is torun the API as a Linux Service, and to make sure is up.

In a following post we will add https in front of our API, because we need to care about security.

Источник

Читайте также:  Закрепить строку excel mac os
Оцените статью