Run .NET MVC with SQL server (Container)  in Ubuntu

Run .NET MVC with SQL server (Container) in Ubuntu

In this article, we will guide you through the process of running a .NET MVC application with an SQL Server container on an Ubuntu system. This comprehensive tutorial covers everything from setting up Docker and creating an SQL Server container to configuring and running a .NET application. By the end of this guide, you will have a fully functional .NET MVC application connected to a SQL Server database, all running seamlessly on Ubuntu.

Preparing SQL server for Application

Install Docker

sudo apt-get update
sudo apt  install docker.io

Create a SQL server container

we are using the Microsft mcr.microsoft.com/mssql/server:2022-latest image from docker hub . Follow these steps to create the container

sudo docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=yourStrong@Password123!" \
   -p 1433:1433 --name sql1 --hostname sql1 \
   -d \
   mcr.microsoft.com/mssql/server:2022-latest

Note: if you remove the container all the data will be lost , Read more how can you persist data

https://learn.microsoft.com/en-us/sql/linux/sql-server-linux-docker-container-configure?view=sql-server-ver16&pivots=cs1-bash#persist

Access your SQL server

you can access and run queries, and create a TestDB database to your SQL server (Running in Docker container) from GUI like SSMS or Azure Data Studio, by changing the server address to your IP address of the Ubuntu server.

Server=192.168.100.59,1433;Database=TestDB;Encrypt=false;User Id=sa;Password=yourStrong@Password123!;MultipleActiveResultSets=true"

I am doing this by going inside the container

 sudo docker exec -it sql1 "bash"

inside the container

/opt/mssql-tools/bin/sqlcmd -S localhost -U sa -P "yourStrong@Password123!"

inside the SQL server

CREATE DATABASE TestDB;
SELECT Name from sys.databases;
GO

Create a Database

Create a Todo Table

Preparing .NET application

this time instead of creating a project by ourselves self we will existing project from the Microsoft GitHub repository

Install .NET SDK

sudo apt-get update && \
  sudo apt-get install -y dotnet-sdk-8.0

Verify the installation

dotnet --list-sdks
dotnet --list-runtimes

Clone the existing Application

git clone https://github.com/Azure-Samples/msdocs-app-service-sqldb-dotnetcore.git

move inside the project

cd msdocs-app-service-sqldb-dotnetcore/

you need to update a couple of things

Updating appsettings.json

update your connecting string in DotNetCoreSqlDb/appsettings.json to this, also replace the server address, and database name you created in SQL server setup section

update <TargetFramework> to the correct .NET version

update the DotNetCoreSqlDb/DotNetCoreSqlDb.csproj for.net version you have configured in your machine,

Run the Application

the Todos data is coming from the SQL server.

Did you find this article valuable?

Support Muhammad Usama by becoming a sponsor. Any amount is appreciated!