I am fascinated about how important is for most of the developers, not only know how to create a simple application in .net core like a webapi or mvc app, but also understand how to deploy those type of applications in operating systems like Ubuntu or Mac.
The purpose of this post is to show you how easy is to achieve it in Ubuntu through a simple example in a webapi application built in .net core.
First of all, what is Docker?
If you have ever used virtual machines like Virtualbox or Vmware to run a version of an Operating System in your computer, you will find that Docker is something similar, but Docker will not create a whole operating system to run applications, Docker will allow you to continue using your Operating System and additionally you can run applications in a container that encapsulates all the dependencies that this app need to work appropiately.
Docker is an open source tool designed to make it easier to create, deploy and run applications by using containers, so the applicatioon is going to be encapsulated in a packages that contains all the libraries and dependencies required.
Step 1: Clone the repository
sudo git clone https://github.com/ricardojavister/net-core-api.git
And create a new branch named “deploy-net-core-with-docker”.
sudo git checkout -b deploy-net-core-with-docker
sudo dotnet restore
sudo dotnet build
sudo dotnet run
Type in your browser http://localhost:8080/swagger/index.html
You will see a page like this:
Step 2: Install Docker in Ubuntu
sudo apt-get update
sudo apt-get remove docker docker-engine docker.io
sudo apt install docker.io
sudo systemctl start docker
sudo systemctl enable docker
Step 3: Create Docker file
This file will contain all the settings required to make a deploy appropiately in Linux.
FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build-envWORKDIR /app# Copy csproj and restore as distinct layersCOPY *.csproj ./RUN dotnet restore# Copy everything else and buildCOPY . ./RUN dotnet publish -c Release -o out# Build runtime imageFROM mcr.microsoft.com/dotnet/core/aspnet:3.1WORKDIR /appEXPOSE 80COPY --from=build-env /app/out .ENTRYPOINT ["dotnet", "crudstore.dll"]
Step 4: Create ignore file named .dockerignore
And put inside of it these lines:
Step 5: Publishing the Application with Docker
Run the next commands to run and deploy the application.
sudo docker build -t crudstore .
sudo docker run -p 8080:80 crudstore