The post has been translated automatically. Original language: Russian
The size and structure of a Docker image affect build and deployment speed, storage costs and security. A few simple techniques can shrink a .NET application's image several times over and speed up CI.
Multi-stage builds
- In the first stage, use the sdk image for restore, build and publish.
- In the final stage, take only the aspnet or runtime image and copy the publish output into it.
- This keeps the SDK, source code and intermediate files out of the final image.
Layer caching
- First copy only the project files (.csproj) and run dotnet restore.
- Then copy the rest of the code and build.
- As long as dependencies don't change, the restore layer comes from cache and builds run noticeably faster.
Image size
- Try lightweight base images: Alpine or Microsoft's chiseled Ubuntu images.
- Add a .dockerignore so you don't copy bin, obj, .git and local settings.
- For the most demanding scenarios, consider trimming and single-file publishing.
Security
- Don't run the application as root — modern .NET images include a ready-made app user for this.
- Don't store secrets in the image: pass them via environment variables or a secrets store.
- Rebuild images regularly to get base layer updates, and scan them for vulnerabilities.
- Pin specific base image versions instead of the latest tag.
A good Dockerfile takes a few minutes of work and saves hours in CI while reducing risk. Which techniques do you use?
Размер и устройство Docker-образа влияют на скорость сборки и деплоя, расходы на хранение и безопасность. Несколько простых приёмов позволяют уменьшить образ .NET-приложения в разы и ускорить CI.
Многоэтапная сборка
- На первом этапе используйте образ sdk для restore, build и publish.
- На финальном этапе берите только образ aspnet или runtime и копируйте в него результат publish.
- Так в итоговый образ не попадают SDK, исходники и промежуточные файлы.
Кэширование слоёв
- Сначала копируйте только файлы проектов (.csproj) и выполняйте dotnet restore.
- Затем копируйте остальной код и собирайте.
- Пока зависимости не меняются, слой с restore берётся из кэша, и сборка идёт заметно быстрее.
Размер образа
- Попробуйте облегчённые базовые образы: Alpine или chiseled-образы Ubuntu от Microsoft.
- Добавьте .dockerignore, чтобы не копировать bin, obj, .git и локальные настройки.
- Для самых требовательных сценариев рассмотрите trimming и сборку в один файл.
Безопасность
- Запускайте приложение не от root — в современных образах .NET для этого есть готовый пользователь app.
- Не храните секреты в образе: передавайте их через переменные окружения или хранилище секретов.
- Регулярно пересобирайте образы, чтобы получать обновления базового слоя, и сканируйте их на уязвимости.
- Фиксируйте конкретные версии базовых образов, а не тег latest.
Хороший Dockerfile — это несколько минут работы, которые экономят часы в CI и снижают риски. Какие приёмы используете вы?
Comments 0
Newest Popular