- Использование средств Visual Studio для контейнеров с ASP.NET Core Visual Studio Container Tools with ASP.NET Core
- Предварительные требования Prerequisites
- Установка и настройка Installation and setup
- Добавление проекта в контейнер Docker Add a project to a Docker container
- Новое приложение New app
- Существующее приложение Existing app
- Общие сведения о Dockerfile Dockerfile overview
- Добавление поддержки оркестратора контейнеров в приложение Add container orchestrator support to an app
- Docker Compose Docker Compose
- Service Fabric. Service Fabric
- Отладка Debug
- Изменение и продолжение Edit and continue
- Публикация образов Docker Publish Docker images
Использование средств Visual Studio для контейнеров с ASP.NET Core Visual Studio Container Tools with ASP.NET Core
Visual Studio 2017 и более поздних версий поддерживает сборку, отладку и запуск контейнерных приложений ASP.NET Core для работы с .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.
Предварительные требования Prerequisites
- Docker для Windows Docker for Windows
- Visual Studio 2019 с рабочей нагрузкой Кроссплатформенная разработка .NET CoreVisual Studio 2019 with the .NET Core cross-platform development workload
Установка и настройка Installation and setup
Нужно настроить Общие диски в Docker для Windows, чтобы обеспечить поддержку сопоставления тома и отладки. 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.
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 в области уведомлений и выберите Переключение на контейнеры Windows или Переключение на контейнеры 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 установите флажок Включение поддержки Docker: When creating a new app with the ASP.NET Core Web Application project templates, select the Enable Docker Support check box:
Если целевой платформой является .NET Core, в раскрывающемся списке ОС можно выбрать тип контейнера. If the target framework is .NET Core, the OS drop-down allows for the selection of a container type.
Существующее приложение Existing app
Для проектов ASP.NET Core, ориентированных на .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 для контейнеров не поддерживают добавление Docker в существующий проект ASP.NET Core, предназначенный для .NET Framework. The Visual Studio Container Tools 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:
Предыдущий Dockerfile основан на образе microsoft/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. Пакеты скомпилированы JIT-компилятором для повышения производительности запуска. The packages are just-in-time (JIT) compiled to improve startup performance.
Если в диалоговом окне создания проекта установлен флажок Configure for HTTPS (Настроить для трафика 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.
Предыдущий Dockerfile основан на образе microsoft/aspnetcore. The preceding Dockerfile is based on the microsoft/aspnetcore image. Этот базовый образ включает пакеты NuGet платформы ASP.NET Core, которые скомпилированы 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 Compose необходимо последовательно выбрать Добавить > Поддержка Docker. 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. Доступны следующие варианты: The following choices are available:
Docker Compose Docker Compose
Средства Visual Studio для контейнеров добавляют в решение проект docker-compose со следующими файлами: The Visual Studio Container Tools add a docker-compose project to the solution with the following files:
- docker-compose.dcproj. Файл, представляющий проект. docker-compose.dcproj: The file representing the project. Включает в себя элемент , указывающий используемую ОС. Includes a 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 build и docker-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:
В предыдущем примере 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 (например, 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.yml и docker-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.
Чтобы в Docker Compose отображался параметр для запуска в Visual Studio, проект Docker должен быть запускаемым. For Docker Compose to display an option to run in Visual Studio, the docker project must be the startup project.
Service Fabric. Service Fabric
Помимо базовых Предварительных требований для решения по оркестрации Service Fabric необходимо выполнить следующие предварительные условия: In addition to the base Prerequisites, the Service Fabric orchestration solution demands the following prerequisites:
- Пакет SDK для Microsoft Azure Service Fabric версии 2.6 или более поздней версии Microsoft Azure Service Fabric SDK version 2.6 or later
- Рабочая нагрузка Разработки Azure в Visual Studio Visual Studio’s Azure Development workload
Service Fabric не поддерживает запуск контейнеров Linux в кластере локальной разработки в Windows. 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 для контейнеров позволяют выполнять следующие задачи: The Visual Studio Container Tools do the following tasks:
добавление проекта Service Fabric Application приложение в решение; Adds a
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. Если Dockerfile уже существует в проекте ASP.NET Core, он переименовывается в Dockerfile.original. If a Dockerfile already exists in the ASP.NET Core project, it’s renamed to Dockerfile.original. Создается новый Dockerfile, аналогичный следующему: A new Dockerfile, similar to the following, is created:
добавляет элемент в файл .csproj проекта ASP.NET Core; Adds an element to the ASP.NET Core project’s .csproj file:
добавляет папку 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.
Отладка 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:
- Получение тега 2.1-aspnetcore-runtime образа среды выполнения microsoft/dotnet (если его еще нет в кэше). 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 значения Development внутри контейнера. The 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. Отправка запроса к порту, назначенному localhost, с помощью команды docker ps . 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 приложения помечается как dev. The resulting Docker image of the app is tagged as dev. Образ основан на теге 2.1-aspnetcore-runtime базового образа microsoft/dotnet. The image is based on the 2.1-aspnetcore-runtime tag of the microsoft/dotnet base image. Выполните команду docker images в окне Консоль диспетчера пакетов (PMC). Run the docker images command in the Package Manager Console (PMC) window. На компьютере отобразятся следующие образы: The images on the machine are displayed:
- Получение образа среды выполнения microsoft/aspnetcore (если его еще нет в кэше). The microsoft/aspnetcore runtime image is acquired (if not already in the cache).
- Задание для переменной среды ASPNETCORE_ENVIRONMENT значения Development внутри контейнера. The ASPNETCORE_ENVIRONMENT environment variable is set to Development within the container.
- Порт 80 открыт и сопоставлен с динамически назначаемым портом для localhost. 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 приложения помечается как dev. The resulting Docker image of the app is tagged as dev. Образ основан на базовом образе microsoft/aspnetcore. The image is based on the microsoft/aspnetcore base image. Выполните команду docker images в окне Консоль диспетчера пакетов (PMC). Run the docker images command in the Package Manager Console (PMC) window. На компьютере отобразятся следующие образы: The images on the machine are displayed:
В образе 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.
Выполните команду docker ps в PMC. Run the docker ps command in PMC. Обратите внимание, что приложение выполняется с помощью контейнера: Notice the app is running using the container:
Изменение и продолжение 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. Выполните команду docker ps в PMC. Run the docker ps command in PMC. Обратите внимание, что исходный контейнер все еще выполняется, как и 10 минут назад: Notice the original container is still running as of 10 minutes ago:
Публикация образов Docker Publish Docker images
После завершения цикла разработки и отладки приложения используйте Средства Visual Studio для контейнеров, чтобы создать рабочий образ приложения. Once the develop and debug cycle of the app is completed, the Visual Studio Container Tools assist in creating the production image of the app. Выберите в раскрывающемся списке конфигурации значение Выпуск и выполните сборку приложения. Change the configuration drop-down to Release and build the app. Инструментарий получает образ компиляции или публикации из центра Docker (если он отсутствует в кэше). The tooling acquires the compile/publish image from Docker Hub (if not already in the cache). Образ создается с тегом latest, который можно отправить в закрытый реестр или в центр Docker. 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:
Начиная с .NET Core 2.1, образы microsoft/aspnetcore-build и microsoft/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 (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. Образ с тегом latest упаковал код приложения, необходимый для запуска приложения на хост-компьютере. 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.