Exploring ASP.NET Core 2.0 And Docker On MacOS

Introduction

Last year, I wrote an article about “.NET Core On Mac - Building An ASP.NET Core App With Web API, EF, PostgreSQL And Running It On Docker”. The article was using the .NET Core 1.1 version and if you’ve been following the same steps mentioned from the article using .NET Core/ ASP.NET Core 2.0, then it’s expected that the steps won’t work anymore.

Over a year, there have been some changes from .NET Core 1.x to version 2.0. In this article, we’ll explore ASP.NET Core 2.0 and Docker by building a simple Web API application and deploying it on a Docker container.

Note: Before you move down further, make sure that you have a basic understanding of ASP.NET Core and Docker because I will not talk about the details of each technology in this article.

Prerequisites

Before getting our hands dirty, we’ll need to update/install the required tools and SDKs for us to build and run the application in MAC environment. Go ahead and install the following:

Docker Images for .NETCore 2.0 and ASP.NET Core 2.0

Once you have installed all prerequisites, we need to pull the required docker images for both .NET Core and ASP.NET Core from Docker Hub. Go ahead and open the terminal and run the following commands separately:

  • docker pull microsoft/dotnet:2.0.0-sdk
  • docker pull microsoft/aspnetcore:2.0.0
  • docker pull microsoft/aspnetcore-build:2.0.0

After pulling the docker images, you can verify it by running the following command:

docker images

The command above should result in something like this.

ASP.NET Core

Creating Your First ASP.NET Core Project

Now, fire up Visual Studio 2017 and create an empty ASP.NET Core project just like in the figure below.

ASP.NET Core

ASP.NET Core

Click “Next”. On the next screen, select .NET Core 2.0 as target framework and then click “Next”. It should now bring you to the following screen:

For the simplicity of this demo, just name the project as “aspnetcoredemo” and then browse the location to where you would want the project to be created. Click “Create” to let Visual Studio generate the default files for you. You should be able to see something like this,

ASP.NET Core

Running the Project for the First Time

Click the Play button to build and run the project. When everything builds successfully, it should display something like this in your browser,

ASP.NET Core

That’s it! We now have an ASP.NET Core app running in MAC.

Let’s Get Going!

Now, to make this demo more exciting, we will move a bit further and create a simple Web API that handles a basic CRUD operations and use Posgres as our database. We will then run our application and database inside a Docker container.

Adding a Docker File

The first thing we need is to create a Docker in our project. The Dockerfile contains the instruction to build the docker image. For more information, see: Dockerfile Reference

Add the following command within the Dockerfile,

FROM microsoft/aspnetcore-build:2.0.0 AS build

WORKDIR /code

COPY . .

RUN dotnet restore

RUN dotnet publish --output /output --configuration Release

FROM microsoft/aspnetcore:2.0.0

COPY --from=build /output /app

WORKDIR /app

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

Integrating EF Core and PostgreSQL

Switch back to Visual Studio and install the latest NuGet packages mentioned below.

  • EntityFrameworkCore.PostgreSQL
  • EntityFrameworkCore.Tools
  • EntityFrameworkCore.Design

The packages above enable us to use EntityFramework Core as our data access mechanism. We’ll be using EF Core to sync and update the database from PostgreSQL database and then use Web API to serve data requests.

Entity Framework Core now supports a variety of database providers. In this particular demo, we will integrate PostgreSQL in our .NET Core application.The easiest way to install Postgres is using Homebrew which should be included upon installing the .NET Core SDK. Now run the following command to download and install PostgreSQL,

$ brew install postgresql

If the installation goes well, then the database manager should be installed. Now, let's launch the PostgreSQL service container by running the following command,

$ docker run -d --name localdb -e POSTGRES_PASSWORD=supersecret postgres

The -d option runs a container in the background and prints the container ID. The --name assigns a name to the container, in this case we named our container as "localdb". The -e allow us to set the environment variables, which in this case, we’ve set a password to "supersecret" for our Postgres image using the POSTGRES_PASSWORD variable.

Running the command above will expose the postgres port 5432 which allow a standard container to be available to the linked containers. The initdb will also be generated with default user and database.

To verify that our PostgreSQL Docker container is up and running, do

$ docker ps

To test the connection, you can do,

$ docker run -it --rm --link pg-db:postgres postgres psql -h postgres -U postgres

Creating the Application

Now that we have our database ready inside a Docker container, it’s time for us to build the application.

Setting Up a Database ConnectionString

Add a new empty .jsonfile and then name the file as “appsettings” just like in the figure below.

ASP.NET Core

Then copy the following setting below,

  1. "DbContextSettings": {  
  2.     "ConnectionString""User ID=postgres;Password=supersecret;Server=postgres;Port=5432;Database=POSTGRES_USER;Integrated Security=true;Pooling=true;"  
  3.   
  4.   }  

The connection string above will allow us to connect to the PostgreSQL service container that we ran earlier.

Creating a Model

For this demo, we will be using EF Code-First approach which means, we will create the Model first and then run a migration to let EF generate the database/schema based on our Model.

Create a new class at the root of your project and name the file as “Student”. Copy the following code below,

  1. namespace aspnetcoredemo  
  2. {  
  3.     public class Student  
  4.     {  
  5.         public int Id { get; set; }  
  6.         public string FirstName { get; set; }  
  7.         public string LastName { get; set; }  
  8.     }  
  9. }  

Defining a DbContext

EF Core Code-First development approach require us to define a data access context class that inherits from the DbContext class. Now, let’s add a new class at the root of our project. Name the file as “StudentContext” and then copy the following code below,

  1. using System;  
  2. using Microsoft.EntityFrameworkCore;  
  3.   
  4. namespace aspnetcoredemo  
  5. {  
  6.     public class StudentContext: DbContext  
  7.     {  
  8.         public StudentContext  
  9.         (DbContextOptions<StudentContext> options)    
  10.             : base(options)    
  11.         { }  
  12.   
  13.         public DbSet<Student> Students { get; set; }  
  14.     }  
  15. }  

Registering Services with Dependency Injection

Next thing that we need is to register the DbContext as a service and enable MVC service to enable Web API. Open startup.cs and replace the existing code with the following,

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.AspNetCore.Builder;  
  6. using Microsoft.AspNetCore.Hosting;  
  7. using Microsoft.AspNetCore.Http;  
  8. using Microsoft.EntityFrameworkCore;  
  9. using Microsoft.Extensions.Configuration;  
  10. using Microsoft.Extensions.DependencyInjection;  
  11.   
  12. namespace aspnetcoredemo  
  13. {  
  14.     public class Startup  
  15.     {  
  16.         public Startup(IHostingEnvironment env)  
  17.         {  
  18.             var builder = new ConfigurationBuilder()  
  19.                 .SetBasePath(env.ContentRootPath)  
  20.                 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)  
  21.                 .AddJsonFile($"appsettings.{env.EnvironmentName} .json", optional: true)  
  22.                 .AddEnvironmentVariables();  
  23.             Configuration = builder.Build();  
  24.         }  
  25.   
  26.         public IConfigurationRoot Configuration { get; }  
  27.         // This method gets called by the runtime. Use this method to add services to the container.  
  28.         // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940  
  29.         public void ConfigureServices(IServiceCollection services)  
  30.         {  
  31.             services.AddMvc();  
  32.   
  33.             var connectionString = Configuration["DbContextSettings:ConnectionString"];  
  34.             services.AddDbContext<StudentContext>(opts => opts.UseNpgsql(connectionString));  
  35.         }  
  36.   
  37.         // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.  
  38.         public void Configure(IApplicationBuilder app, IHostingEnvironment env)  
  39.         {  
  40.             if (env.IsDevelopment())  
  41.             {  
  42.                 app.UseDeveloperExceptionPage();  
  43.             }  
  44.   
  45.             app.UseMvc();  
  46.   
  47.         }  
  48.     }  
  49. }  

Let’s modify the Program.cs to create a database on startup. Here’s the full code below,

  1. using System;  
  2. using Microsoft.AspNetCore;  
  3. using Microsoft.AspNetCore.Hosting;  
  4. using Microsoft.EntityFrameworkCore;  
  5. using Microsoft.Extensions.DependencyInjection;  
  6. using Microsoft.Extensions.Logging;  
  7.   
  8. namespace aspnetcoredemo  
  9. {  
  10.     public class Program  
  11.     {  
  12.         public static void Main(string[] args)  
  13.         {  
  14.             BuildWebHost(args).Run();  
  15.   
  16.             var host = BuildWebHost(args);  
  17.   
  18.             using (var scope = host.Services.CreateScope())  
  19.             {  
  20.                 var services = scope.ServiceProvider;  
  21.   
  22.                 try  
  23.                 {  
  24.                     services.GetService<StudentContext>().Database.Migrate();  
  25.                 }  
  26.                 catch (Exception ex)  
  27.                 {  
  28.                     var logger = services.GetRequiredService<ILogger<Program>>();  
  29.                     logger.LogError(ex, "An error occurred seeding the DB.");  
  30.                 }  
  31.             }  
  32.   
  33.             host.Run();  
  34.         }  
  35.   
  36.         public static IWebHost BuildWebHost(string[] args) =>  
  37.             WebHost.CreateDefaultBuilder(args)  
  38.                 .UseStartup<Startup>()  
  39.                 .Build();  
  40.     }  
  41. }  

EF Core does not do the migration automatically, that’s why we need the pieces of configuration above for us to use Code-First migrations. The Database.Migrate() method piece is responsible for two things: (1) The creation of database in PostgreSQL if it does not exist yet. (2) Migrating the database schemas to the latest version.

Adding Migrations

We will be using EF Core tools to scaffold our migration and updating the database. We’ll be using the command line (dotnet CLI) to run our migrations. We can’t add the Microsoft.EntityFrameworkCore.Tools.DotNet package from Nuget as of this time of writing because of this error:

“Package 'Microsoft.EntityFrameworkCore.Tools.DotNet 2.0.0' has a package type 'DotnetCliTool' that is not supported by project”

As a workaround, we can edit the project file (.csproj) and add the following configuration below,

  1. <ItemGroup>  
  2.    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" />  
  3.  </ItemGroup>  

Now open the terminal to the location where your project root is located and then do,

$ dotnet ef migrations add InitialMigration

The ef migration add is the command to add migrations. When the migration is successful, you should be able to see a new folder named "Migrations" that contains the migration files as shown in the figure below.

ASP.NET Core

The files generated above will be used to create the database on the initial run.

Creating a Web API Controller

It’s time for us to create a simple Web API methods to work with simple GET and POST requests. Add a new Web API Controller class and copy the following code,

  1. using System.Collections.Generic;  
  2. using System.Linq;  
  3. using Microsoft.AspNetCore.Mvc;  
  4.   
  5. namespace aspnetcoredemo.API  
  6. {  
  7.     [Route("api/[controller]")]  
  8.     public class StudentsController : Controller  
  9.     {  
  10.         private readonly StudentContext _context;   
  11.   
  12.         public StudentsController(StudentContext context)  
  13.         {  
  14.             _context = context;  
  15.         }  
  16.   
  17.         // GET: api/students    
  18.         public IEnumerable<Student> Get()    
  19.         {    
  20.             return _context.Students.ToList();    
  21.         }    
  22.   
  23.         // GET api/students/1    
  24.         [HttpGet("{id}")]    
  25.         public Student Get(int id)    
  26.         {    
  27.             return _context.Students.FirstOrDefault(x => x.Id == id);    
  28.         }    
  29.   
  30.         // POST api/students    
  31.         [HttpPost]    
  32.         public IActionResult Post([FromBody]Student value)    
  33.         {    
  34.             _context.Students.Add(value);    
  35.             _context.SaveChanges();    
  36.             return StatusCode(201, value);    
  37.         }    
  38.   
  39.     }  
  40. }  

Nothing really fancy here; the code above just contains a few basic methods that communicate to StudentContext. Notice that we’ve injected an instance of our StudentContext in the Controller’s constructor, so we can interact with our database, and use it for querying the data.

Running the Application on Docker

At this point, we are ready to deploy the application on Docker. First let’s build the app by running the following command,

$ docker build -t dockerdemo .

The command above will generate a new instance of image within our docker machine. You can check the list of image by running docker images in the command line.

Now, run the following command to ensure that our PostgreSQL database image is up and running,

$ docker ps

Now, let’s run our ASP.NET Core 2 application and link the database that we’ve created using the following command,

$ docker run -it -p 5000:80 --link localdb:postgres dockerdemo

Testing the Web API Endpoints

Here are some of the screenshots of the Endpoint test results, using Postman.

POST

ASP.NET Core

GET

ASP.NET Core

GET/id

ASP.NET Core

That's it! I hope you will find this article useful.

References

Summary

In this article, we’ve learned the basics on setting up .NET Core 2 on MAC environment and learned how to create a simple ASP.NET Core 2 application with Web API, EF, PostgreSQL and running it on Docker.

Up Next
    Ebook Download
    View all
    Learn
    View all