使用 Docker Compose 建立多容器應用程式Create a Multi-Container App with Docker Compose

在本教學課程中,您將了解如何在 Visual Studio for Mac 中使用 Docker Compose 管理多個容器並在它們之間通訊。In this tutorial, you'll learn how to manage more than one container and communicate between them when using Docker Compose in Visual Studio for Mac.

先決條件Prerequisites

建立 ASP.NET Core Web 應用程式並新增 Docker 支援Create an ASP.NET Core Web Application and Add Docker Support

  1. 藉由移至 [檔案] > [新增解決方案] 來建立新解決方案。Create a new solution by going to File > New Solution.
  2. 在 [ web 和主控台] > 應用 程式下,選擇 [ web 應用程式 ] 範本:  建立新的 ASP.NET 應用程式Under Web and Console > App choose the Web Application template: Create a new ASP.NET application
  3. 選取目標 Framework。Select the target framework. 在此範例中,我們將使用 .NET Core 3.1:  設定目標 frameworkIn this example we will use .NET Core 3.1: Set target framework
  4. 輸入專案詳細資料,例如,[專案名稱] (此範例中為 DockerDemoFrontEnd ) 和 [解決方案名稱] ( DockerDemo )。Enter the project details, such as Project Name ( DockerDemoFrontEnd in this example) and Solution Name ( DockerDemo ). 所建立的專案包含建置和執行 ASP.NET Core 網站所需的所有基本項目。The created project contains all the basics you need to build and run an ASP.NET Core web site.
  5. 在 [方案] 視窗中,以滑鼠右鍵按一下 DockerDemoFrontEnd 專案,然後選取 [ 新增] > 新增 Docker 支援 : ![ 新增 docker 支援]](media/docker-quickstart-3.png)In the Solution Window, right click the DockerDemoFrontEnd project and select Add > Add Docker Support : Add docker support

Visual Studio for Mac 會將稱為 docker-compose 的專案自動新增到解決方案,並將 Dockerfile 新增到您的現有專案。Visual Studio for Mac will automatically add a new project to your solution called docker-compose and add a Dockerfile to your existing project.

建立 ASP.NET Core Web API 並新增 Docker 支援Create an ASP.NET Core Web API and Add Docker Support

接下來,我們將會建立第二個專案,作為我們的後端 API。Next we will create a second project which will act as our backend API. .NET Core API 範本包括一個控制器,可讓我們處理 RESTful 要求。The .NET Core API template includes a controller that allows us to handle RESTful requests.

  1. 以滑鼠右鍵按一下現有解決方案,選取 [新增] > [新增專案] 以新增專案。Add a new project to the existing solution by right-clicking on the solution and choosing Add > Add New Project.
  2. 在 [ Web 和主控台] > 應用程式 下,選擇 API 範本。Under Web and Console > App choose the API template.
  3. 選取目標 Framework。Select the target framework. 在此範例中,我們將使用 .NET Core 3.1。In this example we will use .NET Core 3.1.
  4. 在此範例中,輸入專案詳細資料,例如專案名稱 ( MyWebAPI ) 。Enter the project details, such as Project Name ( MyWebAPI in this example).
  5. 建立之後,請移至 [方案] 視窗,以滑鼠右鍵按一下 [MyWebAPI] 專案,然後選取 [ 新增] > 新增 Docker 支援 ]。Once created, go to the Solution Window and right click the MyWebAPI project and select Add > Add Docker Support.

系統會自動更新 docker-compose 專案中的 docker-compose.yml 檔案,將 API 專案納入現有 Web 應用程式專案。The docker-compose.yml file in the docker-compose project will be automatically updated to include the API project alongside the existing Web App project. 當我們建置並執行 docker-compose 專案時,這些專案每個都會部署到個別的 Docker 容器。When we build and run the docker-compose project, each of these projects will be deployed to a separate Docker container.

version: '3.4'

services:
  dockerdemofrontend:
    image: ${DOCKER_REGISTRY-}dockerdemofrontend
    build:
      context: .
      dockerfile: DockerDemoFrontEnd/Dockerfile

  mywebapi:
    image: ${DOCKER_REGISTRY-}mywebapi
    build:
      context: .
      dockerfile: MyWebAPI/Dockerfile

整合兩個容器Integrate The Two Containers

我們的解決方案中現在有兩個 ASP.NET 專案,且兩個都已設定 Docker 支援。We now have two ASP.NET projects in our solution and both are configured with Docker support. 接下來,我們需要新增一些程式碼!Next we need to add some code!

  1. DockerDemoFrontEnd 專案中,開啟 Pages/Index. .cs 檔案,然後 OnGet 以下列程式碼取代方法:In the DockerDemoFrontEnd project, open the Pages/Index.cshtml.cs file, and replace the OnGet method with the following code:

     public async Task OnGet()
     {
        ViewData["Message"] = "Hello from webfrontend";
    
        using (var client = new System.Net.Http.HttpClient())
        {
           // Call *mywebapi*, and display its response in the page
           var request = new System.Net.Http.HttpRequestMessage();
           request.RequestUri = new Uri("http://mywebapi/WeatherForecast");
           var response = await client.SendAsync(request);
           ViewData["Message"] += " and " + await response.Content.ReadAsStringAsync();
        }
     }
    

    注意

    在實際執行的程式碼中,您不應該在 HttpClient 每個要求之後處置。In production code, you shouldn't dispose HttpClient after every request. 如需最佳作法,請參閱 使用 HttpClientFactory 來執行復原的 HTTP 要求For best practices, see Use HttpClientFactory to implement resilient HTTP requests.

  2. 在 [Index.cshtml] 檔案中,新增一行以顯示 ViewData["Message"],讓檔案看起來像下列程式碼:In the Index.cshtml file, add a line to display ViewData["Message"] so that the file looks like the following code:

    @page
    @model IndexModel
    @{
        ViewData["Title"] = "Home page";
    }
    
    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
        <p>@ViewData["Message"]</p>
    </div>
    
  3. 在前端和 Web API 專案中,將 Startup.cs 中的 AspNetCore 的呼叫批註為 HttpsPolicyBuilderExtensions Configure ,因為此範例程式碼會使用 HTTP, Startup.cs 而非 HTTPS 來呼叫 Web API。In both the Front End and Web API projects, comment out the call to Microsoft.AspNetCore.Builder.HttpsPolicyBuilderExtensions.UseHttpsRedirection in the Configure method in Startup.cs , because this sample code uses HTTP, not HTTPS, to call the Web API.

                //app.UseHttpsRedirection();
    
  4. docker-compose 專案設定為啟始專案並移至 [執行] > [開始偵錯]。Set the docker-compose project as the startup project and go to Run > Start Debugging. 如果一切都設定正確,您會看到訊息 [Hello from webfrontend and webapi (with value 1).]:If everything is configured correctly, you see the message "Hello from webfrontend and webapi (with value 1).":

執行中的 Docker 多容器解決方案