Introducing ASP.NET Core with Docker

Hello .Net world!

This is a small tutorial on how to create an ASP.NET application and then build it and run it using Docker. We will check all the advantages of using these two technologies together and why you should learn how to use them.

A few introductory concepts

What is ASP.NET?

ASP.NET stands for Active Server Pages and It is a web application framework developed by Microsoft in 2002. ASP.NET is part of Microsoft’s .NET framework which means is a very valuable tool for developers as it allows them to build dynamic and rich web sites and web applications when combined with the .NET framework supported languages, like C# and VB.NET.

What is the difference between ASP.NET and ASP.NET Core?

Now we know what ASP.NET is, but what exactly is the difference between ASP.NET and ASP.NET Core?

The main difference is that ASP.NET belongs to the .NET framework while ASP.NET Core belongs to .NET Core. This means ASP.NET works on Windows while ASP.NET Core is multiplatform and works not only in Windows, but in macOS and Linux too.

Another difference is that .NET Core is more lightweight and modular than .NET Framework, so It is recommended when working with Docker containers, which is important in this tutorial.

What is and Docker and why we need it?

Docker is an open source tool designed to make it easier to develop, deploy and run applications by using “containers”. These containers allow a developer to package an application up with all the parts it needs, such as libraries and other dependencies, into a standardized unit that includes everything it needs to run.

By doing so, the developer can rest assured that the application will always run the same, and makes collaboration as simple as sharing a container image.


Let’s try to build an app

Practice is, in most not-so-humble opinions, the best way to incorporate actual knowledge, so let’s develop a very simple calculator using C#, ASP.NET and JavaScript.

Prerequisites

First we need to download and install all the necessary software:

This can also be done with Visual Studio 2017, which is the full IDE and has way more functionality, but is more than we need. Although it makes our lives easier, I believe a developer should be comfortable using a text editor and the terminal.

You can verify Docker is installed correctly by running `docker version` on the terminal. It should look something like this:

Once you have installed everything, open VS Code, go to the “extensions tab” on the side and install the following ones:

  • C# extension
  • Docker extension

This extensions will make working with C# and Docker easier by providing us shortcuts and many other useful features.

Start coding

Now you are all set to begin with the code. Open the terminal where you want to create your project, and then run the following commands:

mkdir Calculator
cd Calculator
dotnet new mvc
code .

What this will do is create a new directory called “Calculator”, enter the directory, create a new MVC project, and then open VS Code within the projects folder.

Note: MVC is an architectural pattern that separates the project into three main components:
Model: where all the data-related classes and their logic are.
View: where all the UI logic of the application is.
Controller: the interface between the Model and the View components. It processes all the business logic and the incoming requests.
This pattern is widely used in web applications and even mobile because of its ability to reuse code.

If you see this warning message, select Yes:

And the project structure should look like this:

Now, if you press F5 on the keyboard or go to Debug → Start debugging should open your web browser with something like this:

Once you are there, go to the Controllers folder, and open the HomeController.cs file. Inside you will find a few methods. Those are all the requests that the controller can handle. If you go to the Views/Home folder, you will find the views that the controller methods return. The one we will be modifying is the Index.cshtml file.

You will see there is already code in that file. Just delete all the code and replace it with this:

<div class="container">
<div class="row">
<div class="col-12">
<form runat="server" class="my-2">
<div class="form-group result-line">
<h1>Calculator</h1>
<input class="form-control" type="text" name="number1" id="number1">
<div class="my-1 text-right">
<input runat="server" onclick="add()" class="btn btn-secondary" type="button" value="+">
<input runat="server" onclick="subtract()" class="btn btn-secondary" type="button" value="-">
<input runat="server" onclick="multiplication()" class="btn btn-secondary" type="button" value="x">
<input runat="server" onclick="division()" class="btn btn-secondary" type="button" value="÷">
</div>
          <input class="form-control" type="text" name="number2" id="number2">
</div>
        <div class="form-group form-check">
<input class="form-control" type="text" name="result" id="result" value="" disabled>
</div>
</form>
</div>
</div>
</div>

In that code you can see:

  • Two text inputs for the numbers involved in the operation
  • Four buttons for the different operations
  • The result text input which is disabled

But this is just pure HTML with some basic Bootstrap classes, it doesn’t have any functionality. For that we can add the following code:

<script>
const add = () => {
$('#result').val( Number($('#number1').val()) + Number($('#number2').val() ));
}
  const subtract = () => {
$('#result').val( Number($('#number1').val()) - Number($('#number2').val() ));
}
  const multiplication = () => {
$('#result').val( Number($('#number1').val()) * Number($('#number2').val() ));
}
  const division = () => {
$('#result').val( Number($('#number1').val()) / Number($('#number2').val() ));
}
</script>

These are called arrow functions (you can read more about arrow functions here) and will solve the mathematic operations with a little jQuery to get and set the values.

That could be it, but let’s add some css to make it look better.

<style>
.my-2 {
margin-top: 2rem;
margin-bottom: 2rem;
}
  .my-1 {
margin-top: 1rem;
margin-bottom: 1rem;
}
  .col-12 {
max-width: 40rem;
}
  .text-right {
text-align: right;
}
  .result-line {
border-bottom: solid 1px black;
padding: 0 1rem 0.75rem 1rem;
}
</style>

After adding that, the web app should look something like this:

Note that the header and the footer are still the same even though we deleted all the Index file. This is because the header and the footer, as well as some references to stylesheets and javascript files, are in the _Layout.cshtml. Everything we did in the Index file is rendered where the @RenderBody() is into the layout file.

Let’s dockerize all of this

Now that we have our application, let’s convert it to a Docker image so we can use it as a container. We have Docker already installed in our computer, so now just open it and log in. Then, It should appear in the task bar.

Now we have to tell Docker all the steps needed for our applications image to be built so it works properly. The file which will have all the commands is called “Dockerfile”. Although VisualStudio Code can help us, we will create this file manually.

Use this command to create the file:

touch Dockerfile

Then open it in VisualStudio Code and paste this code:

FROM microsoft/dotnet:sdk AS build-env
WORKDIR /app
# Copy csproj and restore as distinct layers
COPY *.csproj ./
RUN dotnet restore
# Copy everything else and build
COPY . ./
RUN dotnet publish -c Release -o out
# Build runtime image
FROM microsoft/dotnet:aspnetcore-runtime
WORKDIR /app
COPY --from=build-env /app/out .
ENTRYPOINT ["dotnet", "Calculator.dll"]

You can find more information about this code in the Docker documentation.

Then create a new file which will tell Docker to ignore certain folders and files when it is building the image. To do this, create a new file with this command:

touch .dockerignore

And paste the following code into that file:

bin\
obj\

Save both files and we are ready to build and run the docker image. From the terminal run the following commands:

  • $ docker build -t calculator . to build the image with the name “calculator”
  • $ docker run -d -p 8080:80 --name calc calculator to run the image “calculator” in the port 80
-t is for indicating the new tag name for the image
-d is for indicating detached-mode, runs in the background of the terminal
-p is for mapping the port 8080 to 80
--name is for indicating the wat to identify the container

After running this commands, if you go to your web browser, in the port 8080 of localhost, you should be able to see the application running.

And that’s it! Now you know how to create a simple ASP.NET Core app and build a Docker image with it so it’s portable and can run in different environments.


Want the project?

If you want the code from this tutorial, you can download it from here.


Further Reading

This is just an introduction to the .NET Core and Docker world, but there are a lot of things to read about If you want to learn more. I highly recommend you read about these two topics: