编程知识 cdmana.com

Netsore is based on docker basic image and mounted file deployment

The ninth true face of Lushan: Micro service architecture NetCore be based on Docker Base image and mount file deployment

One 、 brief introduction
        We were in the last article 《 The eighth true face of Lushan: Micro Service Architecture NetCore be based on Dockerfile File deployment 》 This paper introduces the in , How to be in Linux On the system Docker Deploy... In the container Net Core The first approach to the project . Of course , I forgot to say something , Today we make up for . If you want to practice our example , You have to deal with Linux The system knows something about , Yes Linux You should also have experience in the use of basic operating commands , Because I stepped on a lot of holes , Sad . On this basis , Be right, too Docker Familiar with ,Docker You should also be familiar with the operation commands of , otherwise , It's really difficult . Today as an introduction Net Core Project deployment to Linux In the system Docker The second way in the container , Continue with our series . These three ways should be explained in such detail , Because , In my future articles , If there are any more topics related to project deployment and migration , It would not be so detailed . I hope you will understand , Because we should highlight the theme of each article , And each article solves one problem , otherwise , It's not good to win over the host . People who read my article will know , There will be repetitions in my article , It's also to take care of the readers , Each article is independent , Let us see clearly and clearly , Avoid switching between multiple articles , It's not for word counting .

    1、 explain
           Today's article is very simple , It is to introduce Net Core Project deployment to Linux Environmental Docker The second way is in the container . Yes, of course , For a master , These are trivial , But it may be helpful for beginners or beginners , So , Experts don't have to be sarcastic , If you want to make a statement of your own , It's not welcome to teach . In particular , All the code here has been tested , So you can use , But the reality may be different , The result may not be the same .

    2、 development environment
          
Here's the development environment , Needless to say , All very simple. , It's easy to see .
         (1)、 development tool :Visual Studio 2019
         (2)、 development language :C#
         (3)、 Development platform :Net Core3.1, Cross platform .
         (4)、 operating system :Linux(CentOS 7).
         (5)、 Virtual container :Docker 19.03.13
         (6)、 Upload files :SSH Secure File Transfer Client perhaps XFTP
         (7)、 customer Household End :SSH Secure Shell Client perhaps XShell
         (8)、 Virtual system :VMware Workstation Pro 14.1.3

Two 、Docker Introduction of container technology
   
      

    1
、Docker brief introduction
            Docker Is an open source application container engine , Allows developers to package their applications and dependencies into a portable container , Then post to any popular Linux Machine or Windows On the machine , You can also implement virtualization , Containers are completely sandboxed using the sandbox mechanism , There will be no interface between them .
            Docker yes Docker.Lnc One of the company's open sources is based on LXC Built on technology Container Container engine , Source code hosted in Github On , be based on Go Language and compliance Apache2.0 Open source agreement .
            Docker Belong to Linux An encapsulation of a container , Provide easy to use container interface .
            Docker Dependence of an application on that program , Package it in a file . Run this file , A virtual container will be generated . The program runs in this virtual container , It's like running on a real physical machine . With Docker, You don't have to worry about the environment .
             On the whole ,Docker The interface is fairly simple , You can easily create and use containers , Put your application in a container . Containers can also be version managed 、 Copy 、 Share 、 modify , It's like managing common code .
      
              A complete Docker It consists of the following parts :
                Docker Client client : You can input various commands to operate Docker Mirror image 、 Containers .
                Docker Daemon Daemon :Docker Server side of , Complete the client's requests and commands .
                Docker Image Mirror image : The image is the template of the container instance , Generate container instances based on this template .
                Docker Container Containers : The container instance generated from the image file , There is no mirror image , Unable to generate container .

              Docker Structural components :
               

    2、 Basic commands
          (1)、 Installation kit
                   command :yum install -y yum-utils
             
          (2)、 Set up image warehouse
                   command : Alibaba cloud :$ yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
                    Tsinghua University source :$yum-config-manager --add-repo  https://mirrors.tuna.tsinghua.edu.cn/docker-ce/linux/centos/docker-ce.repo
         
          (3)、 Installing the docker
                   command :

          (4)、 Stop a running container
                   command :docker stop Container name / Containers ID

          (5)、 Start stopped container :
                   command :docker start Container name / Containers ID

          (6)、 Query created container :
                  command :docker-compose ps
             
          (7)、 Deletes the specified container :
                  command :docker rm Container name / Containers ID

          (8)、 Delete all containers :
                  command :docker rm $(docker ps -aq)

          (9)、 Query all images :
                   command :docker ps –a

          (10)、 delete mirror :
                    command :docker rmi Image name / Mirror image ID

          (11)、 Delete all images :
                    command :docker rmi $(docker images -q)

          (12)、docker-compose Command details refer to :
                    command :docker-compose –h

          (13)、 Stop and delete all running container instances :
                    command :docker stop $(docker ps -q) & docker rm $(docker ps -aq)

          (14)、 Check the log :
                    command :docker logs Containers id/ Container name

          (15)、 Check statistics :
                    command :docker stats Containers id/ Container name

          (16)、docker By alias Form to run the specified image
                    command :docker run -itd -p host:container --name Alias Mirror image id/ Image name

            (17)、 Limit the memory used by the mirror -m:
                    command :docker run -itd -p hostPort:containerPort --name Alias -m 200m Mirror image id/ Image name
          
          (18)、 Limiting the use of images cpu number --cpus.:
                    command :docker run -itd -p hostPort:containerPort --name Alias --cpus 1 Mirror image id/ Image name

          (19)、 Enter the specified container
                    command :$Docker exec -it Containers ID| Container name /bin/bash

                  

3、 ... and 、Docker The difference between container and virtual machine
   
       I'm just going to give you a brief introduction Docker The difference between container and virtual machine , To give you a perceptual understanding , If you want to know more about it , Go to study online by yourself , It's a lot of content , Much better than what I wrote . Technology comes from life , And higher than life , therefore , The technology we learned , It can be compared with some things in life . Take virtual technology for example , Its history , Similar to the development of our living conditions .

    1、 The history of virtual technology

          (1)、 Single physical machine 【 Single family villas 】
                   
                    Rich people live in their own villas , Have your own lawn , Independent garden , A beautiful swimming pool , Of course , There are also a lot of rooms that don't have time at all , For individuals , It's comfortable, of course , It's also the life we all aspire to . however , For land resources , Utilization rate is not high . For the network environment , The same is true . At the beginning , People's systems are deployed in their own independent physical machines , Such a physical machine has a complete operating system , Security system , The network environment , There are a lot of features that you can't use , Everything has its own independent set , There is no concept of reuse at all . Each system corresponds to such a complete set of things , Including hardware 、 Resources like software and networks , The big system is like this , The same is true for small systems , It's not going to work like this .

          (2)、 The age of virtual machines 【 High rise community 】
                   
                    The second stage of the development of virtual technology is the era of virtual machine , In this era , Just like the community we live in , People live in high-end communities by buying houses in cities , This is a lot better than the first stage , You can share a lot of , such as : Access control 、 Security staff 、 The foundation 、 Property and other public services . however , Each family is still a separate unit , It has its own bathroom , Separate bedroom , The kitchen 、 Restaurants and the Internet . The network environment of this era 、 Server technology has been developing rapidly , People began to pay attention to the utilization of resources . Virtual machine technology has also been very good development and use , We can deploy multiple virtual machines on a large machine , This big machine , It's like the neighborhood we live in , thus , Improved resource utilization , You can share hardware 、 Networks and other infrastructure , But there is also a complete operating system inside each virtual machine , Service components, etc , At this time, virtual machines are used , It's not much different from using a physical machine .

          (3)、Docker Containers 【 Capsule apartment 】
                  
                   The third stage is the development of virtual technology , It can also be called “ Capsule apartment ” Pattern . Capsule apartment is a way of living in a big city , such as : Tokyo, Japan , Hong Kong in China is quite common . In an apartment like this , Only one person is allowed to rest 、 The most basic place and function of sleep , None of the other extra features , Except for the bed 、 Quilts and lights are something you can control , Everything else is public .Docker Container technology is the product of this era , In order to improve the utilization of resources , Start slimming the virtual machine , And then came the container technology , The container no longer contains a complete operating system , It's a The minimalist Version of the operating system , The system environment necessary to run the software , In addition to the streamlined system , It's what the program depends on must Environmental Science , What's more, the program to be deployed .

    2、 Difference between the two , Look at the picture and understand !
        
           
              Virtual machine is the high-rise building of our community , Container is “ Capsule apartment ”
                  

    3、 What can containers bring us ?
       
        

Four 、Net Core Project based on Docker How containers are deployed

        today , We'll start with the introduction of Net Core Project deployment to Linux On the system Docker The second method in the container . Before the start , Explain , Because we are going to deploy the system to Docker In the container , therefore , Before we start , It has to be installed Docker Containers , The version I currently have installed is :19.03.13, If you log in Linux System (CentOS7), You can type in the command :Docker --version Check that... Is installed Docker, If not installed , Tips : There is no such order (command not found), If installed , The specific version number will be displayed :Docker version 19.03.13,build 4484c46d9d. And a little more ,Docker Try to be up to date , At least 18 Or above , Otherwise, there will be some problems , I just had a problem , It was resolved after upgrading , If you want to upgrade your own Docker, You can see 《 How to integrate Docker Upgrade to the latest version 》.
 
     Today we start creating project images and mounting files , Before the start , Let's first create a test project .

    1、 Build a test project .

             (1)、PatrickLiu.MicroService.Interfaces(NetCore The class library project ), Define the abstract interface layer , The code is simple , Because it's not the point , The focus is on the framework .
              
                         

            
                   
                       Sample code :
                  

 1 using PatrickLiu.MicroService.Models;
 2 using System.Collections.Generic;
 3 
 4 namespace PatrickLiu.MicroService.Interfaces
 5 {
 6     /// <summary>
 7     ///  User service interface definition .
 8     /// </summary>
 9     public interface IUserService
10     {
11         /// <summary>
12         ///  Find the user instance object of the specified primary key .
13         /// </summary>
14         /// <param name="id"> User's primary key .</param>
15         /// <returns> Return the found user instance object .</returns>
16         User FindUser(int id);
17 
18         /// <summary>
19         ///  Get the instance collection of all users .
20         /// </summary>
21         /// <returns> Return all user instances .</returns>
22         IEnumerable<User> UserAll();
23     }
24 }


             (2)、PatrickLiu.MicroService.Models(NetCore The class library project ), Define the entity model used to transfer data , The code is simple , Because it's not the point , The focus is on the framework .
              
            

            

                        Sample code :
                  

 1 using System;
 2 
 3 namespace PatrickLiu.MicroService.Models
 4 {
 5     /// <summary>
 6     ///  The user model .
 7     /// </summary>
 8     public class User
 9     {
10         /// <summary>
11         ///  Get or set the user primary key .
12         /// </summary>
13         public int ID { get; set; }
14 
15         /// <summary>
16         ///  Get or set the user name .
17         /// </summary>
18         public string Name { get; set; }
19 
20         /// <summary>
21         ///  Get or set the user account name .
22         /// </summary>
23         public string Account { get; set; }
24 
25         /// <summary>
26         ///  Get or set the user password .
27         /// </summary>
28         public string Password { get; set; }
29 
30         /// <summary>
31         ///  Get or set the user's email address .
32         /// </summary>
33         public string Email { get; set; }
34 
35         /// <summary>
36         ///  Get or set the user role .
37         /// </summary>
38         public string Role { get; set; }
39 
40         /// <summary>
41         ///  Get or set the login time of the user .
42         /// </summary>
43         public DateTime LoginTime { get; set; }
44     }
45 }


             (3)、PatrickLiu.MicroService.Services(NetCore The class library project ), Define the service layer that implements the interface , The code is simple , Because it's not the point , The focus is on the framework .
             
            

                       

                       Sample code :
                  

 1 using PatrickLiu.MicroService.Interfaces;
 2 using PatrickLiu.MicroService.Models;
 3 using System;
 4 using System.Collections.Generic;
 5 using System.Linq;
 6 
 7 namespace PatrickLiu.MicroService.Services
 8 {
 9 /// <summary>
10 ///  The implementation type that implements the user service interface .
11 /// </summary>
12 public class UserService : IUserService
13  {
14 private IList<User> dataList;
15 
16 /// <summary>
17 ///  Initializing an instance of a type 
18 /// </summary>
19 public UserService()
20  {
21 dataList = new List<User>()
22 { new User {ID=1,Name=" huang feihong ",Account="HuangFeiHong",Password="HuangFeiHong123456",Email="huangFeiHong@sina.com", Role="Admin", LoginTime=DateTime.Now },
23 new User {ID=2,Name=" Hongxiguan ",Account="HongXiGuan",Password="HongXiGuan54667",Email="HongXiGuan@sina.com", Role="Admin", LoginTime=DateTime.Now.AddDays(-5) },
24 new User {ID=3,Name=" Fang Shiyu ",Account="FangShiYu",Password="FangShiYu112233",Email="fangShiYu@163.com", Role="Admin", LoginTime=DateTime.Now.AddDays(-30) },
25 new User {ID=4,Name=" Miao Cuihua ",Account="MiaoCuiHua",Password="MiaoCuiHua887766",Email="miaoCuiHua@sohu.com", Role="Admin", LoginTime=DateTime.Now.AddDays(-90) },
26 new User {ID=5,Name=" Yan Yongchun ",Account="YanYongChun",Password="YanYongChun09392",Email="yanYongChun@263.com", Role="Admin", LoginTime=DateTime.Now.AddMinutes(-50) }};
27  }
28 
29 /// <summary>
30 ///  Find the user instance object of the specified primary key .
31 /// </summary>
32 /// <param name="id"> User's primary key .</param>
33 /// <returns> Return the found user instance object .</returns>
34 public User FindUser(int id)
35  {
36 return dataList.FirstOrDefault(user => user.ID == id);
37  }
38 
39 /// <summary>
40 ///  Get the instance collection of all users .
41 /// </summary>
42 /// <returns> Return all user instances .</returns>
43 public IEnumerable<User> UserAll()
44  {
45 return dataList;
46  }
47  }
48 }


             (4)、PatrickLiu.MicroService.ServiceInstance(Asp.Net Core WebAPI project ), Providing business functions to the outside world WebApi project , The project must introduce other associated projects :

                         PatrickLiu.MicroService.Interfaces
                         PatrickLiu.MicroService.Models
                         PatrickLiu.MicroService.Services

                         
    
                          Sample code :
                         

  1 using System;
  2 using System.Collections.Generic;
  3 using System.Linq;
  4 using System.Threading;
  5 using Microsoft.AspNetCore.Authorization;
  6 using Microsoft.AspNetCore.Mvc;
  7 using Microsoft.Extensions.Configuration;
  8 using Microsoft.Extensions.Logging;
  9 using PatrickLiu.MicroService.Interfaces;
 10 using PatrickLiu.MicroService.Models;
 11 
 12 namespace PatrickLiu.MicroService.ServiceInstance.Controllers
 13 {
 14     /// <summary>
 15     ///  User  API  type .
 16     /// </summary>
 17     [Route("api/[controller]")]
 18     [ApiController]    
 19     public class UsersController : ControllerBase
 20     {
 21         #region  Private field 
 22 
 23         private readonly ILogger<UsersController> _logger;
 24         private readonly IUserService _userService;
 25         private IConfiguration _configuration;
 26 
 27         #endregion
 28 
 29         #region  Constructors 
 30 
 31         /// <summary>
 32         ///  Initializes a new instance of the type .
 33         /// </summary>
 34         /// <param name="logger"> Loggers .</param>
 35         /// <param name="userService"> User service interface .</param>
 36         /// <param name="configuration"> Configure the service .</param>
 37         public UsersController(ILogger<UsersController> logger, IUserService userService, IConfiguration configuration)
 38         {
 39             _logger = logger;
 40             _userService = userService;
 41             _configuration = configuration;
 42         }
 43 
 44         #endregion
 45 
 46         #region  Example method 
 47 
 48         /// <summary>
 49         ///  Get a record 
 50         /// </summary>
 51         /// <param name="id"></param>
 52         /// <returns></returns>
 53         [HttpGet]
 54         [Route("Get")]
 55         public User Get(int id)
 56         {
 57             return _userService.FindUser(id);
 58         }
 59 
 60         /// <summary>
 61         ///  Get all the records .
 62         /// </summary>
 63         /// <returns></returns>
 64         [HttpGet]
 65         [Route("All")]
 66         //[Authorize]
 67         public IEnumerable<User> Get()
 68         {
 69             Console.WriteLine($"This is UsersController {this._configuration["port"]} Invoke");
 70 
 71             return this._userService.UserAll().Select((user => new User
 72             {
 73                 ID = user.ID,
 74                 Name = user.Name,
 75                 Account = user.Account,
 76                 Password = user.Password,
 77                 Email = user.Email,
 78                 Role = $"{this._configuration["ip"]}:{this._configuration["port"]}",
 79                 LoginTime = user.LoginTime
 80             })); ;
 81         }
 82 
 83         /// <summary>
 84         ///  timeout handler 
 85         /// </summary>
 86         /// <returns></returns>
 87         [HttpGet]
 88         [Route("Timeout")]
 89         public IEnumerable<User> Timeout()
 90         {
 91             Console.WriteLine($"This is Timeout Start");
 92             // timeout .
 93             Thread.Sleep(3000);
 94 
 95             Console.WriteLine($"This is Timeout End");
 96 
 97             return this._userService.UserAll().Select((user => new User
 98             {
 99                 ID = user.ID,
100                 Name = user.Name,
101                 Account = user.Account,
102                 Password = user.Password,
103                 Email = user.Email,
104                 Role = $"{this._configuration["ip"]}:{this._configuration["port"]}",
105                 LoginTime = user.LoginTime
106             })); ;
107         }
108 
109         #endregion
110     }
111 }
1         /// <summary>
2         ///  Configure an instance of the injection container .
3         /// </summary>
4         /// <param name="services"></param>
5         public void ConfigureServices(IServiceCollection services)
6         {
7             services.AddSingleton<IUserService, UserService>();
8         }    

      Program.cs 

1         public static void Main(string[] args)
2         {
3             new ConfigurationBuilder()
4                 .SetBasePath(Directory.GetCurrentDirectory())
5                 .AddCommandLine(args)// Support command line 
6                 .Build();
7 
8             CreateHostBuilder(args).Build().Run();
9         }        


     
    2、 Publish the project .
              We're trying to get Net Core Project deployment to Linux(CentOS7) Environmental Docker In the container , First we're going to release our project :PatrickLiu.MicroService.ServiceInstance, therefore , We're going to right-click on the item and choose the menu 【 Release 】.

               (1)、 Start publishing projects .
                       

               (2)、 Project published successfully

                      

               (3)、 Post release project documents .

                           

    3、 Generate Docker Image file .
             (1)、 Copy files
                       Project documents must be released successfully , Then the successful copy of the program file will be released Linux Server .
            
                       Server path :/root/testProject/second
            
             
                      Linux(CentOS7) The file directory structure on the server .

                      

             (2)、 see Linux File structure on the server .
                       command :ls –a
             
            

    4、 Generate container instance .
             We can directly generate container instances .
              command :docker run -d -p 8083:80 -v /root/testProject/second:/app  --workdir /app mcr.microsoft.com/dotnet/core/aspnet dotnet  /app/PatrickLiu.MicroService.ServiceInstance.dll

               

    5、 Test the container to see if it is working properly .
             command :Docker ps –a

              

    6、 Test with browser access .
             The container starts normally , Then we can visit it through the browser , Let's get our address first .
              command :ifconfig

               

              With the address , We visit :http://192.168.127.141:8083/api/users/all

               

5、 ... and 、 Conclusion
  
      Okay , That's it for today . This series is still very hard to organize , Because every link has to be tested , Make sure that the code you write can run in the test environment , But tired and happy . As the saying goes , Short step , A thousand miles , Make a little progress every day , come on. .

版权声明
本文为[Cocoa is OK]所创,转载请带上原文链接,感谢
https://cdmana.com/2020/12/20201224094610852z.html

Scroll to Top