搭配 ASP.NET Core 使用 Visual Studio Tools for DockerVisual Studio Tools for Docker with ASP.NET Core

Visual Studio 2017 及更新版本支援建置、偵錯和執行以 .NET Core 為目標的容器化 ASP.NET Core 應用程式。Visual Studio 2017 and later versions support building, debugging, and running containerized ASP.NET Core apps targeting .NET Core. 同時支援 Windows 和 Linux 容器。Both Windows and Linux containers are supported.

檢視或下載範例程式碼 (英文) (如何下載)View or download sample code (how to download)

必要條件Prerequisites

安裝和設定Installation and setup

若要安裝 Docker,請先檢閱適用於 Windows 的 Docker:What to know before you install (安裝前須知) 中的資訊。For Docker installation, first review the information at Docker for Windows: What to know before you install. 接下來,安裝 適用於 Windows 的 DockerNext, install Docker For Windows.

Docker for Windows 中的 Shared Drives (共用磁碟機) 必須設定為支援磁碟區對應和偵錯。Shared Drives in Docker for Windows must be configured to support volume mapping and debugging. 以滑鼠右鍵按一下系統匣的 Docker 圖示,並選取 [設定],然後選取 [共用磁碟機]。Right-click the System Tray's Docker icon, select Settings, and select Shared Drives. 選取 Docker 儲存檔案的磁碟機。Select the drive where Docker stores files. 按一下 [套用]。Click Apply.

為容器選取共用本機 C 磁碟機的對話方塊

提示

未設定 [共用磁碟機] 時,Visual Studio 2017 15.6 版和更新版本會顯示提示。Visual Studio 2017 versions 15.6 and later prompt when Shared Drives aren't configured.

將專案新增至 Docker 容器Add a project to a Docker container

若要容器化 ASP.NET Core 專案,該專案必須以 .NET Core 為目標。To containerize an ASP.NET Core project, the project must target .NET Core. 同時支援 Linux 和 Windows 容器。Both Linux and Windows containers are supported.

將 Docker 支援新增至專案時,請選擇 Windows 或 Linux 容器。When adding Docker support to a project, choose either a Windows or a Linux container. Docker 主機必須執行相同的容器類型。The Docker host must be running the same container type. 若要變更執行中 Docker 執行個體中的容器類型,請以滑鼠右鍵按一下系統匣的 Docker 圖示,然後選擇 [Switch to Windows containers...] (切換至 Windows 容器...) 或 [Switch to Linux containers] (切換至 Linux 容器...)。To change the container type in the running Docker instance, right-click the System Tray's Docker icon and choose Switch to Windows containers... or Switch to Linux containers....

新增應用程式New app

使用 ASP.NET Core Web 應用程式專案範本來建立新的應用程式時,請選取 [啟用 Docker 支援] 核取方塊:When creating a new app with the ASP.NET Core Web Application project templates, select the Enable Docker Support check box:

啟用 Docker 支援核取方塊

如果目標架構是 .NET Core,則 [OS] 下拉式清單會允許選取容器類型。If the target framework is .NET Core, the OS drop-down allows for the selection of a container type.

現有應用程式Existing app

針對以 .NET Core 為目標的 ASP.NET Core 專案,有兩個選項可透過工具來新增 Docker 支援。For ASP.NET Core projects targeting .NET Core, there are two options for adding Docker support via the tooling. 在 Visual Studio 中開啟專案,然後選擇下列其中一個選項:Open the project in Visual Studio, and choose one of the following options:

  • 選取 [專案] 功能表的 [Docker 支援]。Select Docker Support from the Project menu.
  • 以滑鼠右鍵按一下方案總管中的專案,然後選取 [新增] > [Docker 支援]。Right-click the project in Solution Explorer and select Add > Docker Support.

Visual Studio Tools for Docker 不支援將 Docker 新增至以 .NET Framework 為目標的現有 ASP.NET Core 專案。The Visual Studio Tools for Docker don't support adding Docker to an existing ASP.NET Core project targeting .NET Framework.

Dockerfile 概觀Dockerfile overview

Dockerfile,是用於建立最終 Docker 映像的配方,會新增至專案根目錄。A Dockerfile, the recipe for creating a final Docker image, is added to the project root. 請參閱 Dockerfile 參考,以了解其內的命令。Refer to Dockerfile reference for an understanding of the commands within it. 此特定 Dockerfile 使用多階段建置,包含四個不同的具名建置階段:This particular Dockerfile uses a multi-stage build with four distinct, named build stages:

FROM mcr.microsoft.com/dotnet/core/aspnet:2.1 AS base
WORKDIR /app
EXPOSE 59518
EXPOSE 44364

FROM mcr.microsoft.com/dotnet/core/sdk:2.1 AS build
WORKDIR /src
COPY HelloDockerTools/HelloDockerTools.csproj HelloDockerTools/
RUN dotnet restore HelloDockerTools/HelloDockerTools.csproj
COPY . .
WORKDIR /src/HelloDockerTools
RUN dotnet build HelloDockerTools.csproj -c Release -o /app

FROM build AS publish
RUN dotnet publish HelloDockerTools.csproj -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "HelloDockerTools.dll"]

上述的 Dockerfilemicrosoft/dotnet 映像為基礎。The preceding Dockerfile is based on the microsoft/dotnet image. 此基底映像包含 ASP.NET Core 執行階段與 NuGet 套件。This base image includes the ASP.NET Core runtime and NuGet packages. 套件會進行 Just-in-Time (JIT) 編譯,以改善啟動效能。The packages are just-in-time (JIT) compiled to improve startup performance.

核取新專案對話方塊的 [設定 HTTPS] 核取方塊時,Dockerfile 會提供兩個連接埠。When the new project dialog's Configure for HTTPS check box is checked, the Dockerfile exposes two ports. 其中一個連接埠用於 HTTP 流量,另一個連接埠則用於 HTTPS。One port is used for HTTP traffic; the other port is used for HTTPS. 如果未選取該核取方塊,則會為 HTTP 流量提供單一連接埠 (80)。If the check box isn't checked, a single port (80) is exposed for HTTP traffic.

FROM microsoft/aspnetcore:2.0 AS base
WORKDIR /app
EXPOSE 80

FROM microsoft/aspnetcore-build:2.0 AS build
WORKDIR /src
COPY HelloDockerTools/HelloDockerTools.csproj HelloDockerTools/
RUN dotnet restore HelloDockerTools/HelloDockerTools.csproj
COPY . .
WORKDIR /src/HelloDockerTools
RUN dotnet build HelloDockerTools.csproj -c Release -o /app

FROM build AS publish
RUN dotnet publish HelloDockerTools.csproj -c Release -o /app

FROM base AS final
WORKDIR /app
COPY --from=publish /app .
ENTRYPOINT ["dotnet", "HelloDockerTools.dll"]

上述的 Dockerfilemicrosoft/aspnetcore 映像為基礎。The preceding Dockerfile is based on the microsoft/aspnetcore image. 此基底映像包含 ASP.NET Core NuGet 套件,其進行 Just-in-Time (JIT) 編譯,以改善啟動效能。This base image includes the ASP.NET Core NuGet packages, which are just-in-time (JIT) compiled to improve startup performance.

為應用程式新增容器協調器支援Add container orchestrator support to an app

Visual Studio 2017 版本 15.7 或更早的版本支援將 Docker Compose 作為唯一的容器協調流程解決方案。Visual Studio 2017 versions 15.7 or earlier support Docker Compose as the sole container orchestration solution. 透過 [新增] > [Docker 支援] 可新增 Docker Compose 成品。The Docker Compose artifacts are added via Add > Docker Support.

Visual Studio 2017 版本 15.8 或更新版本只有在指示進行時,才會新增協調流程解決方案。Visual Studio 2017 versions 15.8 or later add an orchestration solution only when instructed. 以滑鼠右鍵按一下方案總管中的專案,然後選取 [新增] > [容器協調器支援]。Right-click the project in Solution Explorer and select Add > Container Orchestrator Support. 提供兩個不同的選擇:Docker ComposeService FabricTwo different choices are offered: Docker Compose and Service Fabric.

Docker ComposeDocker Compose

Visual Studio Tools for Docker 會將 docker-compose 專案,新增至包含下列檔案的解決方案:The Visual Studio Tools for Docker add a docker-compose project to the solution with the following files:

  • docker-compose.dcproj – 代表專案的檔案。docker-compose.dcproj – The file representing the project. 包含 <DockerTargetOS> 項目,指定要使用的 OS。Includes a <DockerTargetOS> element specifying the OS to be used.
  • .dockerignore – 列出在產生組建內容時,要排除的檔案與目錄模式。.dockerignore – Lists the file and directory patterns to exclude when generating a build context.
  • docker-compose.yml – 基礎 Docker Compose 檔案,用於定義分別使用 docker-compose builddocker-compose run 建置並執行的映像集合。docker-compose.yml – The base Docker Compose file used to define the collection of images built and run with docker-compose build and docker-compose run, respectively.
  • docker-compose.override.yml – Docker Compose 將會讀取的選擇性檔案,包含服務的組態覆寫。docker-compose.override.yml – An optional file, read by Docker Compose, with configuration overrides for services. Visual Studio 會執行 docker-compose -f "docker-compose.yml" -f "docker-compose.override.yml" 來合併這些檔案。Visual Studio executes docker-compose -f "docker-compose.yml" -f "docker-compose.override.yml" to merge these files.

docker-compose.yml 檔案會參考執行專案時所建立映像的名稱:The docker-compose.yml file references the name of the image that's created when the project runs:

version: '3.4'

services:
  hellodockertools:
    image: ${DOCKER_REGISTRY}hellodockertools
    build:
      context: .
      dockerfile: HelloDockerTools/Dockerfile

在上述範例中,image: hellodockertools 會在以偵錯模式執行應用程式時產生 hellodockertools:dev 映像。In the preceding example, image: hellodockertools generates the image hellodockertools:dev when the app runs in Debug mode. 發行模式執行應用程式時,會產生 hellodockertools:latest 映像。The hellodockertools:latest image is generated when the app runs in Release mode.

如果映像會推送至登錄,會在映像名稱前加上 Docker Hub 使用者名稱 (例如,dockerhubusername/hellodockertools)。Prefix the image name with the Docker Hub username (for example, dockerhubusername/hellodockertools) if the image is pushed to the registry. 或者,根據設定將映像名稱變更為包含私人登錄 URL (例如,privateregistry.domain.com/hellodockertools)。Alternatively, change the image name to include the private registry URL (for example, privateregistry.domain.com/hellodockertools) depending on the configuration.

如果您需要基於組建設定的不同行為 (例如偵錯或發行),請新增特定於設定的 docker-compose 檔案。If you want different behavior based on the build configuration (for example, Debug or Release), add configuration-specific docker-compose files. 應根據組建設定來命名檔案 (例如 docker-compose.vs.debug.ymldocker-compose.vs.release.yml) 並放在與 docker-compose-override.yml 檔案相同的位置。The files should be named according to the build configuration (for example, docker-compose.vs.debug.yml and docker-compose.vs.release.yml) and placed in the same location as the docker-compose-override.yml file.

使用特定於設定的覆寫檔案,可以為偵錯和發行組建設定指定不同的組態設定 (例如環境變數或進入點)。Using the configuration-specific override files, you can specify different configuration settings (such as environment variables or entry points) for Debug and Release build configurations.

Service FabricService Fabric

除了基礎必要條件之外,Service Fabric 協調流程解決方案還需要下列必要條件:In addition to the base Prerequisites, the Service Fabric orchestration solution demands the following prerequisites:

Service Fabric 不支援在 Windows 上的本機開發叢集中執行 Linux 容器。Service Fabric doesn't support running Linux containers in the local development cluster on Windows. 如果專案已在使用 Linux 容器,Visual Studio 會提示您切換至 Windows 容器。If the project is already using a Linux container, Visual Studio prompts to switch to Windows containers.

Visual Studio Tools for Docker 會執行下列工作:The Visual Studio Tools for Docker do the following tasks:

  • <project_name>應用程式 Service Fabric 應用程式專案,新增至解決方案。Adds a <project_name>Application Service Fabric Application project to the solution.

  • Dockerfile.dockerignore 檔案,新增至 ASP.NET Core 專案。Adds a Dockerfile and a .dockerignore file to the ASP.NET Core project. 如果 ASP.NET Core 專案中已存在 Dockerfile,則會重新命名為 Dockerfile.originalIf a Dockerfile already exists in the ASP.NET Core project, it's renamed to Dockerfile.original. 會建立類似如下的新 DockerfileA new Dockerfile, similar to the following, is created:

    # See https://aka.ms/containerimagehelp for information on how to use Windows Server 1709 containers with Service Fabric.
    # FROM microsoft/aspnetcore:2.0-nanoserver-1709
    FROM microsoft/aspnetcore:2.0-nanoserver-sac2016
    ARG source
    WORKDIR /app
    COPY ${source:-obj/Docker/publish} .
    ENTRYPOINT ["dotnet", "HelloDockerTools.dll"]
    
  • 會將 <IsServiceFabricServiceProject> 項目新增至 ASP.NET Core 專案的 .csproj 檔案:Adds an <IsServiceFabricServiceProject> element to the ASP.NET Core project's .csproj file:

    <IsServiceFabricServiceProject>True</IsServiceFabricServiceProject>
    
  • 會將 PackageRoot 資料夾新增至 ASP.NET Core 專案。Adds a PackageRoot folder to the ASP.NET Core project. 該資料夾包含服務資訊清單與新服務的設定。The folder includes the service manifest and settings for the new service.

如需詳細資訊,請參閱將 Windows 容器中的 .NET 應用程式部署至 Azure Service FabricFor more information, see Deploy a .NET app in a Windows container to Azure Service Fabric.

偵錯Debug

從工具列的偵錯下拉式清單中選取 [Docker],然後開始對應用程式進行偵錯。Select Docker from the debug drop-down in the toolbar, and start debugging the app. [輸出] 視窗的 Docker 檢視會顯示下列將採取的動作:The Docker view of the Output window shows the following actions taking place:

  • 取得 microsoft/dotnet 執行階段映像的 2.1-aspnetcore-runtime 標籤 (若尚未存在於快取中)。The 2.1-aspnetcore-runtime tag of the microsoft/dotnet runtime image is acquired (if not already in the cache). 映像會安裝 ASP.NET Core 與 .NET Core 執行階段,以及相關聯的程式庫。The image installs the ASP.NET Core and .NET Core runtimes and associated libraries. 在生產環境中最好是執行 ASP.NET Core 應用程式。It's optimized for running ASP.NET Core apps in production.
  • 在容器內,ASPNETCORE_ENVIRONMENT 環境變數設定為 DevelopmentThe ASPNETCORE_ENVIRONMENT environment variable is set to Development within the container.
  • 會提供兩個動態指派的連接埠:一個用於 HTTP,另一個用於 HTTPS。Two dynamically assigned ports are exposed: one for HTTP and one for HTTPS. 可使用 docker ps 命令,查詢指派到 localhost 的連接埠。The port assigned to localhost can be queried with the docker ps command.
  • 應用程式會複製至容器。The app is copied to the container.
  • 預設瀏覽器會在偵錯工具使用動態指派的連接埠附加至容器的情況下啟動。The default browser is launched with the debugger attached to the container using the dynamically assigned port.

產生的應用程式 Docker 映像,會標記為 devThe resulting Docker image of the app is tagged as dev. 此映像以 microsoft/dotnet 基底映像的 2.1-aspnetcore-runtime 標籤為基礎。The image is based on the 2.1-aspnetcore-runtime tag of the microsoft/dotnet base image. 在 [套件管理員主控台] (PMC) 視窗中,執行 docker images 命令。Run the docker images command in the Package Manager Console (PMC) window. 這會顯示電腦上的映像:The images on the machine are displayed:

REPOSITORY        TAG                     IMAGE ID      CREATED         SIZE
hellodockertools  dev                     d72ce0f1dfe7  30 seconds ago  255MB
microsoft/dotnet  2.1-aspnetcore-runtime  fcc3887985bb  6 days ago      255MB
  • 取得 microsoft/aspnetcore 執行階段映像 (若尚未存在於快取中)。The microsoft/aspnetcore runtime image is acquired (if not already in the cache).
  • 在容器內,ASPNETCORE_ENVIRONMENT 環境變數設定為 DevelopmentThe ASPNETCORE_ENVIRONMENT environment variable is set to Development within the container.
  • 連接埠 80 會公開並對應至本機主機的動態指派連接埠。Port 80 is exposed and mapped to a dynamically assigned port for localhost. 連接埠是由 Docker 主機所決定,並且可以使用 docker ps 命令進行查詢。The port is determined by the Docker host and can be queried with the docker ps command.
  • 應用程式會複製至容器。The app is copied to the container.
  • 預設瀏覽器會在偵錯工具使用動態指派的連接埠附加至容器的情況下啟動。The default browser is launched with the debugger attached to the container using the dynamically assigned port.

產生的應用程式 Docker 映像,會標記為 devThe resulting Docker image of the app is tagged as dev. 映像以 microsoft/aspnetcore 基底映像為基礎。The image is based on the microsoft/aspnetcore base image. 在 [套件管理員主控台] (PMC) 視窗中,執行 docker images 命令。Run the docker images command in the Package Manager Console (PMC) window. 這會顯示電腦上的映像:The images on the machine are displayed:

REPOSITORY            TAG  IMAGE ID      CREATED        SIZE
hellodockertools      dev  5fafe5d1ad5b  4 minutes ago  347MB
microsoft/aspnetcore  2.0  c69d39472da9  13 days ago    347MB

注意

因為偵錯組態會使用磁碟區掛接來提供重複的體驗,所以 dev 映像不會有應用程式內容。The dev image lacks the app contents, as Debug configurations use volume mounting to provide the iterative experience. 若要推送映像,請使用 [發行] 組態。To push an image, use the Release configuration.

在 PMC 中執行 docker ps 命令。Run the docker ps command in PMC. 請注意是使用容器來執行應用程式:Notice the app is running using the container:

CONTAINER ID        IMAGE                  COMMAND                   CREATED             STATUS              PORTS                   NAMES
baf9a678c88d        hellodockertools:dev   "C:\\remote_debugge..."   21 seconds ago      Up 19 seconds       0.0.0.0:37630->80/tcp   dockercompose4642749010770307127_hellodockertools_1

編輯後繼續Edit and continue

針對靜態檔案和 Razor 檢視所做的變更會自動更新,而不需要編譯步驟。Changes to static files and Razor views are automatically updated without the need for a compilation step. 進行變更並儲存,然後重新整理瀏覽器來檢視更新。Make the change, save, and refresh the browser to view the update.

程式碼檔案的修改需要編譯以及重新啟動容器內的 Kestrel。Code file modifications require compilation and a restart of Kestrel within the container. 完成變更之後,請使用 CTRL+F5 來執行程序,並啟動容器內的應用程式。After making the change, use CTRL+F5 to perform the process and start the app within the container. Docker 容器不會進行重建或停止。The Docker container isn't rebuilt or stopped. 在 PMC 中執行 docker ps 命令。Run the docker ps command in PMC. 請注意,原始容器在 10 分鐘前仍在執行:Notice the original container is still running as of 10 minutes ago:

CONTAINER ID        IMAGE                  COMMAND                   CREATED             STATUS              PORTS                   NAMES
baf9a678c88d        hellodockertools:dev   "C:\\remote_debugge..."   10 minutes ago      Up 10 minutes       0.0.0.0:37630->80/tcp   dockercompose4642749010770307127_hellodockertools_1

發行 Docker 映像Publish Docker images

當應用程式的開發和偵錯循環完畢之後,Visual Studio Tools for Docker 就會協助建立應用程式的實際執行映像。Once the develop and debug cycle of the app is completed, the Visual Studio Tools for Docker assist in creating the production image of the app. 將組態下拉式清單變更為 [發行] 並建置應用程式。Change the configuration drop-down to Release and build the app. 工具會從 Docker Hub (若尚未在快取中) 取得編譯/發行映像。The tooling acquires the compile/publish image from Docker Hub (if not already in the cache). 映像會使用最新的標籤產生,其可推送至私人登錄或 Docker Hub。An image is produced with the latest tag, which can be pushed to the private registry or Docker Hub.

在 PMC 中執行 docker images 命令,可查看映像清單。Run the docker images command in PMC to see the list of images. 會顯示類似下列的輸出:Output similar to the following is displayed:

REPOSITORY        TAG                     IMAGE ID      CREATED             SIZE
hellodockertools  latest                  e3984a64230c  About a minute ago  258MB
hellodockertools  dev                     d72ce0f1dfe7  4 minutes ago       255MB
microsoft/dotnet  2.1-sdk                 9e243db15f91  6 days ago          1.7GB
microsoft/dotnet  2.1-aspnetcore-runtime  fcc3887985bb  6 days ago          255MB
REPOSITORY                  TAG     IMAGE ID      CREATED         SIZE
hellodockertools            latest  cd28f0d4abbd  12 seconds ago  349MB
hellodockertools            dev     5fafe5d1ad5b  23 minutes ago  347MB
microsoft/aspnetcore-build  2.0     7fed40fbb647  13 days ago     2.02GB
microsoft/aspnetcore        2.0     c69d39472da9  13 days ago     347MB

自 .NET Core 2.1 起,上述輸出中所列出的 microsoft/aspnetcore-buildmicrosoft/aspnetcore 映像,會取代為 microsoft/dotnet 映像。The microsoft/aspnetcore-build and microsoft/aspnetcore images listed in the preceding output are replaced with microsoft/dotnet images as of .NET Core 2.1. 如需詳細資訊,請參閱 Docker 存放庫移轉公告For more information, see the Docker repositories migration announcement.

注意

docker images 命令會傳回存放庫名稱和標記識別為 <無> (上面未列出) 的中繼映像。The docker images command returns intermediary images with repository names and tags identified as <none> (not listed above). 這些未命名映像是由多階段建置 Dockerfile 所產生。These unnamed images are produced by the multi-stage build Dockerfile. 它們可以改善最終映像的建置效率 — 發生變更時只會重建必要層。They improve the efficiency of building the final image—only the necessary layers are rebuilt when changes occur. 當不再需要中繼映像時,請使用 docker rmi (英文) 命令予以刪除。When the intermediary images are no longer needed, delete them using the docker rmi command.

相較於 dev 映像,生產或發行映像的大小可能需要更小。There may be an expectation for the production or release image to be smaller in size by comparison to the dev image. 基於磁碟區對應,偵錯工具和應用程式是從本機電腦執行,而不是在容器內執行。Because of the volume mapping, the debugger and app were running from the local machine and not within the container. 「最新」映像已封裝在主機上執行應用程式所需的應用程式碼。The latest image has packaged the necessary app code to run the app on a host machine. 因此,差異是應用程式碼的大小。Therefore, the delta is the size of the app code.

其他資源Additional resources