Tips: This article is a bit long, and it is expected to take 8mins to finish. If you want to follow the practice step by step, it is expected to take 30mins, please make a cup of coffee, find a quiet corner, open the computer practice, the effect will be better.

# 1. Introduction We know. One of the biggest features of NET Core is that it can be cross-platform, and cross-platform seems to have the impression that it can be deployed and run on non-Windows systems. How to do it, however, may be lacking. In this section, we will use a simple example to teach you how to use Docker to container.NET Core applications for cross-platform building and deployment.

# 2. Environment ready since play. .net has always been working with Windows. If we were to start this section based on Windows, wouldn’t it be beside the point? ! Let’s switch to Linux. If there is no Linux foundation and Docker foundation, please consciously complete the following two experiments: Tencent Cloud developer lab: Linux foundation introduction Tencent cloud developer lab: build Docker environment

With these two experiments done, we are one step closer to the world of Linux. Because the follow-up is based on the Linux-centos system for the actual operation drill, there is no Linux operating environment, you can consider from Tencent Cloud Lab list to find a CentOS related experimental project as the drill environment of this article.

Before starting, it is necessary to have a brief understanding of Docker, which can be referred to my last article Hello Docker. Here is a brief repeat. Docker is written in the Go language and developed based on some features of the Linux operating system. It provides an operating system-level abstraction and is a container-managed technology that isolates application dependencies on infrastructure (operating systems, etc.). Compared with virtual machines, Docker shares the hardware resources of the host computer and uses containers to provide an independent running environment to run applications. Virtual machines are isolated virtual machines based on Supervisor (Virtual Machine management program) using virtualization technology, which provides the running environment on the OPERATING system of virtual machines! While both provide good resource isolation, it’s clear that Docker has lower virtualization overhead! Docker involves three core concepts: Register, Image, and Container.

1. Registry: Used to store Docker images, such as Docker official Docker Hub is a public warehouse, on which we can download the images we need. 2. Image: indicates an Image. A developer creates an application or service and packages it and its dependencies into a container image. Mirroring is a static form of an application’s configuration and its dependencies. 3. Container: A Container is a running instance of an image. It is an isolated, resource-controlled, portable runtime environment that contains the operating system, programs that need to be run, dependencies of running programs, and environment variables.

When we execute Docker pull or Docker run, if we do not have the required image locally, we will download (pull) an image from the repository (usually DockerHub). Docker executes the run method to get a container in which the user performs various operations. Docker executes the commit method to convert a container to an image. Docker uses login, push and other commands to push local images to the repository. This image can then be used on other machines or servers to generate containers to run applications.

4. Install the Docker

4.1. Use scripts to automatically install Docker

In the test or development environment, Docker official provides a set of convenient installation scripts to simplify the installation process. CentOS system can use this script installation:

-o get-docker.sh $sudo sh get-docker.sh --mirror AliyunCopy the code

4.2. Start the Docker

After executing this command, the script will automatically do all the preparatory work and install the Edge version of Docker CE on the system.

Start Docker CE $sudo systemctlenable$sudo docker -v docker version 1.12.6, build ec8512b/1.12.6Copy the code

4.3 Testing whether Docker is correctly installed

Docker run hello-world:

$ docker run hello-world
Unable to find image 'hello-world:latest' locally
latest: Pulling from library/hello-world
ca4f61b1923c: Pull complete
Digest: sha256:be0cd392e45be79ffeffa6b05338b98ebb16c87b255f48e297ec7f98e123905c
Status: Downloaded newer image for hello-world:latest
Hello from Docker!
This message shows that your installation appears to be working correctly.
To generate this message, Docker took the following steps:
1. The Docker client contacted the Docker daemon.
2. The Docker daemon pulled the "hello-world" image from the Docker Hub.
(amd64)
3. The Docker daemon created a new container from that image whichruns the executable that produces the output you are currently reading. 4. The Docker daemon streamed that output to the  Docker client,which sent it
to your terminal.
To try something more ambitious, you can run an Ubuntu container with:
$ docker run -it ubuntu bash
Share images, automate workflows, and more with a free Docker ID:
https://cloud.docker.com/
For more examples and ideas, visit:
https://docs.docker.com/engine/userguide/
Copy the code

When a Docker run hello-world is executed, docker will first look for the local hello-world image. If there is no local image, docker will pull the image from the default repository docker Hub. After the image is pulled locally, it instantiates the image to get the container, and prints Hello from Docker! .

4.4. Configure Mirror acceleration

Since the default image repository is out of the country, pulling a small image time is tolerable, but pulling an image on G is a bit too painful, so we use the DaoCloud image accelerator to speed up the image. The configuration method on Linux is as follows:

$ curl -sSL https://get.daocloud.io/daotools/set_mirror.sh | sh -s http://37bb3af1.m.daocloud.io`
$ sudo systemctl restart docker
Copy the code

5. Hello Docker With .NET Core

Once Docker is installed, let’s combine it. Play NET Core.

5.1. Pull Microsoft/Dotnet images

Run the Docker pull Microsoft /dotnet command, wait a few minutes to complete the installation, run the Docker images, you can see that the local contains Microsoft /dotnet, docker. IO /hello-world two images.

5.2. Running a Microsoft/Dotnet Image

Docker run is used to start the image, which is started in interactive mode (into the container) by specifying the parameter -it. Run the following commands in sequence:

// Start a dotnet image $docker run it Microsoft /dotnet // create a project named helloDocker.web. NET Core MVC project dotnet new MVC -n helloDocker. Web // Go to helloDocker. Web foldercdHellodocker.web // start. NET Core MVC project Dotnet RunCopy the code

The running result is as follows:

[root@iZ288a3qazlZ ~]# docker run -it microsoft/dotnet
root@816b4e94de67:/# dotnet new mvc -n HelloDocker.Web
The template "ASP.NET Core Web App (Model-View-Controller)" was created successfully.
This template contains technologies from parties other than Microsoft, see https://aka.ms/template-3pn for details.

Processing post-creation actions...
Running 'dotnet restore' on HelloDocker.Web/HelloDocker.Web.csproj...
  Restoring packages for /HelloDocker.Web/HelloDocker.Web.csproj...
  Generating MSBuild file /HelloDocker.Web/obj/HelloDocker.Web.csproj.nuget.g.props.
  Generating MSBuild file /HelloDocker.Web/obj/HelloDocker.Web.csproj.nuget.g.targets.
  Restore completed in1.83 SECfor /HelloDocker.Web/HelloDocker.Web.csproj.
  Restoring packages for /HelloDocker.Web/HelloDocker.Web.csproj...
  Restore completed in 376.14 ms for /HelloDocker.Web/HelloDocker.Web.csproj.

Restore succeeded.

root@816b4e94de67:/# cd HelloDocker.Web
root@816b4e94de67:/HelloDocker.Web# dotnet run
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
      No XML encryptor configured. Key {727df196-978f-4df8-b3d3-e92a77e410ee} may be persisted to storage in unencrypted form.
Hosting environment: Production
Content root path: /HelloDocker.Web
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
Copy the code

To close the application, press Ctrl+C and type Exit to exit the current container.

Is not a simple steps to complete one. NET Core MVC project creation and running? ! You may be wondering at this point that the Linux host is not installed. NET Core SDK, how is the MVC project created? This is the magic of Docker. The Dotnet image we pulled from the image repository is created, built, and run. All the dependencies and runtime environments required by the NET Core project.

After exiting the container, we execute find-name helloDocker. Web (find the helloDocker. Web file) and find none. That tells us what we just created. NET Core MVC projects are created inside the container and are completely isolated from the host. At this point you might be thinking, it’s inconvenient to have to install the source code in the container every time. Could we have the container run our host’s source code project? Well, that’s a good question. So let’s answer that question.

5.3. Mount the source code

To create on the host. NET Core project, at this point we need to install on the Linux host. NET Core SDK.

5.3.1. Host installation. NET Core SDK

The steps are as follows:

sudo rpm --import https://packages.microsoft.com/keys/microsoft.asc
sudo sh -c 'echo -e "[packages-microsoft-com-prod]\nname=packages-microsoft-com-prod \nbaseurl= https://packages.microsoft.com/yumrepos/microsoft-rhel7.3-prod\nenabled=1\ngpgcheck=1\ngpgkey=https://packages.microsoft .com/keys/microsoft.asc" > /etc/yum.repos.d/dotnetdev.repo'Sudo yum update sudo yum install libunwind libicu sudo yum install dotnet-SDK-2.1.3Copy the code

Once installed, we create one by executing the following commands. NET Core MVC Project:

// return to the root directory $cd $HOME// Create demo folder $mkdir demo $cdDemo // create a project named helloDocker.web. NET Core MVC project dotnet new MVC -n helloDocker. Web // Go to helloDocker. Web foldercdHellodocker.web // start. NET Core MVC project Dotnet RunCopy the code

If you know the native IP address (which can be queried using the ifconfig command), you can access the MVC project we just ran directly from your browser by visiting http://< IP address>:5000.

This step we are in the $HOME/demo/HelloDocker Web directory successfully created the MVC project, we will be the next source project in the directory Shared by mounting the way into the container.

5.3.2. Mount the host project to the container

When starting the Docker image, Docker allows us to mount the host’s files to the specified directory of the container by using the -v parameter. In other words, the host machine shares specified files for the container to access. Without further ado, real knowledge comes from practice.

// The '\' and 'Enter' key in the command form a newline, allowing us to type a long command line. $ docker run -it \ -v$HOME/demo/HelloDocker.Web:/app \
microsoft/dotnet:latest
Copy the code

The above command is to $HOME/demo/HelloDocker Web folder files \ app directory mounted to the container.

[root@iZ288a3qazlZ HelloDocker.Web]# docker run -it \
> -v $HOME/demo/HelloDocker.Web:/app \
> microsoft/dotnet:latest
root@d70b327f4b7e:/# ls
app  bin  boot  dev  etc  home  lib  lib64  media  mnt  opt  proc  root  run  sbin  srv  sys  tmp  usr  var
root@d70b327f4b7e:/# cd app
root@d70b327f4b7e:/app# ls
Controllers  HelloDocker.Web.csproj  Models  Program.cs  Startup.cs  Views  appsettings.Development.json  appsettings.json  bundleconfig.json  obj  wwwroot
root@d70b327f4b7e:/app# dotnet run
warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
      No XML encryptor configured. Key {09a69edf-c1c5-4909-ad24-15a43a572fca} may be persisted to storage in unencrypted form.
Hosting environment: Production
Content root path: /app
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
Copy the code

From the above results, the app directory inside the container contains the source code project for the host. Having a shared copy of the host directory, rather than the container, means that changes to the directory on the host are immediately reflected in the container. Changes to the shared directory in the container, on the other hand, are not reflected on the host, breaking the isolation nature of the container.

With such a simple scenario, can you be smart enough to think of its application to our everyday coding? Yes, we can use continuous build (CI). Git Clone the source code to the host, then mount the source directory to the container to build.

5.4. With the help of Dockerfile

Dockerfile is used to define the set of operations that you will perform in the container. Let’s create our first Dockerfile:

// Make sure to go into the MVC project directory we created $cd $HOME// Use the touch command to create Dockerfile $touch Dockerfile // Use the vi command to edit Dockerfile vi DockerfileCopy the code

After entering the VI editing screen, copy the following code and run the shift + Ins command to paste the code. Press ESE to exit the editing mode, shift + :, and enter wq to save the configuration and exit the editing interface.

FROM microsoft/dotnet:latest
WORKDIR /app
COPY . /app
RUN dotnet restore
EXPOSE 5000
ENV ASPNETCORE_URLS http://*:5000
ENTRYPOINT ["dotnet"."run"]
Copy the code

Let me explain the above commands in turn:

  1. useFROMSpecifies the image used by the container
  2. useWORKDIRSpecify working directory
  3. useCOPYCommand to copy the current directory (where.To the /app directory in the container
  4. useRUNCommand Specifies the command to execute in the container
  5. useEXPOSESpecifies the port number to expose for the container
  6. useENVSpecifies the environment parameters used above to tell. The NETCore project listens on port 5000 on all network interfaces
  7. useENTRYPOINTDefine entry points for containers

With the Dockerfile in place, we can package our current project as an image for distribution. Docker build -t

$ docker build -t hellodocker.web .
Copy the code

This command tells Docker to package the current directory as an image and name it helloDocker.web. After executing the command, enter Docker images to see our newly packaged image. Once the image is created, we can run it directly:

docker run -d -p 80:5000 hellodocker.web
Copy the code

The command above is to run our newly packaged image and map the container from 5000 to port 80 of the host with the -p parameter, where the -d parameter tells Docker to run the image as a backend task. Since 80 is the default Web port, we can access the MVC web site running in our container by accessing the IP directly from the browser. Or check out curl -i http://localhost. The following is an example:

[root@iZ288a3qazlZ HelloDocker.Web]# docker build -t hellodocker.web .Sending build context to Docker Daemon 3.3 MB Step 1: Latest FROM Microsoft /dotnet --> 7d4dc5c258eb Step 2: WORKDIR /app ---> Using cache ---> 98d48a4e278c Step 3 : COPY . /app ---> d5df216b274a Removing intermediate container 0a70f0f2b681 Step 4 : RUN dotnet restore ---> Runningin 0c8a9c4d5ba1
  Restore completed in 939.01 ms for /app/HelloDocker.Web.csproj.
  Restoring packages for /app/HelloDocker.Web.csproj...
  Restore completed in1.38 SECfor /app/HelloDocker.Web.csproj.
 ---> 479f6b5cc7f0
Removing intermediate container 0c8a9c4d5ba1
Step 5 : EXPOSE 5000
 ---> Running in f97feceb7f1b
 ---> 562a95328196
Removing intermediate container f97feceb7f1b
Step 6 : ENV ASPNETCORE_URLS http://*:5000
 ---> Running in 403d8e2e25a6
 ---> 16b7bd572410
Removing intermediate container 403d8e2e25a6
Step 7 : ENTRYPOINT dotnet run
 ---> Running in 0294f87ce3fd
 ---> 532e44a7fd54
Removing intermediate container 0294f87ce3fd
Successfully built 532e44a7fd54
[root@iZ288a3qazlZ HelloDocker.Web]# docker run -d -p 80:5000 hellodocker.web
9d28bb3fa553653e4c26bf727715c82a837a2c224a0942107f3fab08c0a2686d
[root@iZ288a3qazlZ HelloDocker.Web]# curl -i http://localhostHTTP/1.1 200 OK Date: Sat, 23 Dec 2017 14:23:15 GMT Content-Type: text/ HTML; charset=utf-8 Server: Kestrel Transfer-Encoding: chunkedCopy the code

At this point, we use Docker to complete the perfect. Containerized deployment of NET Core projects.

Over? Also have no!

The image I packaged is saved locally, how can I deploy the image to another machine? Keep looking.

6. Push the image to the warehouse

In section 3, we briefly introduced that there is a Registry for storing images. Please register an account in Docker Hub by yourself, and then we can put the local packaged image in the warehouse under your account. ! After registration, execute docker login:

[root@iZ288a3qazlZ HelloDocker.Web]# docker login
Login with your Docker ID to push and pull images from Docker Hub. If you don't have a Docker ID, head over to https://hub.docker.com to create one. Username: shengjie Password: Login Succeeded [root@iZ288a3qazlZ HelloDocker.Web]# docker images REPOSITORY TAG IMAGE ID CREATED SIZE hellodocker.web Latest 532E44a7FD54 13 minutes ago 1.745 GBCopy the code

Docker push:

$ docker push hellodocker.web
Error response from daemon: You cannot push a "root" repository. Please rename your repository to docker.io/<user>/<repo> (ex: docker.io/shengjie/hellodocker.web)
Copy the code

Push failed, indicating that our image name is not standard. The original image was named in

/

format before being pushed. So how do we rename it? We rename it by tagging:

$ docker tag hellodocker.web shengjie/hellodocker.web:v1 $ docker images REPOSITORY TAG IMAGE ID CREATED SIZE Hellodocker. Web latest 532 e44a7fd54 35 minutes line 1.745 GB yanshengjie/hellodocker web v1 532 e44a7fd54 35 minutes a line 1.745 GB $docker push shengjie/hellodocker web The push refers to a repository [docker. IO/shengjie hellodocker. Web] 774b128a8c4f: Pushed 7bf42a9b5527: Pushed bd7f01c2dc6f: Pushed ....Copy the code

On a different machine, we simply executed the following command to complete multiple deployments.

docker run -p 80:5000 <username>/hellodocker.web:v1
Copy the code

7. The last

If you follow the practice step by step, believe you to Docker as well. I have a preliminary understanding of the cross-platform features of NET Core, and I believe you have a deeper understanding of Docker Build, Ship, and Run Any App, Anywhere.

This is the end of the actual practice of this article. In the next chapter, we will see how to complete it with Docker. Distributed deployment of NET Core Web projects!!

The resources

Hello Docker HOSTING.NET CORE ON LINUX WITH Docker – A NOOB’s GUIDE Docker command Collects common LINUX commands