Windows Server 2016 TP5: Deploying .NET Core App in Windows container - Introduction
Create a virtual machine in Azure using the following image: "Windows Server 2016 with Containers Tech Preview 5".
Once the virtual machine is created, verify Docker is installed by running the below command from PowerShell:
Create an empty .NET Core project using the command line tool or Yeoman generator.
Modify the project.json shown below. This uses the KestrelNuGett package for self-hosting the application.
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable",
"emitEntryPoint": true
},
"dependencies": {},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0"
},
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*"
},
"imports": "dnxcore50"
}
}
}
Update the program.cs file to use Kestrel and also the startup page where we configure the request pipeline.
using Microsoft.AspNetCore.Hosting;
namespace HelloWeb
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseStartup<Startup>().UseUrls("http://*:5000")
.Build();
host.Run();
}
}
}
Update the Startup.cs file to get the machine name. It will return the name of the physical machine or the name of the container based on where it is run.
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using System.Text;
using System;
using System.Collections;
using Microsoft.Extensions.Logging;
namespace HelloWeb
{
public class Startup
{
public void Configure(IApplicationBuilder app)
{
app.Run(async ctx =>
{
StringBuilder builder = new StringBuilder();
builder.AppendLine($"Hello from machine : {GetMachineName()}!");
await ctx.Response.WriteAsync($"{builder.ToString()}");
});
}
private static string GetMachineName()
{
var machineName = Environment.MachineName;
return machineName;
}
}
}
Dockerize the application by adding the docker file as shown below:
FROM microsoft/dotnet:1.0.0-preview2-windowsservercore-sdk
RUN mkdir dotnetapp
COPY . dotnetapp
WORKDIR dotnetapp
RUN dotnet restore
EXPOSE 5000
ENTRYPOINT ["dotnet", "run"]
Run the below command from the project directory which will in turn create a Docker image as shown:
docker build -t mywebapp .
Run the below command to run the Docker image created in the above step.
docker run -it -p 5000:5000 mywebapp
Once the application is running, we need to do one more step for the application to be accessible in the container host or outside the Azure virtual machine.
Create Rule in a network security group
In our case, since we are exposing port 5000 from the container to host, we have added a inbound rule as shown below:
Now we will able to browse to the application in the container from the container host or outside the virtual machine.