Меню Закрыть

Asp net core deploy linux

Содержание

This guide explains setting up a production-ready ASP.NET Core environment on an Ubuntu 16.04 server. These instructions likely work with newer versions of Ubuntu, but the instructions haven’t been tested with newer versions.

For information on other Linux distributions supported by ASP.NET Core, see Prerequisites for .NET Core on Linux.

For Ubuntu 14.04, supervisord is recommended as a solution for monitoring the Kestrel process. systemd isn’t available on Ubuntu 14.04. For Ubuntu 14.04 instructions, see the previous version of this topic.

  • Places an existing ASP.NET Core app behind a reverse proxy server.
  • Sets up the reverse proxy server to forward requests to the Kestrel web server.
  • Ensures the web app runs on startup as a daemon.
  • Configures a process management tool to help restart the web app.

Prerequisites

  1. Access to an Ubuntu 16.04 server with a standard user account with sudo privilege.
  2. Install the .NET Core runtime on the server.
  1. Visit the Download .NET Core page.
  2. Select the latest non-preview .NET Core version.
  3. Download the latest non-preview runtime in the table under Run apps — Runtime.
  4. Select the Linux Package manager instructions link and follow the Ubuntu instructions for your version of Ubuntu.
  • An existing ASP.NET Core app.
  • At any point in the future after upgrading the shared framework, restart the ASP.NET Core apps hosted by the server.

    Publish and copy over the app

    If the app is run locally and isn’t configured to make secure connections (HTTPS), adopt either of the following approaches:

    • Configure the app to handle secure local connections. For more information, see the HTTPS configuration section.
    • Remove https://localhost:5001 (if present) from the applicationUrl property in the Properties/launchSettings.json file.

    Run dotnet publish from the development environment to package an app into a directory (for example, bin/Release/ /publish) that can run on the server:

    The app can also be published as a self-contained deployment if you prefer not to maintain the .NET Core runtime on the server.

    Copy the ASP.NET Core app to the server using a tool that integrates into the organization’s workflow (for example, SCP, SFTP). It’s common to locate web apps under the var directory (for example, var/www/helloapp).

    Under a production deployment scenario, a continuous integration workflow does the work of publishing the app and copying the assets to the server.

    to verify the app works on Linux locally.

    Configure a reverse proxy server

    A reverse proxy is a common setup for serving dynamic web apps. A reverse proxy terminates the HTTP request and forwards it to the ASP.NET Core app.

    Use a reverse proxy server

    Kestrel is great for serving dynamic content from ASP.NET Core. However, the web serving capabilities aren’t as feature rich as servers such as IIS, Apache, or Nginx. A reverse proxy server can offload work such as serving static content, caching requests, compressing requests, and HTTPS termination from the HTTP server. A reverse proxy server may reside on a dedicated machine or may be deployed alongside an HTTP server.

    For the purposes of this guide, a single instance of Nginx is used. It runs on the same server, alongside the HTTP server. Based on requirements, a different setup may be chosen.

    Because requests are forwarded by reverse proxy, use the Forwarded Headers Middleware from the Microsoft.AspNetCore.HttpOverrides package. The middleware updates the Request.Scheme , using the X-Forwarded-Proto header, so that redirect URIs and other security policies work correctly.

    Any component that depends on the scheme, such as authentication, link generation, redirects, and geolocation, must be placed after invoking the Forwarded Headers Middleware. As a general rule, Forwarded Headers Middleware should run before other middleware except diagnostics and error handling middleware. This ordering ensures that the middleware relying on forwarded headers information can consume the header values for processing.

    Invoke the UseForwardedHeaders method in Startup.Configure before calling UseAuthentication or similar authentication scheme middleware. Configure the middleware to forward the X-Forwarded-For and X-Forwarded-Proto headers:

    If no ForwardedHeadersOptions are specified to the middleware, the default headers to forward are None .

    Proxies running on loopback addresses (127.0.0.0/8, [::1]), including the standard localhost address (127.0.0.1), are trusted by default. If other trusted proxies or networks within the organization handle requests between the Internet and the web server, add them to the list of KnownProxies or KnownNetworks with ForwardedHeadersOptions. The following example adds a trusted proxy server at IP address 10.0.0.100 to the Forwarded Headers Middleware KnownProxies in Startup.ConfigureServices :

    Install Nginx

    Use apt-get to install Nginx. The installer creates a systemd init script that runs Nginx as daemon on system startup. Follow the installation instructions for Ubuntu at Nginx: Official Debian/Ubuntu packages.

    If optional Nginx modules are required, building Nginx from source might be required.

    Since Nginx was installed for the first time, explicitly start it by running:

    Verify a browser displays the default landing page for Nginx. The landing page is reachable at http:// /index.nginx-debian.html .

    Читайте также:  Iphone se аккумулятор совместимость

    Configure Nginx

    To configure Nginx as a reverse proxy to forward requests to your ASP.NET Core app, modify /etc/nginx/sites-available/default. Open it in a text editor, and replace the contents with the following:

    When no server_name matches, Nginx uses the default server. If no default server is defined, the first server in the configuration file is the default server. As a best practice, add a specific default server which returns a status code of 444 in your configuration file. A default server configuration example is:

    With the preceding configuration file and default server, Nginx accepts public traffic on port 80 with host header example.com or *.example.com . Requests not matching these hosts won’t get forwarded to Kestrel. Nginx forwards the matching requests to Kestrel at http://localhost:5000 . See How nginx processes a request for more information. To change Kestrel’s IP/port, see Kestrel: Endpoint configuration.

    Failure to specify a proper server_name directive exposes your app to security vulnerabilities. Subdomain wildcard binding (for example, *.example.com ) doesn’t pose this security risk if you control the entire parent domain (as opposed to *.com , which is vulnerable). See rfc7230 section-5.4 for more information.

    Once the Nginx configuration is established, run sudo nginx -t to verify the syntax of the configuration files. If the configuration file test is successful, force Nginx to pick up the changes by running sudo nginx -s reload .

    To directly run the app on the server:

    If the app runs on the server but fails to respond over the Internet, check the server’s firewall and confirm that port 80 is open. If using an Azure Ubuntu VM, add a Network Security Group (NSG) rule that enables inbound port 80 traffic. There’s no need to enable an outbound port 80 rule, as the outbound traffic is automatically granted when the inbound rule is enabled.

    When done testing the app, shut the app down with Ctrl+C at the command prompt.

    Monitor the app

    The server is setup to forward requests made to http:// :80 on to the ASP.NET Core app running on Kestrel at http://127.0.0.1:5000 . However, Nginx isn’t set up to manage the Kestrel process. systemd can be used to create a service file to start and monitor the underlying web app. systemd is an init system that provides many powerful features for starting, stopping, and managing processes.

    Create the service file

    Create the service definition file:

    The following is an example service file for the app:

    If the user www-data isn’t used by the configuration, the user defined here must be created first and given proper ownership for files.

    Use TimeoutStopSec to configure the duration of time to wait for the app to shut down after it receives the initial interrupt signal. If the app doesn’t shut down in this period, SIGKILL is issued to terminate the app. Provide the value as unitless seconds (for example, 150 ), a time span value (for example, 2min 30s ), or infinity to disable the timeout. TimeoutStopSec defaults to the value of DefaultTimeoutStopSec in the manager configuration file (systemd-system.conf, system.conf.d, systemd-user.conf, user.conf.d). The default timeout for most distributions is 90 seconds.

    Linux has a case-sensitive file system. Setting ASPNETCORE_ENVIRONMENT to "Production" results in searching for the configuration file appsettings.Production.json, not appsettings.production.json.

    Some values (for example, SQL connection strings) must be escaped for the configuration providers to read the environment variables. Use the following command to generate a properly escaped value for use in the configuration file:

    Colon ( : ) separators aren’t supported in environment variable names. Use a double underscore ( __ ) in place of a colon. The Environment Variables configuration provider converts double-underscores into colons when environment variables are read into configuration. In the following example, the connection string key ConnectionStrings:DefaultConnection is set into the service definition file as ConnectionStrings__DefaultConnection :

    Save the file and enable the service.

    Start the service and verify that it’s running.

    With the reverse proxy configured and Kestrel managed through systemd, the web app is fully configured and can be accessed from a browser on the local machine at http://localhost . It’s also accessible from a remote machine, barring any firewall that might be blocking. Inspecting the response headers, the Server header shows the ASP.NET Core app being served by Kestrel.

    View logs

    Since the web app using Kestrel is managed using systemd , all events and processes are logged to a centralized journal. However, this journal includes all entries for all services and processes managed by systemd . To view the kestrel-helloapp.service -specific items, use the following command:

    For further filtering, time options such as —since today , —until 1 hour ago or a combination of these can reduce the amount of entries returned.

    Data protection

    The ASP.NET Core Data Protection stack is used by several ASP.NET Core middlewares, including authentication middleware (for example, cookie middleware) and cross-site request forgery (CSRF) protections. Even if Data Protection APIs aren’t called by user code, data protection should be configured to create a persistent cryptographic key store. If data protection isn’t configured, the keys are held in memory and discarded when the app restarts.

    Читайте также:  Чип для отслеживания животных под кожу

    If the key ring is stored in memory when the app restarts:

    • All cookie-based authentication tokens are invalidated.
    • Users are required to sign in again on their next request.
    • Any data protected with the key ring can no longer be decrypted. This may include CSRF tokens and ASP.NET Core MVC TempData cookies.

    To configure data protection to persist and encrypt the key ring, see:

    Long request header fields

    Proxy server default settings typically limit request header fields to 4 K or 8 K depending on the platform. An app may require fields longer than the default (for example, apps that use Azure Active Directory). If longer fields are required, the proxy server’s default settings require adjustment. The values to apply depend on the scenario. For more information, see your server’s documentation.

    Don’t increase the default values of proxy buffers unless necessary. Increasing these values increases the risk of buffer overrun (overflow) and Denial of Service (DoS) attacks by malicious users.

    Secure the app

    Enable AppArmor

    Linux Security Modules (LSM) is a framework that’s part of the Linux kernel since Linux 2.6. LSM supports different implementations of security modules. AppArmor is a LSM that implements a Mandatory Access Control system which allows confining the program to a limited set of resources. Ensure AppArmor is enabled and properly configured.

    Configure the firewall

    Close off all external ports that are not in use. Uncomplicated firewall (ufw) provides a front end for iptables by providing a command line interface for configuring the firewall.

    A firewall will prevent access to the whole system if not configured correctly. Failure to specify the correct SSH port will effectively lock you out of the system if you are using SSH to connect to it. The default port is 22. For more information, see the introduction to ufw and the manual.

    Install ufw and configure it to allow traffic on any ports needed.

    Secure Nginx

    Change the Nginx response name

    Configure options

    Configure the server with additional required modules. Consider using a web app firewall, such as ModSecurity, to harden the app.

    HTTPS configuration

    Configure the app for secure (HTTPS) local connections

    The dotnet run command uses the app’s Properties/launchSettings.json file, which configures the app to listen on the URLs provided by the applicationUrl property (for example, https://localhost:5001;http://localhost:5000 ).

    Configure the app to use a certificate in development for the dotnet run command or development environment (F5 or Ctrl+F5 in Visual Studio Code) using one of the following approaches:

    Configure the reverse proxy for secure (HTTPS) client connections

    Configure the server to listen to HTTPS traffic on port 443 by specifying a valid certificate issued by a trusted Certificate Authority (CA).

    Harden the security by employing some of the practices depicted in the following /etc/nginx/nginx.conf file. Examples include choosing a stronger cipher and redirecting all traffic over HTTP to HTTPS.

    Adding an HTTP Strict-Transport-Security (HSTS) header ensures all subsequent requests made by the client are over HTTPS.

    Don’t add the HSTS header or chose an appropriate max-age if HTTPS will be disabled in the future.

    Add the /etc/nginx/proxy.conf configuration file:

    Edit the /etc/nginx/nginx.conf configuration file. The example contains both http and server sections in one configuration file.

    Secure Nginx from clickjacking

    Clickjacking, also known as a UI redress attack, is a malicious attack where a website visitor is tricked into clicking a link or button on a different page than they’re currently visiting. Use X-FRAME-OPTIONS to secure the site.

    To mitigate clickjacking attacks:

    Edit the nginx.conf file:

    Add the line add_header X-Frame-Options "SAMEORIGIN"; .

    MIME-type sniffing

    This header prevents most browsers from MIME-sniffing a response away from the declared content type, as the header instructs the browser not to override the response content type. With the nosniff option, if the server says the content is "text/html", the browser renders it as "text/html".

    Edit the nginx.conf file:

    Add the line add_header X-Content-Type-Options "nosniff"; and save the file, then restart Nginx.

    I am able to deploy CoreCLR ASP.NET apps to Linux and have them run, hurray. To do this I am using

    dnu publish —no-source -o

    which gives me a dest-dir full of many CoreCLR packages, one of which is a package for my published app specifically.

    This folder is pretty big, around 50 MB for the simple Web Application Basic (no auth) described at https://azure.microsoft.com/en-us/documentation/articles/web-sites-create-web-app-using-vscode/ .

    Is there a sensible way to deploy to Linux without pushing so much around? Can I get rid of a bunch of those CoreCLR packages somehow? Is there a good way of deploying source-only and doing the work on the server (I may have seen something about this, but I lost it if I did)?

    Читайте также:  Как в экселе сделать выборку из таблицы

    1 Answer 1

    You are already publishing without runtime ( —runtime option on dnu publish ) which reduces the bundle size significantly.

    You need to get somehow those packages on the server. Even if you deploy only the sources, you’ll have to restore which will download the same amount of packages. Also, running from sources makes the application start significantly slower (depending on the number of dependencies).

    However, if you publish the entire bundle once and you app’s dependencies don’t change, you can upload only the folders corresponding to your projects, instead of re-uploading all the dependencies.

    Подготовка окружения

    Для начала, добавим 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 секунд при краше приложения
    Syslog > User=root # пользователь, под которым следует запускать ваш сервис
    Environment=ASPNETCORE_ENVIRONMENT=Production

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

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

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

    Рекомендуем к прочтению

    Добавить комментарий

    Ваш адрес email не будет опубликован.