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 как контейнера, т.к. считаю его неудобным.
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 insideboot2docker
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 usebootlocal.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 sincetce-load
cannot be run asroot
, andbootlocal.sh
is run asroot
. Thechmod
ofbootlocal.sh
should be unnecessary once #915 is fixed.
Add-a
to thetee
command if you need to append, rather than overwritebootlocal.sh
.)If you wish to use a pre-release version of docker-compose, then replace
pip install -U docker-compose
withpip 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 aprofile
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.
description | keywords | title |
---|---|---|
Get started with Docker Compose |
documentation, docs, docker, compose, orchestration, containers |
Try Docker Compose |
{% include compose-eol.md %}
This tutorial is designed to introduce the key concepts of Docker Compose whilst building a simple Python web application. The application uses the Flask framework and maintains a hit counter in
Redis.
The concepts demonstrated here should be understandable even if you’re not familiar with Python.
Prerequisites
You need to have Docker Engine and Docker Compose on your machine. You can either:
- Install Docker Engine and Docker Compose as standalone binaries
- Install Docker Desktop which includes both Docker Engine and Docker Compose
You don’t need to install Python or Redis, as both are provided by Docker images.
Step 1: Define the application dependencies
-
Create a directory for the project:
$ mkdir composetest $ cd composetest
-
Create a file called
app.py
in your project directory and paste the following code in:import time import redis from flask import Flask app = Flask(__name__) cache = redis.Redis(host='redis', port=6379) def get_hit_count(): retries = 5 while True: try: return cache.incr('hits') except redis.exceptions.ConnectionError as exc: if retries == 0: raise exc retries -= 1 time.sleep(0.5) @app.route('/') def hello(): count = get_hit_count() return 'Hello World! I have been seen {} times.n'.format(count)
In this example,
redis
is the hostname of the redis container on the
application’s network. We use the default port for Redis,6379
.Handling transient errors
Note the way the
get_hit_count
function is written. This basic retry
loop lets us attempt our request multiple times if the redis service is
not available. This is useful at startup while the application comes
online, but also makes the application more resilient if the Redis
service needs to be restarted anytime during the app’s lifetime. In a
cluster, this also helps handling momentary connection drops between
nodes. -
Create another file called
requirements.txt
in your project directory and
paste the following code in:
Step 2: Create a Dockerfile
The Dockerfile is used to build a Docker image. The image
contains all the dependencies the Python application requires, including Python
itself.
In your project directory, create a file named Dockerfile
and paste the following code in:
# syntax=docker/dockerfile:1 FROM python:3.7-alpine WORKDIR /code ENV FLASK_APP=app.py ENV FLASK_RUN_HOST=0.0.0.0 RUN apk add --no-cache gcc musl-dev linux-headers COPY requirements.txt requirements.txt RUN pip install -r requirements.txt EXPOSE 5000 COPY . . CMD ["flask", "run"]
This tells Docker to:
- Build an image starting with the Python 3.7 image.
- Set the working directory to
/code
. - Set environment variables used by the
flask
command. - Install gcc and other dependencies
- Copy
requirements.txt
and install the Python dependencies. - Add metadata to the image to describe that the container is listening on port 5000
- Copy the current directory
.
in the project to the workdir.
in the image. - Set the default command for the container to
flask run
.
Important
Check that the
Dockerfile
has no file extension like.txt
. Some editors may append this file extension automatically and which results in an error when you run the application.
{: .important}
For more information on how to write Dockerfiles, see the
Docker user guide
and the Dockerfile reference.
Step 3: Define services in a Compose file
Create a file called docker-compose.yml
in your project directory and paste
the following:
version: "{{ site.compose_file_v3 }}" services: web: build: . ports: - "8000:5000" redis: image: "redis:alpine"
This Compose file defines two services: web
and redis
.
The web
service uses an image that’s built from the Dockerfile
in the current directory.
It then binds the container and the host machine to the exposed port, 8000
. This example service uses the default port for the Flask web server, 5000
.
The redis
service uses a public Redis
image pulled from the Docker Hub registry.
Step 4: Build and run your app with Compose
-
From your project directory, start up your application by running
docker compose up
.$ docker compose up Creating network "composetest_default" with the default driver Creating composetest_web_1 ... Creating composetest_redis_1 ... Creating composetest_web_1 Creating composetest_redis_1 ... done Attaching to composetest_web_1, composetest_redis_1 web_1 | * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) redis_1 | 1:C 17 Aug 22:11:10.480 # oO0OoO0OoO0Oo Redis is starting oO0OoO0OoO0Oo redis_1 | 1:C 17 Aug 22:11:10.480 # Redis version=4.0.1, bits=64, commit=00000000, modified=0, pid=1, just started redis_1 | 1:C 17 Aug 22:11:10.480 # Warning: no config file specified, using the default config. In order to specify a config file use redis-server /path/to/redis.conf web_1 | * Restarting with stat redis_1 | 1:M 17 Aug 22:11:10.483 * Running mode=standalone, port=6379. redis_1 | 1:M 17 Aug 22:11:10.483 # WARNING: The TCP backlog setting of 511 cannot be enforced because /proc/sys/net/core/somaxconn is set to the lower value of 128. web_1 | * Debugger is active! redis_1 | 1:M 17 Aug 22:11:10.483 # Server initialized redis_1 | 1:M 17 Aug 22:11:10.483 # WARNING you have Transparent Huge Pages (THP) support enabled in your kernel. This will create latency and memory usage issues with Redis. To fix this issue run the command 'echo never > /sys/kernel/mm/transparent_hugepage/enabled' as root, and add it to your /etc/rc.local in order to retain the setting after a reboot. Redis must be restarted after THP is disabled. web_1 | * Debugger PIN: 330-787-903 redis_1 | 1:M 17 Aug 22:11:10.483 * Ready to accept connections
Compose pulls a Redis image, builds an image for your code, and starts the
services you defined. In this case, the code is statically copied into the image at build time. -
Enter http://localhost:8000/ in a browser to see the application running.
If this doesn’t resolve, you can also try http://127.0.0.1:8000.
You should see a message in your browser saying:
Hello World! I have been seen 1 times.
-
Refresh the page.
The number should increment.
Hello World! I have been seen 2 times.
-
Switch to another terminal window, and type
docker image ls
to list local images.Listing images at this point should return
redis
andweb
.$ docker image ls REPOSITORY TAG IMAGE ID CREATED SIZE composetest_web latest e2c21aa48cc1 4 minutes ago 93.8MB python 3.4-alpine 84e6077c7ab6 7 days ago 82.5MB redis alpine 9d8fa9aa0e5b 3 weeks ago 27.5MB
You can inspect images with
docker inspect <tag or id>
. -
Stop the application, either by running
docker compose down
from within your project directory in the second terminal, or by
hitting CTRL+C in the original terminal where you started the app.
Step 5: Edit the Compose file to add a bind mount
Edit docker-compose.yml
in your project directory to add a
bind mount for the web
service:
version: "{{ site.compose_file_v3 }}" services: web: build: . ports: - "8000:5000" volumes: - .:/code environment: FLASK_DEBUG: "true" redis: image: "redis:alpine"
The new volumes
key mounts the project directory (current directory) on the
host to /code
inside the container, allowing you to modify the code on the
fly, without having to rebuild the image. The environment
key sets the
FLASK_DEBUG
environment variable, which tells flask run
to run in development
mode and reload the code on change. This mode should only be used in development.
Step 6: Re-build and run the app with Compose
From your project directory, type docker compose up
to build the app with the updated Compose file, and run it.
$ docker compose up Creating network "composetest_default" with the default driver Creating composetest_web_1 ... Creating composetest_redis_1 ... Creating composetest_web_1 Creating composetest_redis_1 ... done Attaching to composetest_web_1, composetest_redis_1 web_1 | * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit) ...
Check the Hello World
message in a web browser again, and refresh to see the
count increment.
Shared folders, volumes, and bind mounts
If your project is outside of the
Users
directory (cd ~
), then you
need to share the drive or location of the Dockerfile and volume you are using.
If you get runtime errors indicating an application file is not found, a volume
mount is denied, or a service cannot start, try enabling file or drive sharing.
Volume mounting requires shared drives for projects that live outside of
C:Users
(Windows) or/Users
(Mac), and is required for any project on
Docker Desktop for Windows that uses Linux containers.
For more information, see File sharing on Docker
for Mac, and the general examples on how to
Manage data in containers.If you are using Oracle VirtualBox on an older Windows OS, you might encounter an issue with shared folders as described in this VB trouble
ticket. Newer Windows systems meet the
requirements for Docker Desktop for Windows and do not
need VirtualBox.
{: .important}
Step 7: Update the application
Because the application code is now mounted into the container using a volume,
you can make changes to its code and see the changes instantly, without having
to rebuild the image.
Change the greeting in app.py
and save it. For example, change the Hello World!
message to Hello from Docker!
:
return 'Hello from Docker! I have been seen {} times.n'.format(count)
Refresh the app in your browser. The greeting should be updated, and the
counter should still be incrementing.
Step 8: Experiment with some other commands
If you want to run your services in the background, you can pass the -d
flag
(for «detached» mode) to docker compose up
and use docker compose ps
to
see what is currently running:
$ docker compose up -d Starting composetest_redis_1... Starting composetest_web_1... $ docker compose ps Name Command State Ports ------------------------------------------------------------------------------------- composetest_redis_1 docker-entrypoint.sh redis ... Up 6379/tcp composetest_web_1 flask run Up 0.0.0.0:8000->5000/tcp
The docker compose run
command allows you to run one-off commands for your
services. For example, to see what environment variables are available to the
web
service:
$ docker compose run web env
See docker compose --help
to see other available commands.
If you started Compose with docker compose up -d
, stop
your services once you’ve finished with them:
You can bring everything down, removing the containers entirely, with the down
command. Pass --volumes
to also remove the data volume used by the Redis
container:
$ docker compose down --volumes
Where to go next
- Next, try the Sample apps with Compose
- Explore the full list of Compose commands
- Explore the Compose configuration file reference
- To learn more about volumes and bind mounts, see Manage data in Docker
Инсталляционный докерный состав
На этой странице содержится информация о том,как установить Docker Compose.Вы можете запустить Compose на macOS,Windows и 64-битной Linux.
Prerequisites
Docker Compose полагается на Docker Engine для любой значимой работы,поэтому убедитесь,что Docker Engine установлен как локально,так и удаленно,в зависимости от ваших настроек.
-
На таких настольных системах,как Docker Desktop для Mac и Windows,компонент Docker Compose входит в состав этих настольных систем.
-
В системах Linux вы можете установить Docker Compose с Docker Engine с помощью удобного сценария . Выберите страницу установки Docker Engine для вашего дистрибутива, а затем найдите инструкции по установке с помощью удобного сценария.
В противном случае вам следует сначала установить Docker Engine для вашей ОС, а затем обратиться к этой странице за инструкциями по установке Compose в системах Linux. -
Чтобы запустить Compose от имени пользователя без полномочий root, см. раздел Управление Docker от имени пользователя без полномочий root .
Install Compose
Чтобы установить Compose на системы Mac,Windows,Windows Server или Linux,следуйте приведенным ниже инструкциям.
Установить другую версию
В приведенных ниже инструкциях описывается установка текущей стабильной версии ( v2.5.0 ) Compose. Чтобы установить другую версию Compose, замените указанный номер версии на нужный.
Выпуски Compose также перечислены и доступны для прямой загрузки на странице выпуска репозитория Compose на GitHub .
Чтобы установить Python-версию Compose, следуйте инструкциям в ветке Compose v1 GitHub .
- Mac
- Windows
- Windows Server
- Linux
- Linux Standalone binary
Установите Compose on macOS
Docker Desktop для Mac включает Compose вместе с другими приложениями Docker, поэтому пользователям Mac не нужно устанавливать Compose отдельно. Инструкции по установке см. в разделе Установка Docker Desktop на Mac .
Установить композицию на настольные системы Windows
Docker Desktop для Windows включает Compose вместе с другими приложениями Docker, поэтому большинству пользователей Windows не нужно устанавливать Compose отдельно. Инструкции по установке см. в разделе Установка Docker Desktop в Windows .
Если вы используете демона и клиента Docker непосредственно на сервере Microsoft Windows Server,следуйте инструкциям во вкладке Windows Server.
Установите композицию на Windows Server
Следуйте этим инструкциям,если вы запускаете демон и клиент Docker непосредственно на Microsoft Windows Server и хотите установить Docker Compose.
-
Запустите PowerShell с повышенными правами (запустите его от имени администратора). Найдите PowerShell, щелкните правой кнопкой мыши и выберите « Запуск от имени администратора» . Когда вас спросят, хотите ли вы разрешить этому приложению вносить изменения в ваше устройство, нажмите «Да » .
-
В PowerShell,поскольку GitHub теперь требует TLS1.2,выполните следующее:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Затем выполните следующую команду для загрузки текущего стабильного выпуска 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:ProgramFilesDockerdocker-compose.exe
Note
В Windows Server 2019 вы можете добавить исполняемый файл Compose в
$Env:ProgramFilesDocker
. Поскольку этот каталог зарегистрирован в системномPATH
, вы можете запустить командуdocker-compose --version
на последующем шаге без дополнительной настройки.Чтобы установить другую версию Compose, замените
v2.5.0
версией Compose, которую вы хотите использовать. -
Проверьте установку.
$ docker compose version Docker Compose version v2.5.0
Установить композицию на системы Linux
Вы можете установить Docker Compose разными способами,в зависимости от ваших потребностей:
- В средах тестирования и разработки некоторые пользователи предпочитают использовать автоматизированные удобные сценарии для установки Docker.
- Большинство пользователей настраивают репозитории Docker и устанавливают из них для простоты установки и обновления. Это рекомендуемый подход.
- Некоторые пользователи загружают и устанавливают двоичный файл и управляют обновлениями вручную.
Установите с помощью удобного скрипта
Поскольку Docker Compose теперь является частью Docker CLI,его можно установить с помощью удобного скрипта с Docker Engine и CLI.
Выберите свой дистрибутив Linux и следуйте инструкциям.
Установка с использованием репозитория
Если вы уже следовали инструкциям по установке Docker Engine,Docker Compose уже должен быть установлен.
В противном случае вы можете настроить репозиторий Docker, как указано в установке Docker Engine, выбрать свой дистрибутив Linux и перейти к разделу « Set up the repository
».
When finished
-
Обновите индекс пакета
apt
и установите последнюю версию Docker Compose или перейдите к следующему шагу, чтобы установить конкретную версию:$ sudo apt-get update $ sudo apt-get install docker-compose-plugin
-
Чтобы установить определенную версию Docker Engine, перечислите доступные версии в репозитории, затем выберите и установите:
a.Перечислите версии,доступные в вашем репозитории:
$ apt-cache madison docker-compose-plugin docker-compose-plugin | 2.3.3~ubuntu-focal | https://download.docker.com/linux/ubuntu focal/stable arm64 Packages
б. Установите конкретную версию, используя строку версии из второго столбца, например,
2.3.3~ubuntu-focal
.$ sudo apt-get install docker-compose-plugin=<VERSION_STRING>
-
Убедитесь,что Docker Compose установлен правильно,проверив его версию.
$ docker compose version Docker Compose version v2.3.3
Установите двоичный файл вручную
В Linux вы можете загрузить двоичный файл Docker Compose со страницы выпуска репозитория Compose на GitHub и скопировать его в $HOME/.docker/cli-plugins
как docker-compose
. Следуйте инструкциям по ссылке, которые включают запуск команды curl
в вашем терминале для загрузки двоичных файлов. Эти пошаговые инструкции также приведены ниже.
-
Выполните эту команду,чтобы загрузить текущий стабильный выпуск 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
Эта команда устанавливает Compose для активного пользователя в каталог
$HOME
.Чтобы установить Docker Compose для всех пользователей вашей системы, замените~/.docker/cli-plugins
на/usr/local/lib/docker/cli-plugins
.Чтобы установить другую версию Compose, замените
v2.5.0
версией Compose, которую вы хотите использовать. -
Применить исполняемые разрешения к двоичному файлу:
$ chmod +x $DOCKER_CONFIG/cli-plugins/docker-compose
или если вы решили установить Compose для всех пользователей
$ sudo chmod +x /usr/local/lib/docker/cli-plugins/docker-compose
-
Проверьте установку.
$ docker compose version Docker Compose version v2.5.0
Установите Compose как отдельный двоичный файл в системах Linux
Вы можете использовать Compose как отдельный двоичный файл без установки Docker CLI.
- Выполните эту команду,чтобы загрузить текущий стабильный выпуск 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
Чтобы установить другую версию Compose, замените
v2.5.0
версией Compose, которую вы хотите использовать.
- Применить исполняемые разрешения к двоичному файлу:
$ sudo chmod +x /usr/local/bin/docker-compose
Note:
Если команда
docker-compose
не работает после установки, проверьте свой путь. Вы также можете создать символическую ссылку на/usr/bin
или любой другой каталог на вашем пути.For example:
$ sudo ln -s /usr/local/bin/docker-compose /usr/bin/docker-compose
-
Проверьте установку.
$ docker-compose Docker Compose version v2.5.0
Uninstallation
Чтобы удалить Docker Compose, если вы установили с помощью curl
:
$ rm $DOCKER_CONFIG/cli-plugins/docker-compose
или если вы решили установить Compose для всех пользователей
$ sudo rm /usr/local/lib/docker/cli-plugins/docker-compose
Получили ошибку «Разрешение отклонено»?
Если вы получаете сообщение об ошибке «Отказано в доступе» с помощью любого из вышеперечисленных методов, у вас, вероятно, нет необходимых прав для удаления
docker-compose
. Чтобы принудительно удалить, добавьтеsudo
к любой из приведенных выше команд и запустите снова.
Куда идти дальше
- User guide
- Getting Started
- Ссылка на командную строку
- Ссылка на композитный файл
- Примеры приложений с Compose
компоновка , оркестровка , установка , установка , докер , документация
Docker
20.10
-
Обеспечение доступа к GPU с помощью Compose
Службы Compose могут определять резервирование устройств GPU, если хост Docker содержит такие устройства. Демон настроен соответствующим образом.
-
Обзор Докерский состав
Ищете ссылку на файл Compose? Найдите последнюю версию здесь.
-
Состав сети
Эта страница относится к форматам файлов Compose версии 2 и выше.
-
Применение Состав в производстве
Когда вы определяете свое приложение с помощью разработки Compose, вы можете использовать это определение для запуска приложений в различных средах, таких как CI, промежуточная и производственная.
Docker Compose «is a tool for defining and running multi-container Docker applications. With Compose, you use a YAML file to configure your application’s services.» In this post, I will show how you can work with Docker Compose.
- Author
- Recent Posts
Josh’s primary focus is in Windows security and PowerShell automation. He is a GIAC Certified Windows Security Administrator (GCWN) and GIAC Certified Forensic Analyst (GCFA). You can reach Josh at MSAdministrator.com or on Twitter at @MS_dministrator.
Docker on Windows is now commonplace, and it comes with additional features you may not be familiar with. In my previous posts Install Docker and run containers on Windows and Create a Docker container on Windows with a Dockerfile, I showed you how to create a single container. In this article, I will walk you through how to use docker-compose to create and run multiple containers at once.
When you install the Docker Toolbox on Windows, you already have Docker, but you also get Docker Compose. Before we get started, make sure you have docker-compose installed on your machine by opening up a cmd prompt or PowerShell console, and run the following command:
docker-compose -v
If you did not receive an error, you are good to go. If you did, please make sure you look at my previous posts mentioned above.
During this article we are going to create a simple Microsoft IIS Server in one Docker container and have a second container that will test the first to make sure it is running. To do this, we first need to understand that Docker Compose uses a docker-compose.yml file to detail the specifics for our running containers.
Our docker-compose.yml file looks like this:
version: "3" services: web: build: context: ./iis-server dockerfile: Dockerfile test: build: context: ./iis-server-test dockerfile: Dockerfile command: powershell -executionpolicy bypass "c:tempiis-server-test.ps1" depends_on: - "web"
A Docker Compose file uses a YAML configuration syntax to build and manage our containers. Additionally, Docker has specified that a docker-compose.yml file can only have a few top-level keys, which define «sections» within our configuration file. For this example, we are only going to be focusing on version, services, and (later on) networks.
With this simple file, we will create two containers. One will be our actual IIS Server with a sample Home.html page. The second container will be a nanoserver that just runs and tests that our IIS Server is up and running (as expected). Now let’s break down our folder structure:
./docker-compose.yml ./iis-server/Dockerfile ./iis-server/Home.html ./iis-server-test/Dockerfile ./iis-server-test/iis-server-test.ps1
We have specified at the top of our docker-compose.yml file that we would like to use version 3 of the Docker Compose file reference. We could use additional versions if needed, but version 3 is the recommended one.
The second section, services, is where the fun stuff is! We are going to specify two separate containers (or services) in this section. First, we define our actual web application (site). We give it the simple name web, but it can be anything as long as it is a string with no spacing. We then specify that when we run docker-compose, we want it to build a brand-new image/container using the Dockerfile in the specified location (context). You can see this in the following code snippet:
services: # A "section" that specifies services web: # The name of our service build: # We specify that we want to build an image context: ./iis-server # The location (can be a URL) of our image dockerfile: Dockerfile # The name of the file to reference (could be any name)
Let’s take a look at what is in our ./iis-server/Dockerfile:
FROM microsoft/iis RUN mkdir c:myapp RUN powershell -NoProfile -Command Install-WindowsFeature NET-Framework-45-ASPNET; Install-WindowsFeature Web-Asp-Net45; Import-Module IISAdministration; New-IISSite -Name "MyApp" -PhysicalPath C:myapp -BindingInformation "*:8000:" EXPOSE 8000 ADD . /myapp
If you are curious about what this file means, please review my last post titled Create a Docker container on Windows with a Dockerfile. This goes into more detail about Dockerfiles. To summarize though, this Dockerfile will pull down an image from the official Docker repository named Microsoft/iis. It will then create a directory, install Windows Features, create a new IIS website, and add my Home.html to the container in our created directory (c:myappHome.html).
The ./iis-server/Home.html file contains just a simple HTML page:
<HTML> <HEAD> <TITLE>Using Docker Compose on Windows</TITLE> </HEAD> <BODY BGCOLOR="FFFFFF"> <H1>Using Docker Compose on Windows</H1> <H2><a href="https://4sysops.com">4sysops</a> is a great site!</H2> <H3>Josh Rickard</H3> You can reach me here:</br> <a href="https://twitter.com/MS_dministrator">Twitter</a></br> <a href="https://github.com/MSAdministrator">GitHub</a></br> <a href="https://4sysops.com/archives/author/msadministrator/">4sysops Author Page</a></br> <a href="https://msadministrator.com">MSAdministrator.com</a> </BODY> </HTML>
Next, let’s talk about our test image/container. The reason I’m creating this container is to simulate how you would have two (or more) containers running at the same time. Like we did with our web container, we specify a name: test.
test: build: context: ./iis-server-test dockerfile: Dockerfile command: powershell -executionpolicy bypass "c:tempiis-server-test.ps1" depends_on: - "web"
After we have given our container a name, we next specify that we want to build it. By the way, there are additional options when writing a docker-compose.yml file. For example, you could use the image tag. After specifying our build tag, we then pass in our context (or location) and our Dockerfile name.
Let’s look at what is inside both of these next files:
./iis-server-test/Dockerfile FROM microsoft/nanoserver:latest RUN mkdir c:temp ADD iis-server-test.ps1 c:/temp/ # The command: tag in our docker-compose.yml will run the following # after we have successfully built our container image # powershell -executionpolicy bypass c:tempiis-server-test.ps1 ./iis-server-test/ iis-server-test.ps1
try { If((Invoke-WebRequest web).StatusCode -eq 200) { Write-Output "IIS Server is alive!" } Else { Write-Output "IIS Server is not responding" } } catch { throw $Error[0]
Understanding the processing order for these two next two tags better explains how they work. First, let’s look at the depends_on tag. When we use this value, we are saying to create/build our first container web initially before this container (service). With this setting, we are now forcing the Docker Compose image to build web first before we do anything else. The command tag will only run after building web, which is exactly what we want.
Now that we understand our file structure and what our two containers are doing, all we need to do is run one of two simple commands. I prefer using the second one to see what is happening.
docker-compose up or docker-compose up -build
You should see the following when everything is up and running. Please note that the first time you run this, it may take a while. This is because we are downloading our images from the Docker repository, but after the first time, it should only take a few seconds to build.
Running docker compose up build should display the output above
Once you are satisfied your containers are working, you can do the following with them:
docker-compose down # stops resources up created docker-compose stop # use this to stop any running containers docker-compose kill # use this to stop any running containers forcefully docker-compose rm # removes stopped service containers
You can find all the files I referenced below:
Subscribe to 4sysops newsletter!
# ./docker-compose.yml version: "3" services: web: build: context: ./iis-server dockerfile: Dockerfile test: build: context: ./iis-server-test dockerfile: Dockerfile command: powershell -executionpolicy bypass "c:tempiis-server-test.ps1" depends_on: - "web" # ./iis-server/Dockerfile FROM microsoft/iis RUN mkdir c:myapp RUN powershell -NoProfile -Command Install-WindowsFeature NET-Framework-45-ASPNET; Install-WindowsFeature Web-Asp-Net45; Import-Module IISAdministration; New-IISSite -Name "MyApp" -PhysicalPath C:myapp -BindingInformation "*:8000:" EXPOSE 8000 ADD . /myapp
# ./iis-server/Home.html <HTML> <HEAD> <TITLE>Using Docker Compose on Windows</TITLE> </HEAD> <BODY BGCOLOR="FFFFFF"> <H1>Using Docker Compose on Windows</H1> <H2><a href="https://4sysops.com">4sysops</a> is a great site!</H2> <H3>Josh Rickard</H3> You can reach me here:</br> <a href="https://twitter.com/MS_dministrator">Twitter</a></br> <a href="https://github.com/MSAdministrator">GitHub</a></br> <a href="https://4sysops.com/archives/author/msadministrator/">4sysops Author Page</a></br> <a href="https://msadministrator.com">MSAdministrator.com</a> </BODY> </HTML>
# ./iis-server-test/Dockerfile FROM microsoft/nanoserver:latest RUN mkdir c:temp ADD iis-server-test.ps1 c:/temp/ # The commannd: tag in our docker-compose.yml will run the following # after we have successfully built our container image # powershell -executionpolicy bypass c:tempiis-server-test.ps1
# ./iis-server-test/iis-server-test.ps1 try { If((Invoke-WebRequest web).StatusCode -eq 200) { Write-Output "IIS Server is alive!" } Else { Write-Output "IIS Server is not responding" } } catch { throw $Error[0] }
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
Pick Your Operating System
You came here to ask, «how do I install Docker?» The answer can be straightforward if you’re willing to accept my way, but the steps differ based on which operating system is utilized. To make things more complicated, there are a few ways to install Docker on your OS that are largely based on preference. Today I’m going to walk you through my preferred method. This isn’t the only way, but I’ve found it to be the best way to get up and running with ease. For Ubuntu, we’ll be setting up the Docker Engine. For Windows and macOS, we’ll be using Docker Desktop.
Click on any of the links below to get started with installing Docker.
- Installing Docker on Ubuntu
- Installing Docker Compose on Ubuntu
- Automated Installation Script for Linux (Ubuntu)
- Installing Docker Desktop on macOS
- Installing Docker Desktop on Windows and WSL2
Installing Docker on Ubuntu
For Ubuntu, we’re going to install Docker Engine and Docker Compose using the Docker and Compose repositories. This also happens to be the recommended approach by Docker.
Follow Along on YouTube
Set Up
- Delete any prior versions if you had installed them.
sudo apt-get remove docker docker-engine docker.io containerd runc
- Update your system and install the necessary dependencies.
sudo apt-get update
sudo apt-get install apt-transport-https ca-certificates curl gnupg lsb-release
- For security purposes, add Docker’s official GPG key. Read more about that here.
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg
- Set up the stable repository.
echo
"deb [arch=amd64 signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
That’s quite a few steps, but if you followed along exactly, you should be ready to install Docker!
Installation
- Install the latest version of Docker, along with its dependencies.
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io
If you are running a later version of Ubuntu than what Docker has official builds for, you may get the following
error during this step.
Reading package lists... Done
Building dependency tree
Reading state information... Done
Package docker-ce is not available, but is referred to by another package.
This may mean that the package is missing, has been obsoleted, or
is only available from another source
E: Package 'docker-ce' has no installation candidate
E: Unable to locate package docker-ce-cli
E: Unable to locate package containerd.io
E: Couldn't find any package by glob 'containerd.io'
E: Couldn't find any package by regex 'containerd.io'
But don’t worry! We’ll just need to go install the latest version that is available. This can be done with the
following command INSTEAD of the one above.
sudo apt-get install -y docker.io
- Verify your install by running your first image.
sudo docker run hello-world
- Add your user as an admin to the Docker user group.
sudo usermod -aG docker $USER
Doing this last step means you no longer have to append sudo
to run Docker commands!
Uninstall
Fed up with Docker on your Ubuntu box? Uninstall and remove the configuration files with the following commands.
sudo apt-get purge docker-ce docker-ce-cli containerd.io
sudo rm -rf /var/lib/docker
sudo rm -rf /var/lib/containerd
Installing Docker Compose on Ubuntu
Install
You must have completed the installation of Docker Engine in the steps above before you can install Docker Compose. Assuming you’ve done so without any errors, let’s continue on!
- Download the stable release of Docker compose.
sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
Unlike the installation for Docker Engine where it automatically installs the latest version, Docker Compose has to have the version manually specified. At the time of writing, the latest version is 1.29.2
. The latest version can be viewed at the Compose repository release page on GitHub. Feel free to substitute the version in the command above as needed.
- Make the downloaded binary executable.
sudo chmod +x /usr/local/bin/docker-compose
Uninstall
To remove Docker Compose, utilize the following command (assuming you installed with curl
as we did above).
sudo rm /usr/local/bin/docker-compose
Automated Installation Script for Linux (Ubuntu)
An automated installation script can be found here. The contents are pasted below.
#!/bin/sh
echo "Starting docker community edition install..."
echo "Removing any old instances of docker and installing dependencies"
apt remove -y docker docker-engine docker.io containerd runc
apt update
apt install -y apt-transport-https ca-certificates curl gnupg-agent software-properties-common
echo "Dowloading latest docker and adding official GPG key"
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | apt-key add -
echo "Pulling the latest repository"
add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
apt update
echo "Installing docker community edition"
apt install -y docker-ce docker-ce-cli containerd.io
echo "Docker install completed, installing docker-compose"
echo "Dowloading docker-compose 1.29.2 - be sure to update to the latest stable"
curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o
/usr/local/bin/docker-compose
echo "Setting binary permissions"
chmod +x /usr/local/bin/docker-compose
echo “Docker and docker-compose install complete”
# Run docker as non-root user on Ubuntu
sudo usermod -aG docker $USER
Installing Docker Desktop on macOS
Note that Docker Desktop comes pre-equipped with Docker Engine, Docker Compose, Kubernetes, and a few other goodies.
Installation
Intel or Apple Silicon
Depending on which chipset you have on your Mac, you’ll need to install one of two versions of the Docker Desktop application. As this is a GUI application, there’s not much needed other than navigating to the correct site and installing the .dmg file. Just drag and drop the Docker icon into your Applications
directory.
Docker for macOS with Intel
The official link for installing Docker Desktop for macOS with an Intel chipset can be found here.
Apple Silicon
We’ll also need to take a few prior steps to get Docker Desktop running with Apple Silicon. Namely, you’ll need to install Rosetta 2 with the following command.
softwareupdate --install-rosetta
Afterward, install Docker Desktop for macOS with an Apple Silicon chipset from here.
Uninstall
Within the Docker Desktop toolbar item, navigate to the menu > Troubleshoot
> Uninstall
. See the screenshot below.
Installing Docker Desktop on Windows and WSL2
Note that Docker Desktop comes pre-equipped with Docker Engine, Docker Compose, Kubernetes, and a few other goodies. Firstly, you will need Docker Desktop even if you want Docker to only run on WSL. This is due to the sandboxed nature of WSL.
Installation
Windows
- First, you’ll need to ensure that virtualization is enabled for your CPU in the BIOS. This differs amongst motherboard manufacturers and chipsets (namely Intel and AMD). A quick Google search will get you going though.
- The executable for Docker Desktop for Windows can be found here. It can also be found on Docker Hub. Click the installer, follow the prompts and wait for it to be downloaded.
- During the process, be sure to allow the prompts for
Enable Hyper-V Windows Features
and theInstall required Windows components for WSL 2
.
WSL2
You’ll need to complete the steps for installing Docker Desktop on Windows before you can utilize WSL2. However, once you’ve completed it, feel free to come back to this section.
- Enable
Use the WSL2 based engine
in the Docker Desktop for Windows settings andApply & Restart
.
- Be sure that WSL2 is set as your default and current distribution.
Check the current WSL mode.
If not set to v2, upgrade your existing Linux.
wsl.exe --set-version (distro name) 2
Set v2 as the default version.
wsl.exe --set-default-version 2
- Navigate to
WSL Integration
and make sureEnable Integration with my default WSL distro
is checked.
Uninstall
Docker Desktop can be uninstalled from the Apps & features system settings. Just search for Docker Desktop
and select Uninstall
. Follow the prompts.
More Questions or Need Help
Be sure to check out the official documentation for Docker Engine and Docker Desktop and if you have more questions, feel free to send a message with any of the media icons below!