docker dev environment что это

Development Environments Preview

Estimated reading time: 13 minutes

Dev Environments enable you to collaborate easily by allowing you to share work-in-progress code with your team members. When using Dev Environments, you can easily set up repeatable development environments, keeping the environment details versioned along with your code. You can also share your work-in-progress code with your team members in just one click and without having to deal with any merge conflicts while moving between Git branches to get your code on to their machine.

Dev Environments also allow you to switch between your developer environments or your team members’ environments, move between branches to look at changes that are in progress, without moving off your current Git branch.

The Dev Environments feature is currently offered as a Preview. We recommend that you do not use this in production environments.

To access Dev Environments, from the Docker menu, select Dashboard > Dev Environments.

Prerequisites

Dev Environments are available as part of Docker Desktop 3.5.0 release. Download and install Docker Desktop 3.5.0 or higher:

To get started with Dev Environments, you must have the following tools and extension installed on your machine:

Click Install to download and install any missing tools.

Add Git to your PATH on Windows

If you have already installed Git, and it’s not detected properly, run the following command to check whether you can use Git with the CLI or PowerShell:

If it doesn’t detect Git as a valid command, you must reinstall Git and ensure you choose the option Git from the command line. or the Use Git and optional Unix tools. on the Adjusting your PATH environment step.

After you have installed Git, you must quit and then start Docker Desktop. From the Docker menu, select Quit Docker Desktop, and then start it again.

Start a single container Dev Environment

The simplest way to get started with Dev Environments is to create a new environment by cloning the Git repository of the project you are working on. For example, let us create a new Dev Environment using a simple single-dev-env project from the Docker Samples GitHub repository.

When cloning a Git repository using SSH, ensure you’ve added your SSH key to the ssh-agent. To do this, open a terminal and run ssh-add

If you have enabled the WSL 2 integration in Docker Desktop for Windows, make sure you have an SSH agent running in your WSL 2 distribution.

Now, click Create.

This clones the Git code inside a volume, determines the best image for your Dev Environment, and finally, opens VS Code inside the Dev Environment container.

In the above example, the names wizardly_ellis and relaxed_maclaren are randomly generated. You’ll most likely see different names when you create your Dev Environment.

Hover over the container and click Open in VS Code to start working in VS Code as usual. You can also open a terminal in VS Code, and use Git to push or pull code to your repository, or switch between branches and work as you would normally.

You can launch the application by running the command make run in your VS Code terminal. This opens an http server on port 8080. Open http://localhost:8080 in your browser to see the running application.

Create a Dev Environment from a specific branch or tag

You can create a dev environment from a specific branch (for example, a branch corresponding to a Pull Request) or a tag by adding @mybranch or @tag as a suffix to your Git URL:

Docker then clones the repository with your specified branch or tag.

Recap

Let’s summarize the tasks we performed so far to start a single container Dev Environment.

Share your Dev Environment

Docker Pro, Team, and Business users can now share Dev Environments with their team members.

When you are ready to share your environment, just click the Share button and specify the Docker Hub namespace where you’d like to push your Dev Environment to.

This creates a Docker image of your dev environment, uploads it to the Docker Hub namespace you have specified in the previous step, and provides a tiny URL which you can use to share your work with your team members.

Your team members need to open the Create dialog, select the Existing Dev Environment tab, and then paste the URL. Your Dev Environment now starts in the exact same state as you shared it.

Using this shared Dev Environment, your team members can access the code, any dependencies, and the current Git branch you are working on. They can also review your changes and provide feedback even before you create a pull request!

Start a sample Compose Dev Environment

You can also use Dev Environments to collaborate on any Docker Compose-based projects. For example, let’s use the compose-dev-env project from the Docker Samples GitHub repository.

When cloning a Git repository using SSH, ensure you’ve added your SSH key to the ssh-agent. To do this, open a terminal and run ssh-add

Click Create. This initializes the project and clones the Git code and builds the Compose application. This:

Now your application is up and running, you can check by opening http://localhost:8080 in your browser.

The time taken to start the Compose application depends on how your application is configured, whether the images have been built, and the number of services you have defined, etc.

You’ll also notice that VS Code doesn’t open directly (unlike the single container Dev Environment) as there are multiple services configured. You can hover over a service and then click on the Open in VS Code button to open a specific service in Visual Studio Code. This stops the existing container and creates a new container which allows you to develop and update your service in VS Code.

Читайте также:  Что значит терпкий вкус вина

You can now update your service and test it against your Compose application.

Set up your own Compose Dev Environment

In the previous section, we’ve learnt how to start a sample Compose Dev Environment. To set up a Dev Environment for your own Compose-based project, you’ll need some extra configuration that tells Docker Desktop how to build, start, and use the right Dev Environment image for your services.

Let’s take a detailed look at the docker-compose.yaml file we used in the compose-dev-env sample project.

In the above yaml file, the build context backend specifies that that the container should be built using the development stage ( target attribute) of the Dockerfile located in the backend directory ( context attribute)

The development stage of the Dockerfile is defined as follows:

The development target uses a golang:1.16-alpine image with all dependencies you need for development. You can start your project directly from VS Code and interact with the others applications or services such as the database or the frontend.

In our example, the Docker Compose files are the same. However, they could be different and the services defined in the main Compose file may use other targets to build or directly reference other images.

Specify a base image

This configuration is to unblock users for the Preview release only. We may move this configuration for single and multi-container applications to a Compose-based implementation in future releases.

To get involved with the discussion on how we are going to implement this as part of Compose, join the #docker-dev-environments channel in the Docker Community Slack, or let us know your feedback by creating an issue in the Dev Environments GitHub repository.

Start a Dev Environment from a local folder

You can also start a Dev Environment from local code on your machine.

Now, click Create.

This creates a Dev Environment using your local folder, and bind-mounts your local code in the Dev Environment. Finally, it opens VS Code inside the Dev Environment container.

When using a local folder for a Dev Environment, file changes are synchronized between your Dev Environment container and your local files. This can affect the performance inside the container, depending on the number of files in your local folder and the operations performed in the container.

Known issues

The following section lists known issues and workarounds in the Dev Environments Preview:

Feedback

We are excited that you are trying out our Dev Environments Preview. We would love to hear from you.

You can let us know your feedback by creating an issue in the Dev Environments GitHub repository. Alternatively, get in touch with us on the #docker-dev-environments channel in the Docker Community Slack.

Источник

Полная автоматизация «development» среды с помощью docker-compose

В этой статье мы поделимся опытом автоматизации запуска, тестирования и конфигурации больших проектов с использованием docker-compose. Несколько простых изменений могут помочь Вашей команде быть более эффективной и тратить время на важные, а не на рутинные задачи.

Docker в 2017

На конференции Dockercon 2016 CEO компании Docker рассказал, что количество приложений, которые запускаются в Docker выросло на 3100% за последние два года. Боле 460 тысяч приложений по всему миру запускаются в Docker. Это невероятно!

Если вы все еще не используете Docker, я бы посоветовал почитать отличную статью об использовании Docker во всем мире. Docker полностью изменил то, как мы пишем приложения и стал неотъемлемой частью для разработчиков и DevOps команд. В этой статье мы полагаем, что вы уже знакомы с Docker и хотим дать вам еще одну серьезную причину продолжать использовать его.

Что не так?

С начала моей карьеры, когда я занимался разработкой веб-приложений, запуск приложения в рабочем окружении всегда был непростой задачей. Приходилось делать много дополнительной работы от установки базы данных до конфигурации приложения, чтобы просто его запусить. Разработчики любят не любят писать документацию, и шаги для запуска проекта обычно спрятаны в головах членов команды. В итоге, запуск проекта становится болезненной задачей, особенно для новых ребят.

Многие проекты просты в начале, но становятся больше со временем. Это приводит к увеличению внешних зависимостей, таких как базы данных, очереди. В связи с ростом популярности микросервисов, многие проекты перестают быть монолитными и разделяются на несколько небольших частей. Любое такое изменение требует внимания всей команды, так как после таких изменений, проект нужно запускать по-другому. Обычно, разработчики, занимающиеся корневыми изменениями, пишут письмо, либо создают вики страничку с описанием шагов, которые нужно сделать, чтобы проект снова запустился на рабочих окружениях. Обычно это работает, но не всегда 🙂 Однажды наша команда попала в ситуацию, когда разработчик с другого континента сделал много изменений в проекте, написал длинное письмо и ушел спать. Я полагаю, Вы знаете, что было дальше. Все верно, он забыл упомянуть несколько важных моментов. В результате, на следующий день часть команды просто не смогла запустить проект и день был потерян.

Как инженеру, мне нравится автоматизировать все вокруг. Я верю, что запуск, тестирование и развертывание всегда должны быть одношаговыми. В этом случае, команда сможет сфокусироваться на важных задачах: разработке и улучшении продукта. Это было сложнее сделать 10 лет назад, но сейчас автоматизировать стало гораздо проще и, как мне кажется, каждая команда должна уделять этому время. Чем раньше — тем лучше.

Быстрый старт с docker-compose

Docker-compose это простой инструмент, который позволяет настроить и запустить несколько контейнеров одной командой. До того, как мы нырнем глубже в docker-compose, нужно немного остановиться на структуре проекта. Мы используем «monorepo». Код каждого сервиса (frontend, api, worker, etc) находится в своей директории и имеет Dockerfile. Пример структуры проекта можно посмотреть здесь.

Читайте также:  что делать если желтеет пихта

Чтобы запустить проект, нам понадобиться одна команда:

При первом старте, все контейнеры будут построены или скачаны. Если вы работали с Docker, конфигурационный файл для docker-compose должен быть более-менее понятен, но стоит обратить внимание на несколько деталей:

Совет: Вы можете обернуть команду запуска проект в простой баш скрипт:

Частичный запуск

В этом примере docker-compose.yml некоторые сервисы зависят друг от друга:

В больших проектах всегда есть части, которые нужны лишь время от времени. Различные члены команды могут работать над различными частями приложения. Фронтенд разработчику, который работает над landing сайтом, нет нужды запускать проект целиком. Он может просто запустить только те части, которые ему действительно нужны.

>/dev/null назойливые логи

Часто мы используем инструменты, которые генерируют много логов, тем самым отвлекая нас от полезных логов нашего приложения. Чтобы отключить логи для конкретного сервиса, нужно просто установить logging driver в none.

Несколько файлов docker-compose

Так почему же вам может понадобиться несколько конфигурационных файлов? Первый вариант использования — это разбиение большого проекта на несколько более мелких. Интересно, что даже если вы запускаете несколько отдельных docker-compose, сервисы все равно смогут общаться друг с другом по имени из docker-compose. Например, вы можете разделить инфраструктурные контэйнеры (базы данных, очереди и т.д.) и контейнеры приложения в отдельные docker-compose файлы.

Запуск тестов

Наши тесты включают в себя различные типы: юнит, интеграционные, UI тестирование, проверку синтаксиса кода. У каждого сервиса свой набор тестов. Интеграционные и UI тесты требуют api и web frontend для их работы.

В самом начале нам показалось, что мы должны запускать тесты при каждом запуске docker-compose. Но очень скоро мы поняли, что это не всегда удобно и занимает слишком много времени. В каких-то случаях нам также хотелось иметь немного больше контроля над тем, какие тесты запускать. Для этого мы используем отдельный конфигурационный docker-compose файл:

Для запуска тестов необходимо, чтобы основной docker-compose был запущен. Интеграционные тесты используют рабочую версию api сервиса, а UI тесты используют web frontend сервиса. По сути тесты просто используют образы, которые собраны в основном docker-compose. Также возможен запуск тестов только для конкретного сервиса, например:

Данная команда запустит только тесты для api сервиса.

Префикс для контейнеров

Таким образом, префикс будет одинаковым во всех рабочих окружениях.

Заключение

Docker-compose это очень полезный и гибкий способ автоматизации запуска проектов.

Когда новые разработчики добавляются к нам в команду, мы даем им небольшую задачу, которую они должны закончить к концу первого рабочего дня. Каждый, кто присоединялся к нашей команде, справился с этим и был самым счастливым человеком на Земле. Уже с первых минут новые разработчики могут сфокусироваться на важных задачах и не тратить времени на то, чтобы запустить проект. Наша документация для старта проекта состоит из трех пунктов:

Для того, чтобы Вам было проще понять эту статью, у нас есть пример проекта на Github. Делитесь вашим опытом и задавайте вопросы.

Надеемся, что статья была полезной и поможет сделать Ваш проект лучше 🙂

Версию на английском, можно почитать здесь.

Источник

FrontEnd разработка в Docker

Легенда

Данная статья сделана для FrontEnd разработчиков, которые не знакомы с Docker. Мы разберем некоторые вопросы связанные с оптимизацией трафика для запуска и затронем немного вопросы безопасности.

Научимся работать с Docker для локальной разработки

Создадим артефакт для production, который в будущем сможет использовать DevOps.

В конце немного поговорим о безопасности

Установка Docker

Установка докер довольна простая и лучше всего описана в официальной документации.

Также нам для работы понадобится docker-compose, например для MacOS при установке Docker Desktop он также автоматом установится, в linux системах же его придется ставить отдельно.

Справка по CLI Docker

Особенности проекта в статье

Пусть наш FE проект имеет 2 скрипта в package.json: «dev» для разработки и «build» для создания production кода.

В статье мы рассмотрим версию где результатом сборки являются статические файлы. Для node сервера все будет немного сложнее, но не сильно.

TL;DR; Сразу код

Давайте разбираться, что произошло:

Этап разработки:

1 шаг. Объявляем сервис ‘web’. Выбираем образ который будет делать сборку: node:15.8-alpine3.11 Лучше всего детализировать используемые версии, стоит их держать точно такими же, как и у сборщика production build.

2 шаг. Выбираем порты, которые будут в нашей хост системе отражать порты из запущенного контейнера.

3 шаг. Монтируем все из текущей директории в контейнер. Это нужно, чтобы локальные изменения сразу вызывали rebuild, однако это порождает некоторые проблемы с безопасностью — разберем их в конце статьи.

4 шаг. ‘environment’ позволяет задать переменные окружения, которые интересны в твоем конкретном случае.

5 шаг. ‘working_dir’ определяет рабочую директорию внутри контейнера, относительно которой будут исполнены последующие команды.

Этап production:

Хочу особо отметить, что приведенная конфигурация работает для отдачи простой статики. Если используется SSR, нужно будет внести изменения: поднимать сервер на node и т.д.

Что отличается в конфигурации docker-compose.yml от develop версии?

Нет секции command потому что статика будет раздаваться с помощью nginx

Конфигурация nginx максимально простая и не обременяет процесс раздачи файлов и fallback на /index.html в случае, если пытаются получить какой-то файл, которого нет.

Самое интересное кроется в Dockerfile : multi-stage building, который используется для уменьшения результирующего артефакта.

Dockerfile

Первая стадия — это сборка

1 строка. Для этого указываем тот же исходный образ, который использовали для develop FROM node:15.8-alpine3.11 AS build

Важно! Даем стадии имя build, чтобы в следующих стадиях именовать ее по имени, а не по индексу, который может измениться, если включим дополнительные стадии.

2 строка. Указываем рабочую директорию /app

3-5 строки. Здесь останавливаемся подробнее:

Вопрос: почему сначала копируем только package.json и производим установку?
Ответ (не заставляет себя долго ждать): при первом запуске разница не будет заметна, но уже со следующей попытки сборки разница будет очевидна.

Если не было изменений в “package.json”, то слои, по которым собирается docker не изменятся, и данные шаги будут просто взяты из кэша. Это многократно ускорит процесс и снизит сетевую нагрузку в разы. Нам как раз это и надо.

Читайте также:  приставки пре при в каком классе изучают

6 строка. Копируем оставшиеся файлы и запускаем build.

Вторая стадия — формирование артефакта

По своей сути артефакт в нашем случае — это контейнер nginx со статикой.

8 строка. Указываем образ nginx который возьмем за основу.

9 строка. Копируем файлы из первой стадии в папку из которой будем раздавать статику.

10 строка. Копируем в артефакт файл конфигурации nginx

Запускать артефакт можно например так: docker-compose up

Немного о проблеме безопасности для development

Не стоит использовать volumes с директориями на компьютере, которые не хотим отдать в доступ всем пользователям docker.

Как это проявляется? Давайте рассмотрим на примере:

Создаем обычную папку

Под пользователем создаем docker-compose.yml и подключаем директорию, к которой не имеет доступ другой пользователь.

Строка 7. Контейнер будет жить 1 час.

Заходим в систему под другим пользователем, который имеет доступ к docker.

Смотрим имя контейнера: docker ps

Теперь можно спокойно зайти в папку: cd /app

В которой лежит секретный файл sectret.txt
Файл можно просматривать и редактировать его содержимое.

Итоги

Несомненно, тема контейнеризация очень обширная и мы рассмотрели только крошечную часть, однако мы рассмотрели необходимую базу для старта. Я буду рад, если эта статья станет отправной точкой для FE-разработки в Docker.

Источник

Tech Preview: Docker Dev Environments

A couple of weeks ago at DockerCon we showed off a new feature that we are building – Docker Dev Environments. Today we are excited to announce the release of the Technical Preview of Dev Environment as part of Docker Desktop 3.5.

At Docker we have been looking at how teams collaborate on projects using Git. We know that Git is a powerful tool for version control of source code, but it doesn’t solve a lot of the challenges that exist when developers try to collaborate. Developers still suffer with ‘it works on my machine’ when they are trying to work together on changes as dependencies can differ. Developers may also need to move between Git branches to achieve this and often don’t bother, simply looking at code in the browser rather than running it. This means they lack the context and the tools needed to really validate that the code is good and that this collaboration is all happening right at the end of the creation process.

To address this, we are excited to release our preview of Dev Environments. With Dev Environments developers can now easily set up repeatable and reproducible development environments by keeping the environment details versioned in their SCM along with their code. Once a developer is working in a Development Environment, they can share their work-in-progress code and dependencies in one click via the Docker Hub. They can then switch between their developer environments or their teammates’ environments, moving between branches to look at work-in-progress changes without moving off their current Git branch. This makes reviewing PRs as simple as opening a new environment. Dev Environments use tools built into code editors that allow Docker to access code mounted into a container rather than on the developer’s local host. This isolates the tools, files and running services on the developer’s machine allowing multiple versions of them to exist side by side, also improving file system performance! And we have built this experience on top of Compose rather than adding another manifest for developers to worry about or look after.

There are some areas of the first release that we are going to be improving in the coming weeks as we build the experience out to make it even easier to use.

When it comes to working with your team, we will be improving this to make it easier to send someone your work-in-progress changes. Rather than having to create a unique name for your changes each time, we will let you instead share this with one click – keeping everything synced automatically via Docker Hub for your team. This means your team can see your shared Dev Environment in their UI as soon as you share it. They will also be able to swap out the existing services in their Compose stacks for the one you have shared, moving seamlessly between them.

We know that developers love Compose and that we can leverage compose features to make it easier to set up your Dev Environments(things like profiles, setting a gopath, defining debug ports, supporting mounts etc). We will be extending what we have in Compose over the coming weeks, if there are particular features you think we should support please let us know!

We will also be looking at other areas of the experience like support for other IDEs, new creation flows and better ways to set up new Dev Environments.

Lastly we will be looking at all the feedback you as a community give us on other areas we need to improve! If you have feedback on these items or have other areas you think we should be focusing on ready for our GA release, please let us know as part of our feedback repo.

We are really excited about the preview of Dev Environments! If you want to check them out simply download or upgrade Docker Desktop 3.5 and check out the new preview tab. To get started sharing Dev Environments with your team and moving your feedback process back into development rather than at the time of review, upgrade to one of Docker’s team plans today.

Источник

Сказочный портал