Green-sell.info

Новые технологии
0 просмотров
Рейтинг статьи
1 звезда2 звезды3 звезды4 звезды5 звезд
Загрузка...

Asp net core linux

Asp 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

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.

How to host ASP.NET Core on Linux using Nginx?

In my previous article, i have shared my experience on hosting MongoDB server on AWS EC2 Instance. The EC2 instance is running on Ubuntu Server 16.04 LTS machine. To get some knowledge on how to make EC2 instance up and running, you can check this article.

Today, i will share my experience on how to host ASP.NET Core Web API application in my EC2 instance. So, let’s get started.

Step 1: Installing .NET Core in Linux

You will have to install dependencies needed to develop .NET Core applications on Linux. But, there are different dependencies for different Linux distributions/versions. You can check this article for what dependencies should you install for which Linux distributions/versions.

At first, let’s go to the AWS EC2 dashboard and grab the Public IPV4 address like below:

Let’s open PuTTY and connect to the EC2 instance using the copied IPV4 address and login to the EC2 instance.

Now, before installing the dependencies, you should first check which .net core version you are using in your application. You can check by running below command in the console of machine where you are building your application.

Our version is 2.1.200. Keep that in mind because you will install this version in the instance.

Step 1.1: Register Microsoft key and feed

Before installing .NET, you’ll need to register the Microsoft key, register the product repository, and install required dependencies. This only needs to be done once per machine.

Open a command prompt and run the following commands:

Step 1.2: Install .NET Core SDK

You need to update the products available for installation, then install the .NET SDK. In your command prompt, run the following commands:

You can see that we have installed the same .net core sdk version in our EC2 instance also. To check whether it has been installed properly or not, run below command in the Ubuntu console:

Step 2: Host ASP.NET Core on Linux with Nginx

Now, we have to copy our application over to the Linux. Before that, to copy our application code, we need to install WinSCP.

WinSCP is a popular SFTP client and FTP client for Microsoft Windows. It is used to copy file between a local computer and remote servers using FTP, FTPS, SCP, SFTP, WebDAV or S3 file transfer protocols.

Now, let’s connet our EC2 instance with WinSCP like below:

We need to paste our EC2 instance IPV4 address in the Host Name section. So, after connecting successfully, we can see below screen:

On the left is my local computer files and on the right is home directory of my remote computer means the files of the EC2 instance. Now, let’s create a directory in my remote computer called CoreRESTServer.

Now, let’s go to our application code and go to the directory where the application main solution .sln file resides. And, let’s open the command prompt here and run the below command to publish:

You will see some files are generated inside the awssite directory. Now, we will copy all the files of awssite directory of our local computer to the CoreRESTServer directory of remote computer like below:

Now, we have to configure a reverse proxy server in our remote machine.

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.

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 SSL termination from the HTTP server. A reverse proxy server may reside on a dedicated machine or may be deployed alongside an HTTP server.

Step 2.1: Install Nginx

We will use apt-get to install Nginx. The installer creates a systemd init script that runs Nginx as daemon on system startup. We will run the below command:

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

We can verify whether browser displays the default landing page for Nginx. The landing page is reachable at http:// /index.nginx-debian.html . As our server_IP_adress is 52.221.213.34, so we can see a landing page at http://52.221.213.34/index.nginx-debian.html .

Step 2.2: Configue Nginx

To configure Nginx as a reverse proxy to forward requests to our ASP.NET Core app, we need to modify /etc/nginx/sites-available/default. Let’s open it in a text editor, and replace the contents with the following:

You can see the server is listening to port 80. We need to enable this port in the security group. You can see this article on how to add rule in the security group. Since we have All traffic enabled, we don’t need to enable TCP at port 80 again. It is already enabled in the security group. But, we can also enable the TCP port 80 only rather than opening all the traffic.

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

Now, to directly run the app on the server:

  1. We have to navigate to the app’s directory means to CoreRESTServer directory.
  2. Then, we have to run the app’s executable: dotnet like

If a permissions error occurs, we have to change the permissions of the file:

If the app runs on the server but fails to respond over the Internet, we have to check the server’s firewall and confirm that port 80 is open.

Now, our server is setup to forward requests made to http://52.221.213.34:80 on to the ASP.NET Core app running on Kestrel at http://127.0.0.1:5000.

Step 2.3: Running our application as a service

But, if we close the PuTTY session, our application will stop. But, we don’t want that. We have to use systemd 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.

At first, we will create a service file for our web application.

Then, inside that my-web-api.service file, i have included below configurations:

Then, we need to enable the service and run it.

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

Now, if we close the PuTTY session, our web application is still running.

So, we have successfully host our .net core web application Linux using Nginx.

.NET Core

.NET Core — это универсальная платформа разработки, которая поддерживается корпорацией Майкрософт и сообществом .NET на сайте GitHub. Она является кроссплатформенной: поддерживает Windows, Mac OS и Linux. Имеет открытый исходный код: распространяется по лицензиям MIT и Apache 2.

Платформа .NET Core является кроссплатформенным аналогом .NET Framework на уровне библиотек базовых классов (BCL) .NET Framework. Она реализует спецификацию библиотеки .NET Standard.

Важным отличием от проекта Mono, который направлен на создание свободной среды, совместимой с .NET Framework, является то, что .NET Core не имеет реализации Windows Forms и не реализует API .NET Framework с использованием тех же имён сборок, то есть не позволяет запускать приложения, собранные для .NET Framework.

Для ALT p8 и Sisyphus собран .NET Core 2.0.0, соответствующий спецификации .NET Standard 2.0. Платформа развивается очень быстро, уже готовится версия 3.0, и использование версий 1.0/1.1 не рекомендуется.

В составе SDK поставляется компилятор C# с открытым исходным кодом из состава .NET Compiler Platform — Roslyn.

В качестве среды разработки удобно использовать Visual Studio Code (см. подробнее по ссылке), для которого имеется расширение, позволяющее отлаживать приложения, написанные на C# под .NET Core на Linux.

Содержание

Установка [ править ]

Для установки среды выполнения (CoreCLR) с необходимыми библиотеками установите мета-пакет dotnet:

Для разработки приложений установите SDK для .NET Core (пакет dotnet-sdk):

Создание приложения «Hello, world!» [ править ]

(Необходимо иметь в домашнем каталоге >2 ГБ свободного места)

Вывод команд [ править ]

Основные команды [ править ]

Всё взаимодействие с .NET Core из командной строки осуществляется через команду

Для запуска приложения:

Для запуска команды управления пакетами NuGet:

Для скачивания и подготовки всех необходимых для сборки проекта пакетов:

Для запуска тестов MSTest или xUnit:

Диагностика [ править ]

Desktop-приложения [ править ]

Сама по себе платформа .NET Core покрывает и поддерживает только модель консольных приложений и приложений ASP.NET Core. Реализация WPF (Windows Presentation Foundation) отсутствует для платформы Linux.

В настоящее время (июль 2017) шаги к портированию WPF на .NET Core заключаются в обсуждении стандарта XAML Standard, которым описываются UI-элементы, чтобы появилась возможность реализовать System.XAML. После чего возникнет теоретическая возможность портировать/реализовать WPF поверх .NET Core.

ASP.NET [ править ]

Частью ASP.NET Core является кросс-платформенный веб-сервер KestrelHttpServer.

Установить пакет dotnet-aspnetcore

Если требуется доступ отовсюду, то запускаем так

Однако, по рекомендации MS, если приложение смотрит в Интернет, нужно использовать обратный прокси-сервер (IIS, Nginx или Apache).

Зачем .net core для Linux создаёт exe file ?

Перешёл с 2.2 на 3 вылезло куча непонятных траболов. Потихоньку разгребаю.

Конфигурация сборки linux-x64

При компиляции получаю кроме dll ещё и файл exe. Кто знает зачем он для linux?

Развернуть ASP.NET Core 2.0 приложение на Linux хостинг
Собственно асп.нет стандартные приложения я выкладывал на бесплатном somee.com. Решил попробовать.

Несколько приложений ASP.NET Core на одном сервере Linux
Несколько приложений ASP.NET Core на одном сервере Linux.

Asp.net core на linux используя apache получаю Error 403
Доброго времени суток. Написал сайт на asp.net core (2.1) и пытаюсь развернуть его на linux.

Deploy ASP.NET CORE MVC приложения на APACHE сервере в облаке Linux ubuntu
Кто сталкивался с развёртыванием CORE на Apache? Какие надстройки нужно сделать ?

Что-то нет ясности, зачем там два файла.
Получаем два файла .dll и executable . Зачем два файла?
dll — это родной для Windows Portable Executabe файл (PE-файл).
executable — это линуксовый ELF ( Executable and Linkable Format ) .

sau, там по ссылке не нашел ответ

Если с ELF понятно, то что делает Windows DLL на линуксе ?

А-а, dll наверно это промежуточный продукт.
ELF это уже конечный продукт . ну наверно так .

Добавлено через 1 минуту

запускаю как ?
двойным кликом ?

в терминале ./app_name ?

Добавлено через 1 минуту

Во время выполнения команды dotnet build или dotnet publish создается исполняемый файл, который соответствует среде и платформе используемого пакета SDK. Предполагается, что с этими исполняемыми файлами можно выполнять те же действия, что и с другими исполняемыми файлами в машинном коде, например:
исполняемый файл можно дважды щелкнуть;
приложение можно запустить из командной строки напрямую, например myapp.exe в Windows и ./myapp в Linux и macOS.

+ фича «Однофайловые исполняемые файлы»

dll запускаю под линуксом как оно всегда и запускалось

По поводу exe — меня смущает размер. он в 2 раза меньше чем у dll — примерно 300k — dll 150k — exe

По linux не пробовал запускать exe. Может и заработает. Надо будет переписывать серверные конфиги старта службы.

P.S. в 2.2 для линукса exe не генерировалась.

P.S.S. может они в exe dotnet запихнули?

Добавлено через 4 минуты

По поводу dll — я определил что это для линукс потому как он там заработал.

В своё время экспериментировал — делал dll для win и для nix

Так вот не на своей платформе не запускалось — вылетало с ошибками.

Запуск разумеется был таким dotnet xxx.dll

эти dll ни для windows ни для linux , они для платформы net , содержат промежуточный IL код исполняемый CLR
но который соответствует среде и платформе используемого пакета SDK

Добавлено через 3 минуты

Заказываю контрольные, курсовые, дипломные и любые другие студенческие работы здесь.

Можно ли использовать библиотеки написанные на .net Core для .net FW
Можно ли подключить библиотеку написанную на .net Core к WinForm приложению написанному на .net FW.

Подойдет ли .NET Core 1.0 (RC2) для разработки cоциальной сети на ASP.NET?
Добрый день. У меня есть идея одна по написаю одной социальной сети. Как вы думаете подойдет.

Сборка .NET Core проекта в VS2017 в exe
Здравствуйте, подскажите, при сборке проекта типа .NET Core создаётся не исполняемое приложение.

Библиотека NETSquirrel для .NET и .NET Core — формат вывода индексаторов
Предположим, что мы выводим через AutoPrintLine все поля, свойства и индексаторы экземпляра.

Читать еще:  Сервер приложений на linux
Ссылка на основную публикацию
Adblock
detector