Docker compose for windows 10

Docker Compose is available on multiple platforms.In this lab we’ll demonstrate some of the ways to install it on Linux, Windows and Mac.

Installing Docker Compose on Linux

Installing Docker Compose on Linux is a two-step process. Firt you will be downloading binary from github, Second giving executable permission.

Download the current stable release of Docker Compose

$ curl -L https://github.com/docker/compose/releases/download/1.24.1/docker-compose-`uname -s`-`uname -m` -o /usr/local/bin/docker-compose
$ chmod +x /usr/local/bin/docker-compose

Test the installation

You can run this command from a terminal window

$ docker-compose --version

Installing Docker Compose on Windows 10

If you have already installed Docker Desktop for Windows or Docker Toolbox then no need of separate installation for docker compose, since its part of the package.

Check Docker Compose is installed

You can run this command from a PowerShell or CMD terminal.

Installing Docker Compose on Mac

Docker Compose is installed as part of Docker for Mac. So if you have Docker for MAC, you have Docker Compose.

Check Docker Compose is installed

You can run this command from a terminal window.

$ docker-compose --version

Contributor

Savio Mathew

This page contains information on how to install Docker Compose. You can run Compose on macOS, Windows, and 64-bit Linux.

Prerequisites

Docker Compose relies on Docker Engine for any meaningful work, so make sure you have Docker Engine installed either locally or remote, depending on your setup.

  • On desktop systems like Docker Desktop for Mac and Windows, Docker Compose is included as part of those desktop installs.

  • On Linux systems, you can install Docker Compose with the Docker Engine using the convenience script. Select the install Docker Engine page for your distribution and then look for instructions on installing using the convenience script.
    Otherwise, you should first install the Docker Engine for your OS and then refer to this page for instructions on installing Compose on Linux systems.

  • To run Compose as a non-root user, see Manage Docker as a non-root user.

Install Compose

Follow the instructions below to install Compose on Mac, Windows, Windows Server, or Linux systems.

Install a different version

The instructions below outline installation of the current stable release (v2.5.0) of Compose. To install a different version of Compose, replace the given release number with the one that you want.

Compose releases are also listed and available for direct download on the Compose repository release page on GitHub.

To install the Python version of Compose, follow instructions in the Compose v1 GitHub branch.

  • Mac
  • Windows
  • Windows Server
  • Linux
  • Linux Standalone binary

Install Compose on macOS

Docker Desktop for Mac includes Compose along with other Docker apps, so Mac users do not need to install Compose separately. For installation instructions, see Install Docker Desktop on Mac.

Install Compose on Windows desktop systems

Docker Desktop for Windows includes Compose along with other Docker apps, so most Windows users do not need to install Compose separately. For install instructions, see Install Docker Desktop on Windows.

If you are running the Docker daemon and client directly on Microsoft Windows Server, follow the instructions in the Windows Server tab.

Install Compose on Windows Server

Follow these instructions if you are running the Docker daemon and client directly on Microsoft Windows Server and want to install Docker Compose.

  1. Start an “elevated” PowerShell (run it as administrator). Search for PowerShell, right-click, and choose Run as administrator. When asked if you want to allow this app to make changes to your device, click Yes.

  2. In PowerShell, since GitHub now requires TLS1.2, run the following:

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

    Then run the following command to download the current stable release of Compose (v2.5.0):

    Invoke-WebRequest "https://github.com/docker/compose/releases/download/v2.5.0/docker-compose-Windows-x86_64.exe" -UseBasicParsing -OutFile $Env:ProgramFiles\Docker\docker-compose.exe
    

    Note

    On Windows Server 2019, you can add the Compose executable to $Env:ProgramFiles\Docker. Because this directory is registered in the system PATH, you can run the docker-compose --version command on the subsequent step with no additional configuration.

    To install a different version of Compose, substitute v2.5.0 with the version of Compose you want to use.

  3. Test the installation.

    $ docker compose version
    Docker Compose version v2.5.0
    

Install Compose on Linux systems

You can install Docker Compose in different ways, depending on your needs:

  • In testing and development environments, some users choose to use automated convenience scripts to install Docker.
  • Most users set up Docker’s repositories and install from them, for ease of installation and upgrade tasks. This is the recommended approach.
  • Some users download and install the binary, and manage upgrades manually.

Install using the convenience script

As Docker Compose is now part of the Docker CLI it can be installed via a convenience script with Docker Engine and the CLI.
Choose your Linux distribution and follow the instructions.

Install using the repository

If you already follow the instructions to install Docker Engine, Docker Compose should already be installed.
Otherwise, you can set up the Docker repository as mentioned in the Docker Engine installation, choose your Linux distribution and go to the Set up the repository section.

When finished

  1. Update the apt package index, and install the latest version of Docker Compose, or go to the next step to install a specific version:

     $ sudo apt-get update
     $ sudo apt-get install docker-compose-plugin
    
  2. To install a specific version of Docker Engine, list the available versions in the repo, then select and install:

    a. List the versions available in your repo:

    $ apt-cache madison docker-compose-plugin
    
      docker-compose-plugin | 2.3.3~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable arm64 Packages
    

    b. Install a specific version using the version string from the second column, for example, 2.3.3~ubuntu-focal.

    $ sudo apt-get install docker-compose-plugin=<VERSION_STRING>
    
  3. Verify that Docker Compose is installed correctly by checking the version.

    $ docker compose version
    Docker Compose version v2.3.3
    

Install the binary manually

On Linux, you can download the Docker Compose binary from the Compose repository release page on GitHub and copying it into $HOME/.docker/cli-plugins as docker-compose. Follow the instructions from the link, which involve running the curl command in your terminal to download the binaries. These step-by-step instructions are also included below.

  1. Run this command to download the current stable release of Docker Compose:

    $ DOCKER_CONFIG=${DOCKER_CONFIG:-$HOME/.docker}
    $ mkdir -p $DOCKER_CONFIG/cli-plugins
    $ curl -SL https://github.com/docker/compose/releases/download/v2.5.0/docker-compose-linux-x86_64 -o $DOCKER_CONFIG/cli-plugins/docker-compose
    

    This command installs Compose for the active user under $HOME directory. To install Docker Compose for all users on your system, replace ~/.docker/cli-plugins with /usr/local/lib/docker/cli-plugins.

    To install a different version of Compose, substitute v2.5.0 with the version of Compose you want to use.

  2. Apply executable permissions to the binary:

     $ chmod +x $DOCKER_CONFIG/cli-plugins/docker-compose
    

    or if you choose to install Compose for all users

     $ sudo chmod +x /usr/local/lib/docker/cli-plugins/docker-compose
    
  3. Test the installation.

     $ docker compose version
     Docker Compose version v2.5.0
    

Install Compose as standalone binary on Linux systems

You can use Compose as a standalone binary without installing the Docker CLI.

  1. Run this command to download the current stable release of Docker Compose:
  $ curl -SL https://github.com/docker/compose/releases/download/v2.5.0/docker-compose-linux-x86_64 -o /usr/local/bin/docker-compose

To install a different version of Compose, substitute v2.5.0 with the version of Compose you want to use.

  1. Apply executable permissions to the binary:
  $ sudo chmod +x /usr/local/bin/docker-compose

Note:

If the command docker-compose fails after installation, check your path. You can also create a symbolic link to /usr/bin or any other directory in your path.

For example:

$ sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
  1. Test the installation.

     $ docker-compose --version
     Docker Compose version v2.5.0
    

Uninstallation

To uninstall Docker Compose if you installed using curl:

$ rm $DOCKER_CONFIG/cli-plugins/docker-compose

or if you choose to install Compose for all users

$ sudo rm /usr/local/lib/docker/cli-plugins/docker-compose

Got a “Permission denied” error?

If you get a “Permission denied” error using either of the above methods, you probably do not have the proper permissions to remove docker-compose. To force the removal, prepend sudo to either of the above commands and run again.

Where to go next

  • User guide
  • Getting Started
  • Command line reference
  • Compose file reference
  • Sample apps with Compose

compose, orchestration, install, installation, docker, documentation

© 2019 Docker, Inc.
Licensed under the Apache License, Version 2.0.
Docker and the Docker logo are trademarks or registered trademarks of Docker, Inc. in the United States and/or other countries.
Docker, Inc. and other parties may also have trademark rights in other terms used herein.
https://docs.docker.com/compose/install/

Update 2021: docker-compose has been rewritten in Go, and is now a docker command docker compose

As such, there is no longer the need to «install» it.
See docker compose.


Update 7th of november 2018:

On desktop systems like Docker for Mac and Windows, Docker Compose is
included as part of those desktop installs.

Accordingly to the documentation, Docker for Windows and Docker Toolbox already include Compose along with other Docker apps, so most Windows users do not need to install Compose separately.


Update 2017: this is now officially managed (for Windows 10 supporting Hyper-V) with «Docker for Windows».
See «Install Docker for Windows».
It does have a chocolatey installation package for Docker, so:

choco install docker-for-windows 
# or
choco upgrade docker-for-windows 

Again, this requires a 64bit Windows 10 Pro, Enterprise and Education (1511 November update, Build 10586 or later) and Microsoft Hyper-V.

For other Windows, you still need VirtualBox + Boot2Docker.


Update: docker compose 1.5 (Nov 2015) should make it officially available for Windows (since RC2).

Pull requests like PR 2230 and PR 2143 helped.
Commit 13d5efc details the official Build process for the Windows binary.


Original answer (Q1-Q3 2015).

Warning: the original answer («docker-compose in a container») below seems to have a bug, according to Ed Morley (edmorley).

There appear to be caching issues with the «docker-compose in a container» method (See issue #6: «Changes to docker-compose.yml and Dockerfile not being detected»)

Ed recommends:

As such for now, running the Python docker-compose package inside boot2docker seems to be the most reliable solution for Windows users (having spent many hours trying to battle with the alternatives).

To install docker-compose from PyPI, run this from inside boot2docker:

docker@boot2docker:~$ 
tce-load -wi python && curl https://bootstrap.pypa.io/get-pip.py | \
  sudo python - && sudo pip install -U docker-compose

To save having to run the above every time the boot2docker VM is restarted (since changes don’t persist), you can use bootlocal.sh like so:

docker@boot2docker:~$ 
echo 'su docker -c "tce-load -wi python" && \
  curl https://bootstrap.pypa.io/get-pip.py | \
  python - && pip install -U docker-compose' | \ 
  sudo tee /var/lib/boot2docker/bootlocal.sh > /dev/null && \
  sudo chmod +x /var/lib/boot2docker/bootlocal.sh

(The su docker -c gymnastics are required since tce-load cannot be run as root, and bootlocal.sh is run as root. The chmod of bootlocal.sh should be unnecessary once #915 is fixed.
Add -a to the tee command if you need to append, rather than overwrite bootlocal.sh.)

If you wish to use a pre-release version of docker-compose, then replace pip install -U docker-compose with pip install -U docker-compose>=1.3.0rc1 or equivalent.


Original answer:

I also run docker-compose (on Windows boot2docker) in a image by:

  • cloning https://github.com/docker/compose in /c/Users/<username>/myproject/compose (in order to have persistence, since /c/Users/<username> is automatically mounted, when I use VirtualBox with its extension pack )

  • building the docker-compose image:

      cd /c/Users/<username>/myproject/compose
      # that will put the repo in a detached HEAD, but it does not matter here
      git checkout 1.2.0
      docker build -t docker-compose .
    
  • adding a ‘dc‘ alias (in a profile file that I copy to my /home/docker/.ashrc before launching the boot2docker ssh session.)

      dc='docker run --rm -i -t -v /var/run/docker.sock:/var/run/docker.sock -v `pwd`:`pwd` -w `pwd` docker-compose'
    

From there, a ‘dc up‘ or ‘dc ps‘ just works. On Windows. With boot2docker 1.6.

Introduction

Installing docker-compose on Windows requires a few steps. Here’s a step-by-step guide that should help you get set up:

  • Step 1 — Install Docker for Windows

To use docker-compose, you’ll first need to have Docker installed on your Windows machine. If you don’t have it installed already, you can download it from the Docker website:

  1. Go to the Docker website (https://www.docker.com/products/docker-desktop)
  2. Click on the «Get Docker» button to download the installer
  3. Run the installer and follow the prompts to complete the installation

Once Docker is installed, you should be able to open the Docker application from the Windows Start menu and see the Docker daemon running. This is an important step, as docker-compose relies on the Docker engine to work.

  • Step 2 — Install Docker Compose

After installing Docker, you can proceed to install docker-compose. You have a few different options for doing this, depending on your setup and preferences. Here are two methods you can use:

Method 1: Download the docker-compose binary

  1. Go to the docker-compose releases page on GitHub (https://github.com/docker/compose/releases)
  2. Download the docker-compose-Windows-x86_64.exe file for the latest release.
  3. Move the downloaded executable file to a directory in your system’s PATH. This can be done by creating a new directory in C:\Program Files\ and adding the directory path to the PATH environment variable.

Method 2: Use pip to install docker-compose

  1. Install python by downloading the installer from https://www.python.org/downloads/ and run the installer,
  2. add python executable to your system PATH by checking the «Add Python to PATH» checkbox on the first step of the installer.
  3. Open the command prompt and type pip install docker-compose

After you have installed docker-compose, you should be able to run the docker-compose command from the command prompt or PowerShell to see the version of docker-compose installed and check if it’s working properly.

  • Step 3 — Verify the installation

To verify that docker-compose is installed and working properly, you can run the following command:

This should print the version of docker-compose that you have installed, along with some other information. If you see an error message instead, then the installation may not have been successful, and you should check the error message to see what went wrong.

That’s it! You should now have docker-compose installed on your Windows machine and be able to use it to run multi-container applications.
Keep in mind that, this is just a basic introduction, and to learn more about docker-compose and how to use it, you can check the official documentation.

  • Step 4 — Using docker-compose

Now that you have docker-compose installed, you can use it to start, stop and manage multi-container applications.

A docker-compose.yml file is used to define the services, networks and volumes for your application. It’s a YAML file that describes the services, networks and volumes needed for your application. Here’s an example docker-compose.yml file that defines a simple web application with a web service and a redis service:

version: '3'
services:
 web:
 build: .
 ports:
 - "8000:8000"
 volumes:
 - .:/code
 depends_on:
 - redis
 redis:
 image: redis

Once you have a docker-compose.yml file, you can use the docker-compose command to start, stop and manage your application. Here are a few examples of common docker-compose commands you might use:

  • docker-compose up — start the services defined in the docker-compose.yml file
  • docker-compose down — stop the services and remove the containers, networks, and volumes defined in the docker-compose.yml file
  • docker-compose ps — show the status of the services defined in the docker-compose.yml file
  • docker-compose logs — show the logs for the services defined in the docker-compose.yml file
  • docker-compose exec — execute a command in a running container

These are just a few examples of the commands you can use with docker-compose, there are many more options and capabilities that you can explore and use to manage your multi-container applications.

Conclusion

In conclusion, docker-compose is a powerful tool that allows you to easily manage multi-container applications on a Windows machine. The process of installing it requires a few steps, including having Docker installed first. Once you have docker-compose installed, you can use the docker-compose command along with a docker-compose.yml file to start, stop, and manage your application.

It’s a good idea to take a look at the official documentation to explore other options and capabilities of docker-compose as well as to explore some examples of real-world usage. As a beginner, it might take some time for you to get used to the concepts and commands, but with time and practice, you will get more comfortable and confident with it.

imageДанная публикация является разбором особенностей контейнерной виртуализации Docker под системой Windows.

Она не претендует на роль исчерпывающей и по мере необходимости будет обновляться и дополняться.

За практическим руководством с нуля советую обратиться к этой публикации.

Содержание

  • Предварительные настройки
  • Выбор между Docker Toolbox on Windows или Docker for Windows
  • Windows контейнеры и Linux контейнеры
  • Особенности монтирования папок
  • Монтирование с хост-машины или volume
  • Особенности разметки диска GPT и MBR
  • Docker Toobox to Windows
  • Docker Swarm
  • Проблемы с кодировкой
  • Полезные ссылки
  • Заключение

Предварительные настройки

Контейнерная виртуализация или виртуализация на уровне операционной системы Docker нативно работает только на дистрибутивах Linux и FreeBSD (экспериментально).
На Windows вам понадобится гостевая Linux система либо специальная минималистичная виртуальная машина с ядром Linux от разработчиков Docker, которая и ставится из коробки.
Само собой разумеется, что вы включили виртуализацию у себя в BIOS/UEFI
Пункт настройки может называться по-разному: VT-x, VT-d, Intel VT, AMD-V, Virtualization Technology.

Еще одним минимальным системным требованием будет разрядность системы x64 и версия не ниже Windows 7 Pro.

Выбор между Docker Toolbox on Windows или Docker for Windows

Появление Docker Toolbox on Windows и Docker Toolbox on Mac было большим событием.

Сборка включается в себя сам docker, утилиту docker-compose, утилиту для работы с виртуальной машиной docker-machine и клиент Kitematic.

Используется виртуальная машина (по умолчанию на VirtualBox) с минималистичным Linux окружением.

Позже для новых операционных систем выпустили Docker for Windows и Docker for Mac, которая на текущий момент является актуальной версией и продолжает развиваться.

Выбор между версиями не сложный:
— Если у вас Windows 10 x64 Pro, Enterprise или Education то включаем службу Hyper-V и ставим Docker for Windows.

Заметьте, что после включения службы Hyper-V пропадет возможность запускать и создавать x64 виртуальные машины на VirtualBox.

— Если же у вас другая версия Windows(7 Pro, 8, 8.1, 10 Home) то ставим VirtualBox и Docker Toolbox on Windows.

Несмотря на то, что Docker Toolbox разработчиками признан устаревшим работа с ним слабо отличается от Docker for Windows.

Вместе с установкой Docker Toolbox будет создана виртуальная машина.
В самом VirtualBox можно будет добавить оперативной памяти и ядер процессора на ваше усмотрение.

Windows контейнеры и Linux контейнеры

Docker for Windows предоставляет возможность переключать контейнеризацию между Linux и Windows версией.

В режиме Windows контейнеризации вы можете запускать только Windows приложения.
Замечу, что на май 2018 года в официальном Docker Hub существует всего 13 образов для Windows.

После включения Windows контейнеризации не забудьте добавить внешнюю сеть.

В конфигурационном файле docker-compose.yml это выглядит так:

networks:
  default:
    external:
      name: nat

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

На примонтированных volume-ах не кидаются события файловой системы, поэтому inotify-tools не работает.
Спасибо пользователю eee

Если вы разрабатываете свой проект и пользуетесь docker-compose вне домашней папки то вам нужно будет проделать некоторые манипуляции.

Используя Docker for Windows для монтирования нового диска у вашего локального пользователя обязательно должен стоять пароль, который будет использоваться для доступа к shared папки.

Особенность заключается в том, что монтируемые внутрь контейнера диск будет монтироваться как от удаленной машины //10.0.75.1/DISK_DRIVE по протоколу SMB.

Для Docker Toolbox диски монтируются в самом VirtualBox на вкладке «Общие папки»
Пример для диска «D»:

Права доступа к монтируемым файлам и папкам

Как бы вам не хотелось, но для всех примонтированных из хост-машины файлов и папок будут стоять права 755 (rwx r-x r-x) и поменять их вы не сможете.

Остро встает вопрос при монтировании внутрь файла закрытого SSH ключа, права на который должны быть только у владельца(например 600).

В данном случае либо генерируют ключ при создании образа, либо прокидывают сокет ssh-agent с хост-машины.

Монтирование с хост-машины или volume

Монтирование внутрь контейнера происходит с использованием сети и протокола SMB, следовательно, внутри контейнера диск «D:\» будет примонтирован из источника //10.0.75.1/D
Использование volume внутри контейнера отображается как монтирование локального диска /dev/sda1, что влияет на скорость работы.

Простым тестом копирование файла на обычном HDD скорость работы получилась следующая:

Такая разница в скорости скорее всего связана с тем, что в volume данные сбрасываются на диск постепенно, задействуя кеш в ОЗУ.

Особенности разметки диска GPT и MBR

Данный пункт не является истинной так как опровергающей или подтверждающей информации в интернете найти не смог.

Если на хост-машине таблица разделов MBR, то контейнер с MySQL/MariaDB может упасть с ошибкой:

InnoDB: File ./ib_logfile101: ‘aio write’ returned OS error 122. Cannot continue operation

По умолчанию в базе данных включеён параметр innodb_use_native_aio, отвечающий за асинхронный ввод/вывод и его надо будет выключить.

Данная проблема также встречается на некоторых версиях MacOS.

Docker Toobox to Windows

Главное правило: начинать работу с запуска ярлыка на рабочем столе «Docker Quickstart Terminal», это решает 80% проблем.

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

eval $(docker-machine env default)

— Если все же возникают проблемы из разряда «docker: error during connect», необходимо выполнить:

docker-machine env --shell cmd default 
@FOR /f "tokens=*" %i IN ('docker-machine env --shell cmd default') DO @%i

Название Docker Machine по умолчанию default.

Docker Swarm

Ни в Docker for Mac, ни в Docker for Windows — нет возможности использовать запущенные демоны в качестве клиентов кластера (swarm members).
Спасибо пользователю stychos

Проблемы с кодировкой

Используя Docker Toolbox(на Docker for Windows не удалось воспроизвести) нашлась проблема с тем, что русские комментарии в docker-compose.yml файле приводили к ошибке:

Traceback (most recent call last):
  File "docker-compose", line 6, in <module>
  File "compose\cli\main.py", line 71, in main
  File "compose\cli\main.py", line 124, in perform_command
  File "compose\cli\command.py", line 41, in project_from_options
  File "compose\cli\command.py", line 109, in get_project
  File "compose\config\config.py", line 283, in find
  File "compose\config\config.py", line 283, in <listcomp>
  File "compose\config\config.py", line 183, in from_filename
  File "compose\config\config.py", line 1434, in load_yaml
  File "site-packages\yaml\__init__.py", line 94, in safe_load
  File "site-packages\yaml\__init__.py", line 70, in load
  File "site-packages\yaml\loader.py", line 24, in __init__
  File "site-packages\yaml\reader.py", line 85, in __init__
  File "site-packages\yaml\reader.py", line 124, in determine_encoding
  File "site-packages\yaml\reader.py", line 178, in update_raw
  File "c:\projects\compose\venv\lib\encodings\cp1251.py", line 23, in decode
UnicodeDecodeError: 'charmap' codec can't decode byte 0x98 in position 1702: character maps to <undefined>
[4176] Failed to execute script docker-compose

Полезные ссылки

Docker Toolbox on Windows
Docker for Windows
Практическое руководство по Docker

Заключение

Особенности работы с Docker контейнеризацией на системе Windows не отличается от работы на Linux за исключение разобранных выше.

В статье я умышленно не упомянул заметно низкую скорость работы контейнеров и overhead используя систему Windows как само собой разумеющееся.

Буду рад услышать ваши отзывы. Не стесняйтесь предлагать улучшения или указывать на мои ошибки.

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

Какой версией Docker вы пользуетесь?


32.47%
Docker Toolbox on Windows
88


67.53%
Docker for Windows
183

Проголосовал 271 пользователь.

Воздержался 191 пользователь.

  • Docker build from dockerfile windows
  • Docker volume create path windows
  • Docker desktop for windows server 2019
  • Docker users group windows 10
  • Dock панель для windows 10