Ubuntu 16.04+.Net Core+Docker+Uginx installation and deployment

foreword

  Recently, the company's project plans to be ported to the .Net Core platform, so I investigated the installation and deployment of .Net Core under Linux. This article will describe the whole process from installation to configuration to deployment step by step. In the structure and content of the article, the author has borrowed the content of many other blog posts, but I feel that other blog posts have only implemented a part or not written all the configuration content. What I do is to sort out my actual deployment process.

content

1. Preparations

2. Create a non-root user

3. Update the server

4. Install .Net Core

5. Create Demo

6. Daemon deployment

7. Nginx reverse proxy

8. Install Docker

9. Deploy .Net Core project in Docker

step

1. Preparations

  • A Linux server: The author uses the virtual machine simulation environment of VMWare, and friends with conditions can use the real server as the deployment environment
  • Linux terminal: I use MobaXterm

2. Create a non-root user

$ sudo adduser docker_user
$ sudo usermod -aG sudo docker_user
$ exit


3. Update the server

$ sudo apt-get update        
$ sudo apt-get upgrade       
$ sudo apt-get dist-upgrade  
$ sudo reboot

 

4. Install .Net Core

We want to run the .Net Core project, and naturally we have to install the .Net Core environment. Here Microsoft provides installation solutions for most Linux versions. I am using Ubuntu 16.04, so the following code is for this system version. If you are using other versions, you can refer to ( https://docs.microsoft.com/ en-us/dotnet/core/linux-prerequisites?tabs=netcore2x )

// register Microsoft product key as trusted 
$ curl https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor > microsoft.gpg $ 
sudo mv microsoft.gpg /etc/apt/trusted.gpg .d/ microsoft.gpg 

// Set the required version host package 
$ sudo  sh -c ' echo "deb [arch=amd64] https://packages.microsoft.com/repos/microsoft-ubuntu-xenial-prod xenial main" > /etc/apt /sources.list.d/dotnetdev.list ' 
// APT supports Https 
$ sudo apt-get install apt-transport- https
$ sudo apt-get update

// 安装.Net Core SDK
$ sudo apt-get install dotnet-sdk-2.0.3

// Check if the installation was successful 
$ dotnet --version

5. Create Demo

Because it is a Demo project, create a folder in the user root directory and use this folder as the root directory of the project.

5.1 Create a project

$ cd ~/
$ mkdir helloworld
$ cd helloworld
$ dotnet new mvc

5.2 Publish the project

$ dotnet restore
$ dotnet publish -c Release

5.3 Running the published program

Through the above screenshots, we found that the released program is similar to the one on the PC platform, and it is in the bin/Release directory. Let's move to this directory first, then run the demo with the "dotnet" command

$ cd bin/Release/netcoreapp2.0/publish/
$ dotnet helloworld.dll

After executing the command, the terminal will look like the image above. At this time, it means that the program has run. The penultimate line shows that the default port number of the program is 5000. At this time, we can access this website through the server IP + port number 5000. (Note: If it is external network access, you need to open port 5000 in the firewall. This will not be expanded in this article.)

The author is to test whether the program is normal by opening another terminal, and the results are as follows:

// request website via wget 
$ wget http: // localhost:5000

6. Daemon deployment

At this point, many students have discovered it. The current program requires us to always open the terminal to ensure that the website can be accessed, then what we need to do next is to deploy the website as a custom service. Let the website run in a background process.

6.1 Prepare the run directory

According to Linux deployment habits, we create a www folder in the var directory, and put the Demo just released in this directory

$ cd / var
$ sudo  mkdir www
$ cd www
$ sudo mkdir helloworld
$ cd helloworld
$ sudo cp -r ~/helloworld/bin/Release/netcoreapp2.0/publish/* .

6.2 Create a service configuration file

$ cd /etc/systemd/system/
$ sudo touch dotnet-helloworld.service

6.3 Writing service configuration files

$ sudo  vi dotnet-helloworld.service

First enter the file through vi (Note: vi is one of the most commonly used text editors under Linux, if you don't know vi, you can Baidu by yourself, and it will not be expanded here). After entering the editor, write the following code into the configuration file

[Unit]
Description=DotNet Core HelloWorld Running on Ubuntu

[Service]
WorkingDirectory =/var/www/helloworld                              // Working directory, here we write the website working directory just created 
ExecStart=/usr/bin/dotnet /var/www/helloworld/helloworld.dll      // The actual execution command of the service 
Restart = always
RestartSec=10
SyslogIdentifier=dotnet-example
User = docker_user                                                  // Started as docker_user 
Environment=ASPNETCORE_ENVIRONMENT= Production
Environment=DOTNET_PRINT_TELEMETRY_MESSAGE=false

[Install]
WantedBy=multi-user.target

The above configuration file I wrote with reference to Microsoft's official deployment documentation ( document link )

6.4 Start the service

$ sudo systemctl enable dotnet-helloworld.service
$ sudo systemctl start dotnet-helloworld.service

6.5 Checking Service Status

$ sudo systemctl status dotnet-helloworld.service

After the service is started, when you run the status command to view the service status, the service execution log will be returned, and the terminal will display code similar to the following figure.

This code is similar to what we used to start the dotnet project directly from the command line, which means that our service deployment was successful. We can use wget authentication again, and we can also visit this website.

7. Nginx reverse proxy

To do this, the deployment of the .Net Core project is almost there. Next, we will reverse proxy through Nginx.

7.1 Install Nginx

// install command 
$ sudo apt-get install nginx

// Check if the installation was successful after completing the installation 
$ nginx -v

7.2 Configure reverse proxy

 

// Move to Nginx configuration folder
$ cd /etc/nginx/conf.d/

// Create proxy configuration file 
$ sudo  touch helloworld.conf

// 编辑配置文件
$ sudo vi helloworld.conf

// 配置内容
server {
    listen 80;

    location / {
        proxy_pass http: //localhost:5000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade $http_upgrade;
        proxy_set_header Connection keep - alive;
        proxy_set_header Host $host;
        proxy_cache_bypass $http_upgrade;
    }
}

// 测试配置
$ sudo nginx -t

// 重新加载配置
$ sudo nginx -s reload

 

当完成这一步后,我们就可以在浏览器里直接输入服务器的IP地址来访问Demo网站了。

注:这里有一个小坑,Nginx有一个默认配置文件,文件路径在:/etc/nginx/sites-available下。文件名是default。如果访问的时候打开的不是上面这个网站,那需要到这个配置文件下,把所有的配置都注释掉,再重新reload一下Nginx。

 

8. 安装Docker

通过上面的教程,大家已经可以在自己电脑上访问Linux服务器上的.Net Core项目了。接下来我们将.Net Core项目放到Docker下运行,并同样通过Nginx方向代理,使我们能访问到.Net Core项目。

8.1 卸载旧版本Docker

因为Ubuntu系统可能自带Docker,所以在安装新版Docker前先将旧版的Docker清楚干净

$ sudo apt-get remove docker \
docker-engine \
docker.io

8.2 安装

$ sudo apt-get update

// 由于apt源使用 HTTPS 以确保软件下载过程中不被篡改。因此,我们首先需要添加使用HTTPS 传输的软件包以及 CA 证书。
$ sudo apt-get install \
apt-transport-https \
ca-certificates \
curl \
software-properties-common

// 鉴于国内网络问题,强烈建议使用国内源,官方源请在注释中查看。
// 为了确认所下载软件包的合法性,需要添加软件源的  GPG  密钥。
$ curl -fsSL https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu/gpg | sudo apt-key add -

// 官方源
// $ curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

// 向 source.list 中添加 Docker 软件源
sudo add-apt-repository \
"deb [arch=amd64] https://mirrors.ustc.edu.cn/docker-ce/linux/ubuntu \
$(lsb_release -cs) \
stable"

$ sudo apt-get update

// 执行安装命令
$ sudo apt-get install docker-ce

8.3 启动Docker服务

$ sudo systemctl enable docker
$ sudo systemctl start docker

8.4 建立Docker用户组

默认情况下,docker命令会使用 Unix socket 与 Docker 引擎通讯。而只有 root 用户和 docker 组的用户才可以访问 Docker 引擎的 Unix socket。出于安全考虑,一般 Linux 系统上不会直接使用 root 用户。因此,更好地做法是将需要使用 docker 的用户加入 docker 用户组。

 

// 建立docker用户组,这行命令执行的时候可能会报该用户组已存在。如果报这个错,可以直接跳过这条命令。
$ sudo groupadd docker

// 将当前用户加入docker用户组
$ sudo usermod -aG docker $USER

 

执行完这条命令后,退出终端重新登录一下。就可以使用docker命令来管理docker了。

8.5 镜像加速器配置

镜像(image)是docker的一个基础元素,但当我们在国内的网络环境中拉取Docker Hub(官方Docker镜像库)镜像时会变得比较困难,这时我们就可以配置镜像加速器。这里我使用的是Docker官方提供的国内加速器服务。

// docker文件夹默认是只允许root访问的。这里笔者偷个懒就直接开放docker的文件夹权限了。
sudo chmod 777 /etc/docker
cd /etc/docker

// 创建并编辑加速器源
sudo touch daemon.js
sudo vi daemon.js

// 文件内容
{
    "registry-mirrors": [
        "https://registry.docker-cn.com"
    ]
}

// 重启服务
$ sudo systemctl daemon-reload
$ sudo systemctl restart docker

 

9. 在Docker中部署.Net Core项目

9.1 拉取.Net Core镜像

$ sudo docker pull microsoft/dotnet

9.2 修改Demo程序

之前我们用的是默认的Demo程序运行,程序是运行在5000端口上的,在我们的实际环境中,不可能每个服务都用同一个端口号,所以这次我们将端口好做一个小变动。

// 移动到最开始我们创建的Demo中。编辑Program.cs
// $ cd ~/helloworld
// $ vi Program.cs

内容为

namespace helloworld
{
    public class Program
    {
        public static void Main(string[] args)
        {
            BuildWebHost(args).Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .UseUrls("http://*:10001")        // 使用10001作为程序运行时端口
                .Build();
    }
}

完成之后,我们重新发布

$ dotnet restore
$ dotnet publish -c Release

9.3 编写Dockerfile

// 移动到发布目录
$ cd ~/helloworld/bin/Release/netcoreapp2.0/publish/// 创建Dockerfile
$ sudo touch Dockerfile

// 编辑Dockerfile
$ sudo vi Dockerfile

以下是Dockerfile的内容

// 基于.Net Core镜像来构建我们的镜像
FROM microsoft/dotnet

// 将程序复制到镜像中的publish目录
COPY . /publish

// 定义工作目录为publish
WORKDIR /publish

// 设置Docker容器对外暴露的端口
EXPOSE 10001

// 执行dotnet命令
CMD ["dotnet", "helloworld.dll"]

9.4 构建Docker镜像

$ docker build -t helloworld:1.0 .

注意最后有一个"."

 

9.5 运行构建的镜像

$ docker run --name helloworld -d -p 10001:10001 helloworld:1.0

 

 

9.6 修改Nginx配置

在本文前半段,我们让Nginx代理了5000端口,现在我们把他改为10001。

// 编辑之前创建的Nginx配置
$ cd /etc/nginx/conf.d/
$ vi helloworld.conf

// 只需要修改代理的端口就行
server {
  listen 80;

  location / {
    proxy_pass http://localhost:10001;
    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection keep-alive;
    proxy_set_header Host $http_host;
    proxy_cache_bypass $http_upgrade;
  }
}

// Reload Nginx 
$ sudo nginx -t
$ sudo nginx -reload

All right. You're done, we can now use the server IP to directly access the Demo website in the browser.

Summarize

This learning process took about two days in total, and I watched many other tutorials over and over again. But most of the tutorials feel that either it is not clear, or there is a lack of a step, which makes it unable to run in the end, so after completing the configuration, I decided to write this article as an explanation for myself. Hope it can help you too.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324968200&siteId=291194637