Combine ASP NET Core and SQL Server with Docker Compose

Source: Internet
Author: User
Tags curl dotnet mssql web services asp net docker compose



Directory


    • Docker Compose
      • Brief introduction
      • Installation
    • WEBAPI Project
      • Create a project
      • Writing Dockfile
    • Web MVC Project
      • Create a project
      • Writing Dockfile
    • Writing docker-compose.yml files
    • Run the project
    • Source
    • Reference

This article simulates a relatively complete project, including front-end (MVC), Back-end (WEBAPI), and Database (Mssql-server-linux). Assemble and execute them through the Docker Compose definition. Related to Docker Compose installation, command, DOCKER-COMPOSE.YML file authoring, WebApi and MVC project authoring, Dockfile writing, etc.

About Docker Compose


Docker compose is one of the Docker musketeers that defines and runs multiple Docker container applications, docker compose up and is responsible for the rapid orchestration of Docker container clusters.



We can define a separate application container through Dockerfile. However,docker compose command  in the daily work, docker compose volumes often encounter the need for multiple containers to cooperate with each other to complete a task. For example, to implement a Web project, in addition to the Web Services container itself, it is often necessary to add the backend database service container, install docker compose and so on.



Compose just met the demand. It allows the user to define a set of associated application containers through a separate DOCKER-COMPOSE.YML configuration board file (YAML format). Then, docker compose build using a single command, you can create and start all services based on the configuration.


Installation
    1. Curl Download Docker Compose

sudo curl -L https://github.com/docker/compose/releases/download/{{site.compose_version}}/docker-compose-$(uname -s)-$(uname -m) -o /usr/local/bin/docker-compose

Replace {{site.compose_version}} with the latest version number

    1. Assign Execute Permissions

sudo chmod +x /usr/local/bin/docker-compose
    1. Test whether the installation was successful

docker-compose --version
WEBAPI Project Creation Project
    1. Refer to the Microsoft sample create a Web API for creating a net core 2.1-based WEBAPI project named Todo.api. Refer to the example to add model and database context.

    2. Register the database context in configureservices.



services.AddDbContext<TodoContext>(options =>
    options.UseSqlServer(Configuration["ConnectionString"]));
    1. Refer to Microsoft Sample work with SQL Server LocalDB Add seed class and add seed initializer inside Program.cs.


public static void Main(string[] args)
    {
        var host = CreateWebHostBuilder(args).Build();

        using (var scope = host.Services.CreateScope())
        {
            var services = scope.ServiceProvider;

            try
            {
                var context = services.GetRequiredService<TodoContext>();
                if (context.Database.GetPendingMigrations().Any())
                {
                    context.Database.Migrate();
                    SeedData.Initialize(services);
                }
            }
            catch (Exception ex)
            {
                var logger = services.GetRequiredService<ILogger<Program>>();
                logger.LogError(ex, "An error occurred seeding the DB.");
            }
        }

        host.Run();
    }

Just run the add-migration command to generate the migration. There is no need to execute the update-database command, as the program runs through the context. Database.migrate () to perform the migration.

Writing Dockfile


FROM microsoft/dotnet:2.1-aspnetcore-runtime

WORKDIR /app

EXPOSE 80/tcp

ENTRYPOINT ["dotnet", "Todo.Api.dll"]
WEB MVC Project Creation Project
    1. Create a net core 2.1-based web MVC project named Webmvc.

    2. Add the Service to invoke the WebApi open interface.



public class TodoService : ITodoService
    {
        private readonly HttpClient _apiClient;
        private readonly IOptions<ApiConfig> _setting;

        public TodoService(HttpClient httpClient, IOptions<ApiConfig> settings)
        {
            _apiClient = httpClient;
            _setting = settings;
        }

        public async Task<IEnumerable<TodoViewModel>> GetTodos()
        {
            var url = $"{_setting.Value.TodoApiUrl}/api/todo";
            var dataString = await _apiClient.GetStringAsync(url);
            return JsonConvert.DeserializeObject<IEnumerable<TodoViewModel>>(dataString);
        }

        public async Task<IEnumerable<string>> GetMachineNames()
        {
            var url = $"{_setting.Value.TodoApiUrl}/api/machine";
            var dataString = await _apiClient.GetStringAsync(url);
            return JsonConvert.DeserializeObject<IEnumerable<string>>(dataString);
        }
    }
Writing Dockfile


FROM microsoft/dotnet:2.1-aspnetcore-runtime

WORKDIR /app

EXPOSE 80/tcp

ENTRYPOINT ["dotnet", "WebMVC.dll"]
Writing docker-compose.yml files


version: "3"

services:
  webmvc:
    image: webmvc
    environment:
      - ASPNETCORE_URLS=http://0.0.0.0:80
    build:
      context: ./WebMVC
      dockerfile: Dockerfile
    ports: 
    - "8080:80"
    volumes: 
      - ./WebMVC/bin/pub/:/app
    container_name: webmvc
    depends_on:
      - todo.api

  todo.api:
    image: todo.api
    environment:
      - ASPNETCORE_URLS=http://0.0.0.0:80
      - ConnectionString=Server=sql.data;User=sa;[email protected];Database=WebAPI_SQL_Docker_Demo;    
    build:
      context: ./Todo.Api
      dockerfile: Dockerfile
    ports: 
      - "8081:80"
    volumes: 
      - ./Todo.Api/bin/pub/:/app
    container_name: todo.api
    depends_on:
      - sql.data

  sql.data:
    image: microsoft/mssql-server-linux:2017-latest
    environment:
      - [email protected]
      - ACCEPT_EULA=Y
    ports:
      - "1433:1433"

Image: Specify the name of the mirror or build image
Build: Build the build image. The context directive specifies the path to the folder where Dockerfile is located, and the Dockerfile directive specifies Dockerfile file name
Environment: Setting Environment variables
Ports: Exposes port information. Using the host Port: Container port (host:container) format
Volumes: The Mount path setting for the data volume. Host path (Host:container) can be set
Container_name: Specifies the container name. The default is to use the project name _ service Name _ ordinal format
DEPENDS_ON: Solve the problem of container dependency and start-up


For more information, refer to Compose file version 3 reference


Run the project
    1. Execute thedocker-compose buildservice container in the build project under the Docker-compose.yml file-through directory.

docker-compose build
    1. Bydocker-compose upcreating, associating, and starting the service.

docker-compose up

-D runs the service container in the background.
--scale Service=num creates n instances of a service.


Please refer to Compose (docker-compose) CLI for details reference


Source
    • GitHub
Reference
    • Compose GitHub
    • Quickstart:compose and ASP. NET Core with SQL Server
    • Get Started Building microservices with ASP. NET Core and Docker in Visual Studio Code
    • Docker Compose Project


Combine ASP NET Core and SQL Server with Docker Compose


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.