(C# ASP.NET Core) How to Create a Docker Image with Visual Studio

This is a walkthrough on creating a docker image with visual studio. We start by creating a simple asp.net core project with sqlite database connectivity, and then explain how Dockerfile can be easily created, followed by a docker image. We have included database connectivity because we shall use the same project for persistence with docker volumes later on.
(Rev. 31-Oct-2024)

Categories | About |     |  

Parveen,

Ensure that Docker Desktop is Running

First of all visit the docker.com website and install the Docker Desktop program. If you are Windows 10 Home edition then you may be asked to install an additional support for linux. Accept everything and install whatever you are prompted for.

Run the docker program and verify that you are able to open its GUI window.

Video Explanation

Please watch the following youtube video:

Create a Simple ASP.NET Core Project

Next create a simple ASP.NET Core project. Do not select docker support at the time of creation - we will configure it later.

Open the project, and reach the solution explorer.

Open the program.cs file. This file is configured for sqlite connectivity. The name of the sqlite file is configured through the connection string. For sake of clarity, the configuration has been kept to bare minimum.

// program.cs file 
using HelloDocker.Pages.Models;

using Microsoft.AspNetCore.Builder;

using Microsoft.AspNetCore.Hosting;

using Microsoft.EntityFrameworkCore;

using Microsoft.Extensions.DependencyInjection;

using Microsoft.Extensions.Hosting;

Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{

  webBuilder.ConfigureServices(services =>
  {

    services.AddDbContext<MyProjectContext>(
    opt => opt.UseSqlite("Data Source=mydb")
    );

    services.AddRazorPages();

  });

  webBuilder.Configure(app =>
  {

    app.UseRouting();

    app.UseEndpoints(endpoints =>
    {

      endpoints.MapRazorPages();

    });

  });

})

.Build()
.Run();

Next open the index.cshtml file.

We have written the entire code in this file itself. We haven't used a separate backing class. This has been done for simplicity.

DbContext is obtained through dependency inject.

You can see that a BindProperty has been used for 2-way communication between the form and the index razor page.

The form data is processed in the OnPost method, and records are saved in the database.

Then, you can see the markup for the form. The current data in the database is displayed using a foreach loop.

@page

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers

@using HelloDocker.Pages.Models

@inject MyProjectContext _ctx

@functions {

  [BindProperty]
  public CMySimpleModel MyModel { get; set; } = new CMySimpleModel();

  [TempData]
  public String? Message { get; set; }

  public async Task<IActionResult> OnPost()
  {
    _ctx.MyRows?.Add(MyModel);

    await _ctx.SaveChangesAsync();

    Message = "Saved Ok!";

    return RedirectToPage();
  }

}

<span style="color:red">@TempData["Message"]</span>

<form method="post">
  <table>
  <tr>
  <td>
  <label asp-for="MyModel.Name"></label>
      </td>
  <td>
  <input asp-for="MyModel.Name" />
      </td>
    </tr>
  <tr>
  <td></td>
  <td>
  <input type="submit" />
      </td>
    </tr>
  </table>

</form>

@{
  var allRows = _ctx.MyRows?.ToList() ?? new List<CMySimpleModel>();

  if (0 == allRows.Count)
    return;
}

<h2>Current data</h2>

@foreach (var row in allRows)
{
  <div>

    @row.Name

  </div>
}

Model Classes and DbContext

Open the CMySimpleModel.cs file to have a look at the model class.

We have added two properties - ID for the primary key, and Name for a column for storing the posted text.

public class CMySimpleModel
{

  [Key]
  [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
  public int ID { get; set; }

  // string property for name 
  public String? Name { get; set; }
}

Open the project context file. We have a dbset collection for the records.

public class MyProjectContext : DbContext
{

  public MyProjectContext(DbContextOptions op) : base(op)
  {

    Database.EnsureCreated();

  }


  // dbset 
  public DbSet<CMySimpleModel>? MyRows { get; set; }
}

Run the Project so far

Run the project so that we can verify that it compiles successfully. Add some data to verify that the data is actually saved in the database.

Add Docker Support

Let us now add docker support to our project.

Right click the project and select the option Add > Docker Support.

Allow the process to complete. A file called Dockerfile appears in the solution explorer. This file has no extension. Double click to open it. It contains all the layers and instructions for creating a docker image.

Next let us generate the docker image.

Come to the solution explorer and right click the Dockerfile to open the context menu. Select the option to create docker image. Let the process complete to success.

Verifying the Created Image

Open a command prompt on your PC.

Type the command docker images and click enter.

  
  cmd> docker images

  // output is 

  REPOSITORY                        TAG       IMAGE ID   
hellodocker                       latest    abc06063d915 
mcr.microsoft.com/dotnet/aspnet   5.0       92335f6f00c1 

  

Your image should appear in the list now!

In the next tutorial we shall see how to run this image.


This Blog Post/Article "(C# ASP.NET Core) How to Create a Docker Image with Visual Studio" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.