Write down Docker Compose file for ASP.net  and SQL Server application

Write down Docker Compose file for ASP.net and SQL Server application

Here, Docker Compose file for a simple ASP.NET application with a SQL Server database. This example assumes you are using ASP.NET Core, but adjustments can be made for other ASP.NET versions.

  1. ASP.NET Application Structure: Create a directory structure for your ASP.NET application:

     /myaspnetapp
     |-- src
     |   `-- MyAspNetApp
     |       `-- (ASP.NET application files)
     |-- docker-compose.yml
     `-- Dockerfile
    
  2. Dockerfile (in the same directory as your ASP.NET application):

     FROM mcr.microsoft.com/dotnet/core/sdk:3.1 AS build
     WORKDIR /app
    
     # Copy csproj and restore as distinct layers
     COPY src/MyAspNetApp/*.csproj ./
     RUN dotnet restore
    
     # Copy everything else and build
     COPY src/MyAspNetApp/. ./
     RUN dotnet publish -c Release -o out
    
     FROM mcr.microsoft.com/dotnet/core/aspnet:3.1 AS runtime
     WORKDIR /app
     COPY --from=build /app/out ./
    
     ENTRYPOINT ["dotnet", "MyAspNetApp.dll"]
    
  3. docker-compose.yml:

     version: '3.8'
    
     services:
       web:
         build:
           context: .
           dockerfile: Dockerfile
         ports:
           - "8080:80"
         depends_on:
           - db
    
       db:
         image: "mcr.microsoft.com/mssql/server"
         environment:
           SA_PASSWORD: "YourPassword123"
           ACCEPT_EULA: "Y"
           MSSQL_PID: "Express"
         ports:
           - "1433:1433"
         volumes:
           - sql-data:/var/opt/mssql/data
    
     volumes:
       sql-data:
    

Explanation:

  • The web service uses the ASP.NET Docker image to build and run the ASP.NET Core application. It exposes port 8080 on the host, mapping it to port 80 on the container. The depends_on directive ensures that the db service starts before the web service.

  • The db service uses the official SQL Server Docker image from Microsoft. It sets the necessary environment variables such as SA_PASSWORD, ACCEPT_EULA, and MSSQL_PID. The SQL Server data is persisted using a Docker volume named sql-data.

  • The volumes section defines the Docker volume used for persisting SQL Server data.

Make sure to replace "YourPassword123" with a strong password for the SQL Server SA account.

To run the application, navigate to the directory containing the docker-compose.yml file and run:

docker-compose up

This will build and start both the ASP.NET application and the SQL Server container. Access the ASP.NET application at http://localhost:8080.

To stop and remove the containers, use:

docker-compose down

Adjust the versions and configurations based on your specific requirements and ASP.NET version.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!