Getting Started With ASP.NET Core & Docker

Getting Started With ASP.NET Core & Docker

This is a really short tutorial about how you may set up fast and easily a simple .NET applicaction with Docker

This is a really short tutorial about how you may set up fast and easily a simple .NET applicaction with Docker

So, things you will get from this post will be:

  1. Having a clearer idea about what is .NET and one approach about how you should start or where you may start
  2. Learning the basics about Docker to deploy your application

Oh right! then let’s start from the beginning, what is .NET and what is Docker?

.NET

.NET is a free, cross-platform, open source developer platform for building many different types of applications.> .NET is a free, cross-platform, open source developer platform for building many different types of applications.
What about .NET Core? NET Core is the framework that support ASP.NET, is a cross platform, open source re-implementation of the .NET Framework. If you want to know more in depth, I recommend you this.NET Core.

And ASP .NET? makes easy to create MVC Applications. It provides a languange named razor to build views. Basically, allow to insert C# code inside HTML, reducing coding and increasing the productivity.

You can learn more about .NET on the official page: https://dotnet.microsoft.com/learn/dotnet/what-is-dotnet

Docker

.NET is a free, cross-platform, open source developer platform for building many different types of applications.
I really like this definition, you can read more about it on: https://opensource.com/resources/what-docker or you may want to go to the official where you can read about containers as well: https://www.docker.com/

Requirements:

In order to moving forward with this tutorial you will need to have some softwares already installed on your pc, on this links you will find an installation step by step guide for Windows / Linux / MAC Platforms:

  • .NET Core
  • Docker
  • A text editor (Like Visual Studio Code, Atom, Sublime Text)

If you are able to run these commands in your shell, then you are ready to go!

Ok, let’s put hands on the code:

Open a terminal and create some folders:

mkdir NetCore-Docker
cd NetCore-Docker
mkdir src
cd src
mkdir AspMVC
cd AspMVC

Once you have created this folder tree and have your shell on AspMVC folder we create or .Net Core project:

dotnet new MVC

You should get something like this:

Now we open our project with our prefered text editor, and should have a folder tree similar to this:

At this moment we have already the basic files and structure to start creating an ASP .NET application but it isn’t dockerized, let’s do a few more steps before bring docker to the field.

Let’s run this command from command line:

dotnet publish -o ./publish

You should get something like this:

Now

cd publish
dotnet AspMVC.dll

You will get this:

You can also run this command from AspMVC folder:

dotnet run

And will get:

In your browser you will get a basic view like this either running dotnet run or dotnet AspMVC.dll, and if you have troubles with https just add the exception and it should open:

So basically we are running an ASP .NET app directly from our computer, this is what we want to achieve but without using our local dotnet software, instead, we want to use docker.

Dockerizing our app

In order to understand what we want to do, we have to understand this:

  1. Having a clearer idea about what is .NET and one approach about how you should start or where you may start
  2. Learning the basics about Docker to deploy your application

.NET is a free, cross-platform, open source developer platform for building many different types of applications.

  1. Docker containers

.NET is a free, cross-platform, open source developer platform for building many different types of applications.
So images is what we build and containers is an instance of that build that runs our code, what we want to do is create sucessfully an image that we can use to run an instance of that image, that means a container that will run our code

Let’s start for creating our Dockerfile, at this moment your shell should be located either NetCore-Docker/src/AspMVC/publish or NetCore-Docker/src/AspMVC, we need to go to our root folder, that would be NetCore-Docker

cd ../../../
# Make sure you are in the root directory! ---> NetCore-Docker
# Create new file with the name Dockerfile (extension is not required)
code Dockerfile

Now open a new file (or create) called Dockerfile on my root directory, since i use Visual Studio Code:

On this file we are going to copy this:

FROM microsoft/dotnet:sdk AS build-env
WORKDIR /app

# Copy csproj and restore as distinct layers
COPY ./src/AspMVC/*.csproj ./
RUN dotnet restore

# Copy everything else and build
COPY ./src/AspMVC ./
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", "AspMVC.dll"]

I must say this is the way that actually propose microsoft to dockerize an app, you can check it here: https://docs.microsoft.com/en-us/dotnet/core/docker/build-docker-netcore-container

But there is another way, that could result a little bit easier to understand:

FROM microsoft/dotnet:latest

WORKDIR /app

COPY ./AspMVC/publish .

ENTRYPOINT ["dotnet", "AspMVC.dll"]

If you want to know what means every reserved word and how to use it, please check: https://docs.docker.com/engine/reference/builder/

So once we got our file ready we go back to our console. Here we create our image

docker build -t myapp .

You should be getting an input similar to that, once it has finished, we run these commands, this will create an instance of our image, that means, create our container that will run our code and the second command will list us what containers we got running in our computer:

docker run -d -p 8080:80 --name MyNetApp myapp
docker ps

If everything is ok, you should be getting something similar to this:

That means our app is already working and dockerized, and we can check it writing in our browser http://localhost:8080 and we should get the same Home Page, that we got earlier running our app directly from our dotnet installed directly in our pc

Please note that when we run

docker run -d -p 8080:80 --name MyNetApp myapp

It has a few parameters

  • .NET Core
  • Docker
  • A text editor (Like Visual Studio Code, Atom, Sublime Text)

When we run

docker ps

We are listing all our running containers.

If you want to list all your images, you can just type console

docker images

And you should see a list with all image that you have on your computer, like this:

That’s it, we did it! Now we can start coding our app and easily deploy it or run it from everywhere where we can run Docker. I strongly suggest you to read about docker compose. It’s a tool that let you run multiples containers and all of them connected between each other :O.

In real world this is really common since we need to run a DB Server, with a FrontEnd Server and a BackEnd Server to run a full application.

You can get the files from:

https://github.com/nostick/dot-net-core

You will find a file call Dockerfile and Dockerfile1 if you want to switch between how you build your images just rename the file Dockerfile1 to Dockerfile or viceversa and run the same commands

What’s next?

Here are some useful articles to continue learning Docker and .NET Core

  • .NET Core
  • Docker
  • A text editor (Like Visual Studio Code, Atom, Sublime Text)

How to debug an ASP.NET Core Docker container in Windows AND Linux

How to debug an ASP.NET Core Docker container in Windows AND Linux

How to debug an ASP.NET Core Docker container in Windows AND Linux - Docker is an revolutionary tool that has far too many benefits to list in this blog post. Instead, we will be walking through the tooling that can be leveraged when you create and debug your next ASP.NET Core Docker application.

There is no question that .NET Core has exploded in popularity over the last couple of years. The new cross-platform successor to the .NET Framework has opened many new doors to developers. Using tools such as Docker have allowed developers to deploy their solutions in very repeatable and reliable ways.

Taking it a step further, what would be a better way to highlight the cross platform nature of .NET Core than exploring this on Windows AND Linux!

VISUAL STUDIO TOOLS FOR DOCKER

On the Windows side of the house, I have been impressed by the tooling that exists natively in Visual Studio. Using Visual Studio Tools for Docker makes working with containers a breeze. You can see this firsthand when creating a new ASP.NET Core project and selecting the Enable Docker Support checkbox.

Once complete, you will notice a new Dockerfile is created at the root of the project (shown below). The Dockerfile will run your application inside of a container however, that’s not all. To guarantee consistency across development machines, you can see the Dockerfile actually restores and publishes the project inside a build container. Say goodbye to those “it builds on my machine” excuses!

FROM microsoft/dotnet:2.1-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM microsoft/dotnet:2.1-sdk AS build
WORKDIR /src
COPY ["JrTech.Docker.Web/JrTech.Docker.Web.csproj", "JrTech.Docker.Web/"]
RUN dotnet restore "JrTech.Docker.Web/JrTech.Docker.Web.csproj"
COPY . .
WORKDIR "/src/JrTech.Docker.Web"
RUN dotnet build "JrTech.Docker.Web.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "JrTech.Docker.Web.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "JrTech.Docker.Web.dll"]

Auto generating a Dockerfile is a great first step however, your development process is going to be rocky if you cannot debug your code. Luckily Visual Studio does some magic for us to allow just that. If you run the application, the following output will be shown in the debug window. This highlights how Visual Studio is running the Docker container with the remote debugger attached.

docker run -dt -v "C:\Users\jason\vsdbg\vs2017u5:/remote_debugger:rw" -v "C:\Jason\Repositories\gc\ahbc_dotnet_201810\JrTech.Docker.Web\JrTech.Docker.Web:/app" -v "C:\Users\jason\AppData\Roaming\ASP.NET\Https:/root/.aspnet/https:ro" -v "C:\Users\jason\AppData\Roaming\Microsoft\UserSecrets:/root/.microsoft/usersecrets:ro" -v "C:\Users\jason.nuget\packages:/root/.nuget/fallbackpackages2" -v "C:\Program Files\dotnet\sdk\NuGetFallbackFolder:/root/.nuget/fallbackpackages" -e "DOTNET_USE_POLLING_FILE_WATCHER=1" -e "ASPNETCORE_ENVIRONMENT=Development" -e "ASPNETCORE_URLS=https://+:443;http://+:80" -e "ASPNETCORE_HTTPS_PORT=44372" -e "NUGET_PACKAGES=/root/.nuget/fallbackpackages2" -e "NUGET_FALLBACK_PACKAGES=/root/.nuget/fallbackpackages;/root/.nuget/fallbackpackages2" -p 56567:80 -p 44372:443 --entrypoint tail jrtechdockerweb:dev -f /dev/null

We can now set breakpoints and debug the application while it is running. Many of us may take this for granted however, we can see Visual Studio had to do a little bit of work to put this together for us.

I have to say, I’ve been impressed with how easy it to create an ASP.NET Core Docker container with Visual Studio. What could make it even better? Doing the same on a Linux OS! Next we will go through the same exercise with VSCode on Linux.

VISUAL STUDIO CODE ON LINUX

One of the best things about .NET Core is that it is completely cross platform. It’s been a couple years but, it still feels weird to say… we can develop, build, and run ASP.NET Core on the operating system of our choice. Visual Studio Code is also cross platform and can be run on Windows, Mac, or Linux.

To get started, we need to install the following components.

DOCKER VISUAL STUDIO CODE EXTENSION

Visual Studio Code has a great extension subsystem so, it is no surprise that there is Docker extension readily available.

Once we have the extension installed, we can get started by creating our new project. Visual Studio Code is designed for working with all kinds of languages and frameworks so, it is no surprise that we don’t have a “new project template” available. No need to worry, .NET Core has an awesome command line interface!

Using the dotnet new command, we can create a new ASP.NET Core MVC project.

[email protected]:~/Source$ dotnet new mvc -n JrTech.Docker.Web -o JrTech.Docker.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/aspnetcore-template-3pn-210 for details.

Processing post-creation actions...
Running 'dotnet restore' on JrTech.Docker.Web/JrTech.Docker.Web.csproj...
Restoring packages for /home/jason/Source/JrTech.Docker.Web/JrTech.Docker.Web.csproj...
Generating MSBuild file /home/jason/Source/JrTech.Docker.Web/obj/JrTech.Docker.Web.csproj.nuget.g.props.
Generating MSBuild file /home/jason/Source/JrTech.Docker.Web/obj/JrTech.Docker.Web.csproj.nuget.g.targets.
Restore completed in 531.14 ms for /home/jason/Source/JrTech.Docker.Web/JrTech.Docker.Web.csproj.

Restore succeeded.

[email protected]:~/Source$ code .

When Visual Studio Code launches, you will see the following popup on the bottom right corner of the IDE. Selecting ‘Yes’ will create a tasks.json file with the required build steps.

We should now see a new web project similar to the one we created with Visual Studio. There is one key difference though, we do not have a Dockerfile yet. This is where the Docker extension helps us out. We can add a Dockerfile using the Add Docker Files to Workspace command. For a default file, select ASP.NET Core as the application platform, Linux as the operating system, and port 80 as the default port.

Looking at it newly created Dockerfile, we can see a familiar file format. In essence, this is the same multistage Dockerfile we had with Visual Studio.

FROM microsoft/dotnet:2.2-aspnetcore-runtime AS base
WORKDIR /app
EXPOSE 80

FROM microsoft/dotnet:2.2-sdk AS build
WORKDIR /src
COPY ["JrTech.Docker.Web.csproj", "./"]
RUN dotnet restore "./JrTech.Docker.Web.csproj"
COPY . .
WORKDIR "/src/."
RUN dotnet build "JrTech.Docker.Web.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "JrTech.Docker.Web.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "JrTech.Docker.Web.dll"]

The next step is setting up our debug configuration so we can debug our application while it is running in a container. From the Debug pane, we can select Add Configuration from the drop-down to add our new configuration.

We have a ton of options to choose from but, in our case, we want to add the Docker: Launch .NET Core (Preview) configuration.

Depending on our containers requirements we can apply specific configurations here. With a newly created project, using the defaults works fine.

With our new configuration selected, clicking the play button will build and run our container with the debugger attached. As we did with Visual Studio, we can now add breakpoints and step through our application.

SUMMARY

As I’ve said previously, Docker is a very powerful technology, especially when combined with an orchestrator like Kubernetes. It is great to see the developer tooling we get out of the box with ASP.NET Core. I’ve been on a bit of a Linux kick lately so, it’s encouraging that we can replicate this behavior on multiple operating systems.

Happy coding!

Originally published by  JROB5756 at espressocoder.com

=============================

Thanks for reading

If you liked this post, share it with all of your programming buddies!

Follow me on Facebook | Twitter

How to build a Docker container for beginners

Tutorial Laravel 6 with Docker and Docker-Compose

Docker for the Absolute Beginner - Hands On - DevOps

Docker Basics: Docker Compose

Docker for Absolute Beginners


Build an ASP.NET Core application with Docker and Visual Studio

Build an ASP.NET Core application with Docker and Visual Studio

In this article will guide you building, running, and debugging an ASP.NET Core application with Docker and Visual Studio ...

Development frameworks, platforms, and tools that do not offer a rich development experience will ultimately lack in adoption. Docker is an amazing technology but, what is the development experience like? Not too long ago, I wrote about creating and debugging an ASP.NET Core Docker container in two different ways.

  1. Visual Studio 2017 (Windows)
  2. Visual Studio Code (Linux)

With the launching of Visual Studio 2019 recently, I felt compelled to target one more IDE  .

PREREQUISITES

The first step is making sure Visual Studio is set up correctly. This is a simple as installing Visual Studio 2019 with the .NET Core cross-platform development workload installed. More specifically, if you select Individual Components, you need to ensure that the Container Development Tools component is selected as shown below.

Lastly, you will need to have Docker Desktop for Windows installed if you haven’t already. Once this is done, we are ready to create an ASP.NET Core Docker container in Visual Studio.

___________________________________________________________________________________

You may also like: Tutorial Laravel 6 with Docker and Docker-Compose

____________________________________________________________________________________

CREATING AN ASP.NET CORE DOCKER CONTAINER

As explained in this blog post, the new project dialog in Visual Studio has been given an overhaul. I have become quite accustomed to the previous version however, I must admit the improvements are very intuitive. For this tutorial, we will select the ASP.NET Core Web Application template and click Next.

Once this is done, we can give our new project a name, location, and solution name. As you can see, this process is much more like a wizard as opposed to the monolithic dialog that was used in previous versions.

Now we can provide some more specifics for our new application. For the purposes of this example we will select the API project template. That said, a key piece can be found in the advanced section. Here we want to select Enable Docker Support and make sure Linux is selected in the following drop-down.

Similar to when working with Visual Studio 2017, a Dockerfile is generated with four named build stages (base, build, publish, and final). Multistage builds are helpful to optimize layers and keep our Dockerfile easy to maintain.

FROM mcr.microsoft.com/dotnet/core/aspnet:2.1-stretch-slim AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/core/sdk:2.1-stretch AS build
WORKDIR /src
COPY ["JrTech.Docker.Vs2019/JrTech.Docker.Vs2019.csproj", "JrTech.Docker.Vs2019/"]
RUN dotnet restore "JrTech.Docker.Vs2019/JrTech.Docker.Vs2019.csproj"
COPY . .
WORKDIR "/src/JrTech.Docker.Vs2019"
RUN dotnet build "JrTech.Docker.Vs2019.csproj" -c Release -o /app

FROM build AS publish
RUN dotnet publish "JrTech.Docker.Vs2019.csproj" -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "JrTech.Docker.Vs2019.dll"]

Next lets take a look at how our application gets built and deployed as a container.

BUILDING THE CONTAINER

Prior to building or debugging our application, we will already notice some activity in the Container Tools output in the output window.

========== Checking for Container Prerequisites ==========
Verifying that Docker Desktop is installed...
Docker Desktop is installed.
========== Verifying that Docker Desktop is running... ==========
Verifying that Docker Desktop is running...
Docker Desktop is running.
========== Verifying Docker OS ==========
Verifying that Docker Desktop's operating system mode matches the project's target operating system...
Docker Desktop's operating system mode matches the project's target operating system.
========== Pulling Required Images ==========
Checking for missing Docker images...
Docker images are ready.
========== Warming up container(s) for JrTech.Docker.Vs2019 ==========
Starting up container(s)...
docker build -f "C:\Users\jason\source\repos\JrTech.Docker.Vs2019\JrTech.Docker.Vs2019\Dockerfile" -t jrtechdockervs2019:dev --target base --label "com.microsoft.created-by=visual-studio" --label "com.microsoft.visual-studio.project-name=JrTech.Docker.Vs2019" "C:\Users\jason\source\repos\JrTech.Docker.Vs2019"
Sending build context to Docker daemon 18.94kB
Step 1/6 : FROM mcr.microsoft.com/dotnet/core/aspnet:2.1-stretch-slim AS base
---> 9a8e320a271f
Step 2/6 : WORKDIR /app
---> Using cache
---> 3bca35715a51
Step 3/6 : EXPOSE 80
---> Using cache
---> 854d77a40024
Step 4/6 : EXPOSE 443
---> Using cache
---> 962750b42169
Step 5/6 : LABEL com.microsoft.created-by=visual-studio
---> Using cache
---> 09e977d58879
Step 6/6 : LABEL com.microsoft.visual-studio.project-name=JrTech.Docker.Vs2019
---> Using cache
---> 5053ced48dc0
Successfully built 5053ced48dc0
Successfully tagged jrtechdockervs2019:dev
SECURITY WARNING: You are building a Docker image from Windows against a non-Windows Docker host. All files and directories added to build context will have '-rwxr-xr-x' permissions. It is recommended to double check and reset permissions for sensitive files and directories.
docker run -dt -v "C:\Users\jason\vsdbg\vs2017u5:/remote_debugger:rw" -v "C:\Users\jason\source\repos\JrTech.Docker.Vs2019\JrTech.Docker.Vs2019:/app" -v "C:\Users\jason\AppData\Roaming\Microsoft\UserSecrets:/root/.microsoft/usersecrets:ro" -v "C:\Users\jason\AppData\Roaming\ASP.NET\Https:/root/.aspnet/https:ro" -v "C:\Users\jason.nuget\packages:/root/.nuget/fallbackpackages2" -v "C:\Program Files\dotnet\sdk\NuGetFallbackFolder:/root/.nuget/fallbackpackages" -e "DOTNET_USE_POLLING_FILE_WATCHER=1" -e "ASPNETCORE_ENVIRONMENT=Development" -e "NUGET_PACKAGES=/root/.nuget/fallbackpackages2" -e "NUGET_FALLBACK_PACKAGES=/root/.nuget/fallbackpackages;/root/.nuget/fallbackpackages2" -p 49558:80 -p 44304:443 --entrypoint tail jrtechdockervs2019:dev -f /dev/null
e93c776e500a98321e35fa1c02d2d89e6f64ff92f4c3e945f635f9c590f17d70
Container started successfully.
========== Finished ==========

This is a new optimization added to Visual Studio 2019. In order to allow our application to build, deploy, and run quickly Visual Studio preemptively creates a container. We can see the container by running docker ps from the command line.

E:\Software\cmder_mini
λ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e93c776e500a jrtechdockervs2019:dev "tail -f /dev/null" 20 seconds ago Up 19 seconds 0.0.0.0:49558->80/tcp, 0.0.0.0:44304->443/tcp flamboyant_shirley

With the http and https ports exposed, the container is primed and ready to go. If we open a browser and browse to the http port, 49558 in my case, we see that we do not get a response yet. This makes sense because while our container is started, nothing is actually deployed to it yet.

To build and deploy our application to the running container, we must debug using the Docker configuration profile. This should be selected by default. Once we are up and running, we can see that our application is available through http/https ports that were exposed in our Docker container.

We can also see that the same container that was started when we created our application is still running. When we run our application a new container isn’t created, rather the output from our project is copied into the running container. We can see this by observing the running containers which shows or original container is still running.

E:\Software\cmder_mini
λ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
e93c776e500a jrtechdockervs2019:dev "tail -f /dev/null" 7 minutes ago Up 7 minutes 0.0.0.0:49558->80/tcp, 0.0.0.0:44304->443/tcp flamboyant_shirley

Visual Studio remotely attaches to the process running inside the container. This gives us the ability to set breakpoints and debug our application while it is running.

The development experience in Visual Studio 2019 is very similar to Visual Studio 2017 as it pertains to building Docker containers. That said, there are some nice enhancements under the hood that make the development process even more seemless. It is great to Microsoft’s continued investment in this great new technology!

Happy Coding!

Further Reading

How To Set Up Laravel, Nginx, and MySQL with Docker Compose

Containerizing a Node.js Application for Development With Docker Compose

Docker Basics: Docker Compose

Originally published by JROB5756  at espressocoder.com

++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on Facebook | Twitter


WordPress in Docker. Part 1: Dockerization

WordPress in Docker. Part 1: Dockerization

This entry-level guide will tell you why and how to Dockerize your WordPress projects.

This entry-level guide will tell you why and how to Dockerize your WordPress projects.