Docker compose запуск windows

Docker-compose — это утилита, позволяющая запускать одновременно несколько контейнеров, используя при этом единый файл конфигурации всего стека сервисов, нужных вашему приложению. Например, такая ситуация: запускаем node.js webapp, которому нужна для работы mongodb, compose выполнит build вашего контейнера с webapp (традиционный Dockerfile) и перед его запуском запустит контейнер с mongodb внутри; так же может выполнить линк их между собой. Что крайне удобно как в разработке, так и в CI самого приложения. Так сложилось, что Windows пользователи были обделены возможностью использовать столько удобное средство, ввиду того, что официальной поддержки данной ОС все еще нет. А python версия для *nix не работает в окружении windows cmd, ввиду ограничений консоли Windows.

Для того, чтобы запустить docker-compose, мы можем использовать консольную оболочку Babun. Это, так сказать, «прокаченный» форк cygwin.

Итак, рецепт запуска docker-compose в Windows из консоли babun такой:

1. Скачиваем(~280MB!) и устанавливаем сам babun, узнать больше об этой оболочке можно на ее домашней странице babun.github.io;
2. Распаковываем архив (после установки полученную папку можно удалять);
3. Запускаем файл install.bat и ждем, пока пройдет установка;
4. После в открывшемся окне babun введем команду:

babun update

И убедимся, что у нас самая последняя версия оболочки (далее все команды выполняются только внутри оболочки babun);
5. Если вам не нравится дефолтный shell babun (используется zsh), его можно изменить на bash. Для этого вводим:

babun shell /bin/bash 

6. Теперь нам нужно установить те самые зависимости Python, которых так не хватает docker-compose. Для этого выполним следующие команды по очереди:

pact install python-setuptools 

pact install libxml2-devel libxslt-devel libyaml-devel

curl -skS https://bootstrap.pypa.io/get-pip.py | python

pip install virtualenv

curl -skS https://raw.githubusercontent.com/mitsuhiko/pipsi/master/get-pipsi.py | python

7. Теперь мы готовы установить сам docker-compose:

pip install -U docker-compose

Если все прошло успешно, увидим:

{ ~ }  » docker-compose --version                                                            
docker-compose 1.2.0

Если же вы получили ошибку, error python fcntl или сообщение о не найдом файле docker-compose, попробуйте найти файл docker-compose в папках /usr/local/bin, /usr/sbin и подобных, затем можно сделать симлинк на /bin/. либо добавить в системный PATH недостающий путь.

Для правильной работы docker-compose нужно иметь уже настроенное окружение консоли для работы с docker-machine или boot2docker, а так же сам клиент docker должен быть доступен в системном PATH. О том, что такое docker, docker-machine и как с ними работать отлично рассказывает официальная документация.

Для входа в окружение нашего хоста докера, запущенного в docker-machine, нужно выполнить:

eval "$(docker-machine env ИМЯ_МАШИНЫ)"

Либо тоже самое для boot2docker:

eval "$(boot2docker shellinit)"

Проверить правильность работы клиента docker можно так:

docker ps

Если получаем список контейнеров или просто заголовки таблицы, значит, все ок!

docker ps
CONTAINER ID        IMAGE                         COMMAND                CREATED             STATUS              PORTS                                          NAMES

Для запуска стека приложения переходим в каталог нашего приложения, где у нас уже должен быть заготовлен файл docker-compose.yml или fig.yml. Синтаксис yml файла описан тут.

Далее для запуска вводим команду:

docker-compose up

Если нужно запустить в фоне, добавляем -d. Compose построит нужный образ и запустит его согласно вашему файлу docker-compose.yml.

На этом все.

Спасибо за внимание, надеюсь было полезно.

p.s. Я умышлено не стал говорить о варианте запуска compose как контейнера, т.к. считаю его неудобным.

Last Updated :
24 May, 2024

Docker is a powerful Container platform that allows you to create containers where you can run, deploy, and develop applications without worrying about different dependencies, services, and limitations of the operating system. The best part is the isolation of the container so you can use this container on different platforms. Now let’s talk about the ecosystem of Docker.

  1. Docker Engine: It is the core part of Docker which handles the different functionalities of Docker.
  2. Docker Compose: It is a tool which is provided by Docker used to maintain multi-container-based applications.
  3. Docker Hub: it is a cloud platform where all the Docker images are stored similar to Git Hub.

What Is Docker Compose?

Docker Compose is a multi-container-based application tool that will allow you to contain all the configurations and requirements for docker image building in a single YAML file. It is the single place where you can see what kind of services are required for the particular image and then you can manage and execute the configurations with commands. These are the basic details mentioned in the Docker-Compose file.

  • Services and Dependencies
  • Docker Networking
  • Docker Port-mapping
  • Docker Volumes
  • Docker Environment Variables etc…

How To Install Docker Desktop On Windows

Step 1: Download The Docker Desktop For Windows

  • Go to official website of Docker and search Docker Desktop Download.
  • Click on the «Docker Desktop For Windows» button.

Docker-desktop For Windows

Step 2: Install Docker Desktop

  • Run the downloaded software through clicking on Install option.
  • Follow the Installation Wizard instructions.
  • During the Installation, make sure to enable ‘Hyper-V windows Features’ option is selected.

Installation Of Docker Desktop process

Step 3: Run Docker Desktop

  • After the installation of Docker Desktop has done successfully. Close the Applications and open it again from the Start Menu.

Step 4: Enabling WSL 2 (Windows Subsystem For Linux)

  • Docker Desktop uses WSL2 as its default backend. Ensure that you have WSL2 installed.
  • Ensure to follow the instructions provided by Docker Desktop to enable WSL2 during the first run.

Restarting the docker desktop

  • When your system restart this windows occurs on your screen. Finally the setup of the Docker Desktop has done successfully.

open

Step 5: Verifying Installation

  • Open your command prompt or power shell.
  • Run the following command to check the Docker CLI installation.
docker --version
  • Run the following command to verify the docker can pull and run the containers.
docker pull ubuntu:latest

How to Install Compose standalone on Windows

Step 1: Open Powershell

  • Open Powershell on your windows system
  • and run as an administrator

Powershell

Step 2: Run the following command

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

A-Powershell-TLSA-permissions

Step 3 : Now run this command to download specific docker-compose version

Start-BitsTransfer -Source "https://github.com/docker/compose/releases/download/v2.24.5/docker-compose.exe" -Destination $Env:Program Files\Docker\docker-compose.exe
  • in the -Source section you can specify the Docker-Compose version which you want to intsall.
  • in the -Destination section you can specify the location where you download the file.
  • after running this command wait until the downloading process is not completed.

permission-command

Step 5: Verifying Installation

  • After finishing the downloading process.
  • Open your command prompt or power shell.
  • Run the following command to check the Docker CLI installation.
docker --version

Docker Compose Tips And Tricks For Windows

Use Verified Images

Always use Verified Images it is a best practice which will give you confidence about the authenticity of an Docker Image. Verfied Images are well maintained and easy to understand because all process is well documented. The verified images is updated time to time and fixes bugs and issues related to Images. before using the image you can check on the Dockerhub and use only those images who have official tag and associated with well known organization.

  • You can also use Docker inspect command to check the image is signed or not. this is the syntax
docker trust inspect IMAGE[:TAG] [IMAGE[:TAG]...]

Tip : you can check how does Docker Content Trust works and how it verify the images and if you want so you can also use it to verify your own Docker images.

Versioning

Mention the current Docker Compose version in the starting in your Docker File. so there might be less chance of getting the issues with the version. it is the best practice to use latest version and if you want so you can also specify the which O.S you use if you use light weight Os like alpine it will give you advantage and provide efficiency in fetching and pulling the request.

Efficient Catching In Layers

As we know that Time is everything. by following some simple techniques we can save the time, the steps in dockerfile is called as layers in docker compose. and when you run command for building the image so it go through each step. and docker temporarily store the layers which are rebuild. so the next time you rebuild the image so it will not taking too much time and redownload it. when you run the build command. it will speed up the process. The following are the simple techniques you follow for efficient catching:

  • Take care of ordering of Layers.
  • Use multi stage builds
  • Take care of what files you are copying in Docker file
  • If you want so can add large files to Dockerignore file i.e nodemodules.

Use Docker Volumes

Docker volumes are very useful feature. by using this feature you can share your data from one container to another container. you can mount your data to another container so if somehow your container are stopped are destroyed so your data is not destroyed with the container. and that’s how you saved your data. if you want so you can also create your custom volumes.

Enviroment Variables

Enviroment variables are the one of the most important factor of Docker File. Make sure to provide the Enviroment variable name according to it’s work which is readable and explain it’s related work and provide default values which will helps in different scenarios.

Special Tricks For Usage Of Docker Compose For Windows

  • You can use some special Editors/Extentions which will highlight Docker syntax and it helps you to grab the right options.
  • Docker required a large storage in your system so sometimes it will creating issues with low-end pc’s so you can use some alternatives of it or try to clear your storage time to time.
  • make sure that the file you mentioned in docker compose file are in the same directory/project otherwise it will not getting access to it.
  • You can explore the availability of creating your own network on your docker file which will give you the isolation which you required for better security.
  • You can use caching techniques for saving the data. which will help you to reduce the image loading time.

Conclusion

Docker compose is a powerful tool for managing multi-container-based applications. by using Docker compose you can effectively manage what kind dependencies, servers , and networks etc required for your container. in this article we go through how we can install Docker Desktop to our system and what is Docker compose and some special tips and tricks how we can use Docker compose effectively.

Docker Compose lets you run complex applications using a single command. This means that containers can be deployed faster and more efficiently. Our tutorial guides you through the Docker Compose Windows installation step by step.

What are the requirements of Docker Compose on Windows?

Docker Compose is an integral part of Docker Desktop for Windows. To use the standalone version of Docker Compose, the following requirements must be met:

  • Docker Engine: Compose is an extension of Docker Engine. So you need to have the Docker Server and Client binaries installed.
  • Operating System: Windows, administrator rights

How to install Docker Compose on Windows step by step

To install and use Docker Compose, Docker Daemon and Docker Client should be running on your Windows server. Before getting started it’s best to ensure that the Docker service is running error-free.

Step 1: Start PowerShell

First, launch PowerShell using your administrator rights. Confirm “Yes” to allow the app to make changes to your device.

User Account Control

Click “Yes” to begin installation.

Step 2: Set up TLS security protocol

GitHub requires TLS1.2 as the default security protocol. Run the following command in Windows PowerShell:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

powershell

Step 3: Download and install Docker Compose

Download the latest version of Compose (v2.17.2) from GitHub:

Start-BitsTransfer -Source "https://github.com/docker/compose/releases/download/v2.17.2/docker-compose-Windows-x86_64.exe" -Destination $Env:ProgramFiles\Docker\docker-compose.exe

powershell

To install a different version, simply replace v2.17.2 in the target address with the desired version number.

Step 3: Test Docker Compose

Check if the installation was successful by displaying the current version of Compose:

docker compose version

powershell

You should see the following output:

Docker Compose Version

When you see the version number of Compose, the installation was successful.

Как запустить Docker Compose на Windows: Полное руководство для начинающих и продвинутых пользователей 🐳

😤Открыть📄

Docker Compose — это мощный инструмент, позволяющий с легкостью управлять многоконтейнерными Docker-приложениями. Он оркестрирует запуск, остановку и взаимосвязь нескольких контейнеров, определяя их конфигурацию в едином YAML-файле. В этой статье мы подробно рассмотрим, как запустить Docker Compose на Windows, а также затронем важные аспекты работы с Docker в целом.

Выберите подходящий раздел посредством нижеследующей ссылки:

💎 Запуск Docker Compose в Visual Studio: Два простых способа 🚀

💎 Что такое Docker и зачем он нужен? 🤔

💎 Как удалить Docker с Windows: Полная деинсталляция 🧹

💎 Docker Swarm: Оркестрация контейнеров в кластере 🐝

💎 Где Docker хранит свои данные? 📁

💎 Json

💎 Зачем нужен Docker Compose? 🤝

💎 Выводы и заключение 🎯

💎 FAQ: Часто задаваемые вопросы ❓

📰 Автор


Запуск Docker Compose в Visual Studio: Два простых способа 🚀

Если вы разрабатываете в Visual Studio, у вас есть два удобных способа запустить Docker Compose:

  1. Через меню «Отладка»: Перейдите в меню «Отладка» и выберите пункт «Управление параметрами запуска Docker Compose». Этот способ позволяет настроить параметры запуска, такие как переменные среды и порты, непосредственно из интерфейса Visual Studio. Это особенно удобно при отладке сложных приложений, состоящих из множества сервисов.
  2. Через контекстное меню проекта: Щелкните правой кнопкой мыши на проекте `docker-compose` в Visual Studio и выберите «Управление параметрами запуска Docker Compose». Этот способ более быстрый, если вам нужно просто запустить приложение с настройками по умолчанию или уже существующей конфигурацией.

Оба способа позволяют интегрировать процесс запуска Docker Compose непосредственно в ваш рабочий процесс разработки, значительно упрощая тестирование и отладку приложений.

Что такое Docker и зачем он нужен? 🤔

Docker — это не просто технология, это целая философия разработки, основанная на контейнеризации. 📦 Контейнеризация позволяет упаковать приложение со всеми его зависимостями (библиотеками, фреймворками, системными инструментами) в изолированный контейнер. Этот контейнер можно легко перенести на любую другую систему, где установлен Docker, и ваше приложение будет работать точно так же, как и на вашей машине разработчика.

Преимущества Docker:

  • Изоляция: Контейнеры изолированы друг от друга, что предотвращает конфликты между приложениями и обеспечивает безопасность. 🛡️
  • Переносимость: Контейнеры можно запускать где угодно: на локальной машине, в облаке, на сервере. ☁️
  • Воспроизводимость: Docker обеспечивает согласованность среды разработки и развертывания, что снижает количество ошибок. 🐛
  • Масштабируемость: Легко масштабировать приложения, добавляя или удаляя контейнеры. 📈
  • Эффективность: Контейнеры используют ресурсы более эффективно, чем виртуальные машины. ⚡

Docker стал стандартом в современной разработке, позволяя командам быстрее создавать, тестировать и развертывать приложения.

Как удалить Docker с Windows: Полная деинсталляция 🧹

Если вам нужно удалить Docker с Windows, следуйте этим шагам:

  1. Откройте «Параметры»: Перейдите в «Параметры» Windows 10 (через меню «Пуск» или нажав Win+I).
  2. Перейдите в «Приложения»: Выберите раздел «Приложения».
  3. Найдите Docker: В списке «Приложения и компоненты» найдите «Docker Desktop».
  4. Удалите Docker: Выберите «Docker Desktop» и нажмите кнопку «Удалить».
  5. Следуйте инструкциям: Следуйте инструкциям на экране, чтобы завершить процесс удаления.

После удаления рекомендуется перезагрузить компьютер.

Docker Swarm: Оркестрация контейнеров в кластере 🐝

Docker Swarm — это встроенный инструмент оркестрации контейнеров в Docker. Он позволяет объединить несколько Docker-хостов в кластер и управлять ими как единым целым.

Ключевые особенности Docker Swarm:

  • Кластеризация: Объединение узлов Docker в кластер. 🌐
  • Оркестрация: Автоматическое развертывание, масштабирование и управление контейнерами. ⚙️
  • Обнаружение сервисов: Автоматическое обнаружение сервисов внутри кластера. 🔍
  • Балансировка нагрузки: Распределение нагрузки между контейнерами. ⚖️
  • Отказоустойчивость: Автоматическое восстановление контейнеров в случае сбоя. 🛡️

Docker Swarm — это отличный выбор для небольших и средних проектов, где не требуется сложная оркестрация, предоставляемая Kubernetes.

Где Docker хранит свои данные? 📁

По умолчанию Docker хранит слои образов и другие данные в папке `C:\ProgramData\docker`. Эта папка разделена на несколько подкаталогов, включая `image` и `windowsfilter`.

Как изменить расположение данных Docker:

Вы можете изменить расположение данных Docker, используя параметр `docker-root` в конфигурации Docker Engine. Для этого необходимо отредактировать файл конфигурации Docker Engine (обычно `daemon.json`) и добавить или изменить параметр `data-root`.

Json

{

«data-root»: «D:\\docker-data»

}

После изменения конфигурации необходимо перезапустить Docker Engine.

Важно: Перенос данных Docker может занять много времени, в зависимости от размера ваших образов и контейнеров.

Зачем нужен Docker Compose? 🤝

Docker Compose — это инструмент, который позволяет определить и запустить многоконтейнерные Docker-приложения. Он использует YAML-файл (`docker-compose.yml`) для определения сервисов, сетей и томов, необходимых для вашего приложения.

Преимущества Docker Compose:

  • Простота: Легко определить и запустить многоконтейнерные приложения. 📝
  • Воспроизводимость: Конфигурация приложения хранится в файле, что обеспечивает воспроизводимость. 🔄
  • Управление жизненным циклом: Docker Compose позволяет управлять всеми этапами жизненного цикла сервиса: запуск, остановка, перестроение, просмотр состояния и журналов. ♻️

Docker Compose — это незаменимый инструмент для разработки и тестирования многоконтейнерных приложений.

Выводы и заключение 🎯

В этой статье мы рассмотрели основные аспекты работы с Docker и Docker Compose на Windows. Мы узнали, как запустить Docker Compose в Visual Studio, что такое Docker и зачем он нужен, как удалить Docker с Windows, что такое Docker Swarm, где Docker хранит свои данные и зачем нужен Docker Compose.

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

FAQ: Часто задаваемые вопросы ❓

  • Вопрос: Как проверить, установлен ли Docker на Windows?
  • Ответ: Откройте командную строку и выполните команду `docker —version`. Если Docker установлен, вы увидите версию Docker.
  • Вопрос: Как запустить Docker Compose из командной строки?
  • Ответ: Перейдите в каталог, где находится файл `docker-compose.yml`, и выполните команду `docker-compose up -d`.
  • Вопрос: Как остановить Docker Compose?
  • Ответ: Перейдите в каталог, где находится файл `docker-compose.yml`, и выполните команду `docker-compose down`.
  • Вопрос: Где найти примеры файлов `docker-compose.yml`?
  • Ответ: В Интернете можно найти множество примеров файлов `docker-compose.yml` для различных приложений. Вы также можете посмотреть примеры в официальной документации Docker Compose.
  • Вопрос: Что делать, если Docker Compose не запускается?
  • Ответ: Проверьте, правильно ли установлен Docker, правильно ли настроен файл `docker-compose.yml`, и нет ли конфликтов портов. Также можно посмотреть логи Docker Compose для получения более подробной информации об ошибке.

Вопросы и ответы

👉 Что такое доккер 👈

Docker — это программная платформа для разработки, доставки и запуска контейнерных приложений. Он позволяет создавать контейнеры, автоматизировать их запуск и развертывание, управляет жизненным циклом. С помощью Docker можно запускать множество контейнеров на одной хост-машине.

👉 Как остановить образ docker 👈

Закрытие контейнеров Docker:

1. На компьютере хоста перейдите в рабочий каталог Docker, в котором вы ранее внедрили файлы пакета образов Docker (/mdm).

2. Выполните следующую команду docker-compose , чтобы остановить и удалить связанные контейнеры и аккуратно закрыть сеть: docker-compose –f down.

👉 Как в Docker Compose.yml указать, что один сервис зависит от другого и должен быть запущен после него 👈

Ключевое слово — depends_on. Так будет указано что контейнер зависит от другого и их запуск будет в определенном порядке.

👉 Что такое docker для чайников 👈

Docker — это платформа с открытым исходным кодом для автоматизации разработки, доставки и развертывания приложений. Ее основная идея — создание стандартного и предсказуемого окружения, где приложения могут работать независимо от операционной системы или инфраструктуры.

👉 Где хранятся настройки docker 👈

Предпочтительный метод настройки подсистемы Docker в Windows использует файл конфигурации. Файл конфигурации можно найти по адресу C:\ProgramData\Docker\config\daemon. json. Если этот файл еще не существует, его можно создать.

👉 Где находится папка docker 👈

Где хранятся слои и как изменить его:

В установке по умолчанию слои хранятся в C:\ProgramData\docker и разделяются по каталогам image и windowsfilter. Вы можете изменить место хранения слоев с помощью конфигурации docker-root , как показано в документации по подсистеме Docker в Windows.

👉 Зачем нужен докер композ 👈

Файл Docker Compose обеспечивает управление всеми этапами в жизненном цикле определенной службы: запуском, остановкой и перестроением служб; просмотром состояния службы; и потоковой передачей журналов. Откройте интерфейс командной строки из каталога проекта (где находится файл docker-compose.

👉 Где лежит конфиг docker 👈

Предпочтительный метод настройки подсистемы Docker в Windows использует файл конфигурации. Файл конфигурации можно найти по адресу C:\ProgramData\Docker\config\daemon.

👉 Что такое docker Swarm 👈

Режим Swarm — это функция Docker, которая предоставляет встроенные возможности оркестрации контейнеров, включая собственную кластеризацию узлов Docker и планирование рабочих нагрузок контейнеров. Группа узлов Docker формирует кластер swarm, когда их подсистемы Docker работают вместе в режиме swarm.


☑️ Как посмотреть логи docker Compose

☑️ Как запустить файл yaml

☑️ Какой тип личности у Юнги из BTS

☑️ Как правильно стирать кимоно для джиу-джитсу

….

How to Install Docker Compose on Windows Server 2016 / 2019 / 2022. In this tutorial we will introduce Docker with it’s main advantages then move onto installation phase on Windows server.

Imagine a situation where you want to use two containers in a single system. In such a case, building, running and connecting the container from separate Docker files can be very difficult. It will take a lot of your time and even affect your productivity. That is why you need to consider Docker Compose.

What Is Docker Compose?

How to Install Docker Compose on Windows Server 2016 / 2019 / 2022.

A Docker tool used for defining and running multi container Docker applications. Every container running on this platform is isolated. However, they can interact with each other as and when needed.

Moreover, Docker Compose files are written in an easy scripting language called YAML. An XML based language whose acronym is Yet Another Markup Language. What makes this tool highly popular among users is its feature of providing access to activate all the services using a single command.

In a nutshell, instead of containing all the services in a huge container, Docker Compose splits them up into individually manageable containers. It proves to be highly advantageous both for building and deployment as you can manage all of them in distinct codebases.

You can use a Docker Compose in three processes:

  • Firstly to build component images using Docker Files, or get them from the libraries.
  • Secondly to determine every component service in the “docker-compose.yml” files.
  • Lastly to run them together via “docker-compose” CLI.

Docker Compose Features

Docker Compose constitutes the following features:

  • Supporting Environment Variables -here the Docker Compose enables you to customize containers based on different environments or users by adding variables in the Docker Compose files. This way, you tend to get more flexibility while setting up containers with Compose. Interestingly you can use this feature for almost anything from securely providing passwords to specifying a software version.
  • Reusing Existing Containers – where Docker Compose recreates containers that have changed since the last run. If it notices no changes, it re uses the existing container. It relies on the ability of the software to cache container configuration, thereby allowing you to set up your services faster.
  • Volume Data Preservation – with Docker Compose it saves data used by the services. You do not have to worry about losing data created in containers. If you have containers from the previous run, it will find them and copy their volumes to the new run.

Advantages Of Docker Compose

Some of the crucial benefits of Docker Compose are as follows:

  • Immediate And Straightforward Configurations – Since Docker Compose uses YAML scripts and environment variables, configuring and modifying application services is very effortless.
  • Provides Portability And CI/CD Support – All the services are defined inside of the Docker Compose files, making it effortless for developers to access and share the entire configuration. If they pull the YAML files and source code, an environment can be launched in just a matter of minutes. This way, setting and enabling CI/CD pipelines is very easy.
  • Internal Communication Security – With the help of Docker Compose, you can create a network for all the services to share. It adds an extra security layer for the app as the services cannot be accessed externally.
  • Using Resources Efficiently -by using Docker Compose, you can host multiple environments on one host. When you run everything on a single piece of hardware, you save a lot of resources. This way, it can cache configuration and re use existing containers contributing to resource efficiency.

Follow this post to show you how to install Docker Compose on Windows Server 2016, 2019 and 2022.

Install Docker Compose on Windows Server 2016, 2019 and 2022

Prerequisites

  • A server running Windows Server 2016, 2019 or 2022 operating system along with RDP access.
  • A user with administrative privileges.
  • Minimum 4 GB of RAM with 2 Cores CPU.

Verify Docker Installation

Before installing Docker Compose, you will need to make sure Docker is installed on your Windows server. To verify the Docker installation, open your Windows command prompt and run the following command:

If Docker is installed on your system, you will get the following information:

				
					Client: Docker Engine - Enterprise
 Version:           19.03.2
 API version:       1.40
 Go version:        go1.12.8
 Git commit:        c92ab06ed9
 Built:             09/03/2019 16:38:11
 OS/Arch:           windows/amd64
 Experimental:      false

Server: Docker Engine - Enterprise
 Engine:
  Version:          19.03.2
  API version:      1.40 (minimum version 1.24)
  Go version:       go1.12.8
  Git commit:       c92ab06ed9
  Built:            09/03/2019 16:35:47
  OS/Arch:          windows/amd64
  Experimental:     false

				
			

Install Docker Compose

Before installing Docker Compose, you will need to enable TLS12 in PowerShell to download the Docker Compose binary from the Git Hub.

First step is to open the PowerShell as an administrator user. Run the following command to enable the Tls12:

				
					[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
				
			

Second step is to change the directory to the Docker directory with the following command:

				
					cd C:\Program Files\Docker>
				
			

Next step is to download the latest version of Docker Compose binary from the Git Hub with the following command:

				
					Invoke-WebRequest "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-Windows-x86_64.exe" -UseBasicParsing -OutFile docker-compose.exe
				
			

Once the Docker Compose is downloaded, you can verify the Docker Compose version with the following command:

				
					docker-compose.exe version
				
			

You will get the Docker Compose version in the following output:

				
					docker-compose version 1.29.2, build 5becea4c
docker-py version: 5.0.0
CPython version: 3.9.0
OpenSSL version: OpenSSL 1.1.1g  21 Apr 2020
				
			

Docker Compose Help

If you are new to Docker Compose and don’t know all option to run it, then use this command to see the list of all options:

				
					docker-compose.exe --help
				
			

You will get the following list:

				
					Commands:
  build              Build or rebuild services
  config             Validate and view the Compose file
  create             Create services
  down               Stop and remove resources
  events             Receive real time events from containers
  exec               Execute a command in a running container
  help               Get help on a command
  images             List images
  kill               Kill containers
  logs               View output from containers
  pause              Pause services
  port               Print the public port for a port binding
  ps                 List containers
  pull               Pull service images
  push               Push service images
  restart            Restart services
  rm                 Remove stopped containers
  run                Run a one-off command
  scale              Set number of containers for a service
  start              Start services
  stop               Stop services
  top                Display the running processes
  unpause            Unpause services
  up                 Create and start containers
  version            Show version information and quit

				
			

Create a Sample IIS Container with Docker Compose

To use Docker Compose, you will need to create a docker-compose.yml file where you can define your all applications, interconnect all with each other and run them using a single command.

Let’s create a docker-compose.yml file to launch a simple IIS container. To do so, open your Notepad++ editor and add the following configurations:

				
					version: "2.1"
services:
  iis-demo:
    build: .
    image: "iis-demo:1.0"
    ports:
    - "80"
    networks:
      nat:
        ipv4_address: 172.24.128.2
    volumes:
    - "c:/temp:c:/inetpub/logs/LogFiles"
    environment:
    - "env1=LIVE1"
    - "env2=LIVE2"
    - "HOSTS=1.2.3.4:TEST.COM"
networks:
  nat:
    external: true
				
			

Save the file with name docker-compose.yml.

Next step is to create a Docker file using the Notepad++ editor using the following content:

				
					FROM microsoft/iis

# install ASP.NET 4.5
RUN dism /online /enable-feature /all /featurename:IIS-ASPNET45 /NoRestart

# enable windows eventlog
RUN powershell.exe -command Set-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\WMI\Autologger\EventLog-Application Start 1

# set IIS log fields
RUN /windows/system32/inetsrv/appcmd.exe set config /section:system.applicationHost/sites /siteDefaults.logFile.logExtFileFlags:"Date, Time, ClientIP, UserName, SiteName, ServerIP, Method, UriStem, UriQuery, HttpStatus, Win32Status, TimeTaken, ServerPort, UserAgent, Referer, HttpSubStatus"  /commit:apphost

# deploy webapp
COPY publish /inetpub/wwwroot/iis-demo
RUN /windows/system32/inetsrv/appcmd.exe add app /site.name:"Default Web Site" /path:"/iis-demo" /physicalPath:"c:\inetpub\wwwroot\iis-demo"

# set entrypoint script
ADD SetHostsAndStartMonitoring.cmd \SetHostsAndStartMonitoring.cmd
ENTRYPOINT ["C:\\SetHostsAndStartMonitoring.cmd"]

# declare volumes
VOLUME ["c:/inetpub/logs/LogFiles"]

				
			

Save the file with name Dockerfile.

Following step is to open your PowerShell as a administrator and change the directory to the directory where your docker-compose.yml and Dockerfile are saved.

Now run the following command to download IIS image and start the container:

Once the IIS container is started, you can verify the running container using the following command:

To check the container logs, run the following command:

If you want to stop the IIS container, run the following command:

That is great! We have learned How to Install Docker Compose on Windows Server 2016 / 2019 / 2022. it is time to summarize.

How to install Docker Compose on Windows Server 2016, 2019 and 2022 Conclusion

In this post, we explained how to install Docker Compose on Windows server 2016, 2019 and 2022. We also explained how to create a Docker file and docker-compose.yml file to launch the IIS demo container. I hope you can now easily launch your container using Docker Compose on Windows machine.

Docker Compose is very useful tool that make it easier orchestrate multiple containers to work together, especially in the case where you need to orchestrate more complex applications with multiple services. Docker compose also helps developers to automate the deployment of their code.

Please take a look at our Docker content here. 

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Amd raid driver for windows 7 64
  • Windows device mobile centre
  • Нет дисковода в моем компьютере windows 10
  • Apex legends не запускается на windows 11
  • Mt6580 driver windows 10