- Quickstart: Compose and ASP.NET Core with SQL Server
- Dockerize an ASP.NET Core application
- Introduction
- Why build ASP.NET Core?
- Prerequisites
- Create a Dockerfile for an ASP.NET Core application
- Method 1:
- Method 2 (build app outside Docker container):
- Yet another tutorial: запускаем dotnet core приложение в docker на Linux
Quickstart: Compose and ASP.NET Core with SQL Server
Estimated reading time: 6 minutes
This quick-start guide demonstrates how to use Docker Engine on Linux and Docker Compose to set up and run the sample ASP.NET Core application using the .NET Core SDK image with the SQL Server on Linux image. You just need to have Docker Engine and Docker Compose installed on your platform of choice: Linux, Mac or Windows.
For this sample, we create a sample .NET Core Web Application using the microsoft/dotnet:2.1-sdk Docker image. After that, we create a Dockerfile , configure this app to use our SQL Server database, and then create a docker-compose.yml that defines the behavior of all of these components.
Note: This sample is made for Docker Engine on Linux. For Windows Containers, visit Docker Labs for Windows Containers.
Create a new directory for your application.
This directory is the context of your docker-compose project. For Docker Desktop for Windows and Docker Desktop for Mac, you need to set up file sharing for the volume that you need to map.
Within your directory, use the dotnet:2.1-sdk Docker image to generate a sample web application within the container under the /app directory and into your host machine in the working directory:
Note: If running in Docker Desktop for Windows, make sure to use Powershell or specify the absolute path of your app directory.
Create a Dockerfile within your app directory and add the following content:
This file defines how to build the web app image. It uses the .NET Core SDK image, maps the volume with the generated code, restores the dependencies, builds the project and exposes port 80. After that, it calls an entrypoint script that we create in the next step.
The Dockerfile makes use of an entrypoint to your webapp Docker image. Create this script in a file called entrypoint.sh and paste the contents below.
Note: Make sure to use UNIX line delimiters. The script doesn’t work if you use Windows-based delimiters (Carriage return and line feed).
This script restores the database after it starts up, and then runs the application. This allows some time for the SQL Server database image to start up.
Create a docker-compose.yml file. Write the following in the file, and make sure to replace the password in the SA_PASSWORD environment variable under db below. This file defines the way the images interact as independent services.
Note: The SQL Server container requires a secure password to startup: Minimum length 8 characters, including uppercase and lowercase letters, base 10 digits and/or non-alphanumeric symbols.
This file defines the web and db micro-services, their relationship, the ports they are using, and their specific environment variables.
Note: You may receive an error if you choose the wrong Compose file version. Be sure to choose a version that is compatible with your system.
Go to Startup.cs and locate the function called ConfigureServices (Hint: it should be under line 42). Replace the entire function to use the following code (watch out for the brackets!).
Note: Make sure to update the Password field in the connection variable below to the one you defined in the docker-compose.yml file.
Go to app.csproj . You see a line like:
The generated project uses sqlite by default. To use SQL Server, add this line to app.csproj :
The Sqlite dependency was at version 1.1.2 at the time of this writing. Use the same version for the SQL Server dependency.
Ready! You can now run the docker-compose build command.
Make sure you allocate at least 2GB of memory to Docker Engine. Here is how to do it on Docker Desktop for Mac and Docker Desktop for Windows. This is necessary to run the SQL Server on Linux container.
Run the docker-compose up command. After a few seconds, you should be able to open localhost:8000 and see the ASP.NET core sample website. The application is listening on port 80 by default, but we mapped it to port 8000 in the docker-compose.yml .
Go ahead and try out the website! This sample uses the SQL Server database image in the back-end for authentication.
Источник
Dockerize an ASP.NET Core application
Estimated reading time: 4 minutes
Introduction
This example demonstrates how to dockerize an ASP.NET Core application.
Why build ASP.NET Core?
- Open-source
- Develop and run your ASP.NET Core apps cross-platform on Windows, MacOS, and Linux
- Great for modern cloud-based apps, such as web apps, IoT apps, and mobile backends
- ASP.NET Core apps can run on .NET Core or on the full .NET Framework
- Designed to provide an optimized development framework for apps that are deployed to the cloud or run on-premises
- Modular components with minimal overhead retain flexibility while constructing your solutions
Prerequisites
This example assumes you already have an ASP.NET Core app on your machine. If you are new to ASP.NET you can follow a simple tutorial to initialize a project or clone our ASP.NET Docker Sample.
Create a Dockerfile for an ASP.NET Core application
Method 1:
- Create a Dockerfile in your project folder.
- Add the text below to your Dockerfile for either Linux or Windows Containers. The tags below are multi-arch meaning they pull either Windows or Linux containers depending on what mode is set in Docker Desktop for Windows. Read more on switching containers.
- The Dockerfile assumes that your application is called aspnetapp . Change the Dockerfile to use the DLL file of your project.
- To make your build context as small as possible add a .dockerignore file to your project folder and copy the following into it.
Method 2 (build app outside Docker container):
- Create a Dockerfile in your project folder.
- Add the text below to your Dockerfile for either Linux or Windows Containers. The tags below are multi-arch meaning they pull either Windows or Linux containers depending on what mode is set in Docker Desktop for Windows. Read more on switching containers.
The Dockerfile assumes that your application is called aspnetapp . Change the Dockerfile to use the DLL file of your project. This method assumes that your project is already built and it copies the build artifacts from the publish folder. Refer to the Microsoft documentation on Containerize a .Net Core app.
The docker build step here will be much faster than method 1, as all the artifacts are built outside of the docker build step and the size of the base image is much smaller compared to the build base image.
This method is preferred for CI tools like Jenkins, Azure DevOps, GitLab CI, etc. as you can use the same artifacts in multiple deployment models if Docker isn’t the only deployment model being used. Additionally, you’ll be able to run unit tests and publish code coverage reports, or use custom plugins on the artifacts built by the CI.
Источник
Yet another tutorial: запускаем dotnet core приложение в docker на Linux
Предупреждение читателю: статья ориентирована на совсем новичков в docker/dotnet core и писалась большей частью, как напоминалка для себя. Вдохновлялся я первыми 3 частями Docker Get Started Guide и неким блог-постом на english. У кого хорошо с английским, можно читать сразу их и в общем-то будет сильно похоже. Если же после всего вышенаписанного вы еще не передумали продолжить чтение, то добро пожаловать под кат.
Пререквизиты
Итак нам понадобится собственно Linux (в моем случае это была Ubuntu 16.04 под VirtualBox на Windows 10), dotnet core, docker, а также docker compose, чтобы было удобнее поднимать сразу несколько контейнеров за раз.
Никаких особых проблем с установкой возникнуть не должно. По крайней мере, у меня таковых не возникло.
Формально можно писать хоть в блокноте и отлаживаться через логи или консольные сообщения, но т.к. я несколько избалован, то все-таки хотелось получить нормальную отладку и, желательно, еще и нормальный рефакторинг.
Из того, что может под Linux, для себя я попробовал Visual Studio Code и JetBrains Rider.
Visual Studio Code
Что могу сказать — оно работает. Отлаживаться можно, синтаксис подсвечивается, но уж очень все незатейлево — осталось впечатление, что это блокнот с возможностью отладки.
Rider
По сути Idea, скрещенная с решарпером — все просто и понятно, если работал до этого с любой IDE от JetBrains. До недавнего времени не работал debug под linux, но в последней EAP сборке его вернули. Вообщем для меня выбор в пользу Rider был однозначен. Спасибо JetBrains за их классные продукты.
Презреем в учебных целях кнопки Create Project различных IDE и cделаем все ручками через консоль.
1. Переходим в директорию нашего будущего проекта
2. Посмотрим ради интереса, какие шаблоны мы можем использовать
3. Создадим WebApi проект
4. Подтянем зависимости
5. Запустим наше приложение
6. Открываем http://localhost:5000/api/values и наслаждаемся работой C# кода на Linux
Готовим приложение к докеризации
Заходим в Program.cs и в настройке хоста добавляем
В итоге должно получится что-то типа
Это нужно для того, чтобы мы смогли обратится к приложению, находящемуся внутри контейнера.
По дефолту Kestrel, на котором работает наше приложение, слушает http://localhost:5000 . Проблема в том, что localhost является loopback-интерфейсом и при запуске приложения в контейнере доступен только внутри контейнера.
Соответственно, докеризовав dotnet core приложение с дефолтной настройкой прослушиваемых url можно потом довольно долго удивляться, почему проброс портов не работает, и перечитывать свой docker-файл в поисках ошибок.
Передача параметров в приложение
При запуске контейнера хотелось бы иметь возможность передавать приложению параметры.
Беглое гугление показало, что если обойтись без экзотики типа обращения изнутри контейнера к сервису конфигурации, то можно использовать передачу параметров через переменные окружения или подмену файла конфига.
Отлично, будем передавать через переменные окружения.
Идем в Startup.cs publicpublic Startup(IHostingEnvironment env) и смотрим, что у нашего ConfigurationBuilder вызван метод AddEnvironmentVariables() .
Собственно все — теперь можно инжектить параметры из переменных окружения куда угодно через DI.
При старте инстанса приложения будем генерировать новый Guid и засунем его в IoC-контейнер, чтобы раздавать страждущим. Нужно это, например, для анализа логов от нескольких параллельно работающих инстансов сервиса.
Все тоже достаточно тривильно — у ConfigurationBuilder вызываем:
После этих двух шагов public Startup(IHostingEnvironment env) будет выглядеть примерно так:
Он не показался мне хоть сколько-нибудь интуитивным. Глубоко я не копал, но тем не менее приведу ниже небольшой пример того, как прокинуть Id инстанса, который мы задаем при старте, и что-нибудь из переменных окружения(например переменную MyTestParam) в контроллер.
Первым делом надо создать класс настроек — имена полей должны совпадать с именами параметров конфигурации, которые мы хотим инжектить.
Далее идем в Startup.cs и вносим изменения в ConfigureServices(IServiceCollection services)
И последним шагом идем в наш подопытный и единственный созданный автоматом ValuesController и пишем инжекцию через конструктор
не забывая добавить using Microsoft.Extensions.Options; . Для теста переопределяем ответ любого понравившегося Get метода, чтобы он возвращал обретенные контроллером параметры, запускаем, проверяем → профит.
Собираем и запускаем docker-образ
1. Первым делом получим бинарники нашего приложения для публикации. Для этого открываем терминал, переходим в директорию проекта и вызываем:
Более подробно про команду можно почитать тут.
Запуск этой команды без доп. аргументов из директории проекта сложит dll-ки для публикации в ./bin/Debug/[framework]/publish
2. Собственно эту папочку мы и положим в наш docker-образ.
Для этого создадим в директории проекта Dockerfile и напишем туда примерно следующее:
3. После того, как Dockerfile написан, запускаем:
Где my-cool-service — имя образа, а 1.0 — тэг с указанием версии нашего приложения
4. Теперь проверим, что образ нашего сервиса попал в репозиторий:
5. И, наконец, запустим наш образ:
6. Открываем http://localhost:5000/api/values и наслаждаемся работой C# кода на Linux в docker
Посмотреть образы в локальном репозитории
Посмотреть запущенные контейнеры
Получить информацию о контейнере
Удалить все контейнеры и все образы
Немного docker-compose напоследок
docker-compose удобен для запуска групп связанных контейнеров. Как пример, приведу разработку нового микросервиса: пусть мы пишем сервис3, который хочет общаться с уже написанными и докеризованными сервисом1 и сервисом2. Сервис1 и сервис2 для целей разработки удобно и быстро поднять из репозитория через docker-compose .
Напишем простенький docker-compose.yml , который будет поднимать контейнер нашего приложения и контейнер с nginx (не знаю, зачем он мог понадобиться нам локально при разработке, но для примера сойдет) и настраивать последний, как reverse proxy для нашего приложения.
docker-compose поднимает при старте между сервисами, описанными в docker-compose файле, локальную сеть и раздает hostname в соотвествии с названиями сервисов. Это позволяет таким сервисам удобно между собой общаться. Воспользуемся этим свойством и напишем простенький файл конфигурации для nginx
из директории с docker-compose.yml и получаем nginx, как reverse proxy для нашего приложения. При этом рекомендуется представить, что тут вместо nginx что-то действительно вам полезное и нужное. Например база данных при запуске тестов.
Мы создали dotnet core приложение на Linux, научились собирать и запускать для него docker-образ, а также немного познакомились с docker-compose .
Надеюсь, что кому-нибудь эта статья поможет сэкономить немного времени на пути освоения docker и/или dotnet core.
Просьба к читателям: если вдруг среди вас у кого-нибудь есть опыт с dotnet core в продакшене на Linux (не обязательно в docker, хотя в docker особенно интересно) — поделитесь, пожалуйста, впечатлениями от использования в комментариях. Особенно будет интересно услышать про реальные проблемы и то, как их решали.
Источник