Overview of docker-compose CLI
This page provides the usage information for the docker-compose Command.
Command options overview and help
You can also see this information by running docker-compose —help from the command line.
You can use Docker Compose binary, docker-compose [-f <arg>. ] [options] [COMMAND] [ARGS. ] , to build and manage multiple services in Docker containers.
Use -f to specify name and path of one or more Compose files
Use the -f flag to specify the location of a Compose configuration file.
Specifying multiple Compose files
You can supply multiple -f configuration files. When you supply multiple files, Compose combines them into a single configuration. Compose builds the configuration in the order you supply the files. Subsequent files override and add to their predecessors.
For example, consider this command line:
The docker-compose.yml file might specify a webapp service.
If the docker-compose.admin.yml also specifies this same service, any matching fields override the previous file. New values, add to the webapp service configuration.
Use a -f with — (dash) as the filename to read the configuration from stdin . When stdin is used all paths in the configuration are relative to the current working directory.
The -f flag is optional. If you don’t provide this flag on the command line, Compose traverses the working directory and its parent directories looking for a docker-compose.yml and a docker-compose.override.yml file. You must supply at least the docker-compose.yml file. If both files are present on the same directory level, Compose combines the two files into a single configuration.
The configuration in the docker-compose.override.yml file is applied over and in addition to the values in the docker-compose.yml file.
Specifying a path to a single Compose file
You can use the -f flag to specify a path to a Compose file that is not located in the current directory, either from the command line or by setting up a COMPOSE_FILE environment variable in your shell or in an environment file.
For an example of using the -f option at the command line, suppose you are running the Compose Rails sample, and have a docker-compose.yml file in a directory called sandbox/rails . You can use a command like docker-compose pull to get the postgres image for the db service from anywhere by using the -f flag as follows: docker-compose -f
/sandbox/rails/docker-compose.yml pull db
Here’s the full example:
Use -p to specify a project name
Each configuration has a project name. If you supply a -p flag, you can specify a project name. If you don’t specify the flag, Compose uses the current directory name. See also the COMPOSE_PROJECT_NAME environment variable.
Set up environment variables
You can set environment variables for various docker-compose options, including the -f and -p flags.
For example, the COMPOSE_FILE environment variable relates to the -f flag, and COMPOSE_PROJECT_NAME environment variable relates to the -p flag.
Name already in use
docs / compose / reference / index.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
This page provides the usage information for the docker compose Command.
Important
The new Compose V2, which supports the compose command as part of the Docker CLI, is now available.
Compose V2 integrates compose functions into the Docker platform, continuing to support most of the previous docker-compose features and flags. You can run Compose V2 by replacing the hyphen ( — ) with a space, using docker compose , instead of docker-compose .
For more information about Docker Compose V2 GA, see the blog post Announcing Compose V2 General Availability<: target rel="noopener" class >.
Command options overview and help
You can also see this information by running docker compose —help from the command line.
You can use Docker Compose binary, docker compose [-f <arg>. ] [options] [COMMAND] [ARGS. ] , to build and manage multiple services in Docker containers.
Use -f to specify name and path of one or more Compose files
Use the -f flag to specify the location of a Compose configuration file.
Specifying multiple Compose files
You can supply multiple -f configuration files. When you supply multiple files, Compose combines them into a single configuration. Compose builds the configuration in the order you supply the files. Subsequent files override and add to their predecessors.
For example, consider this command line:
The docker-compose.yml file might specify a webapp service.
If the docker-compose.admin.yml also specifies this same service, any matching fields override the previous file. New values, add to the webapp service configuration.
When you use multiple Compose files, all paths in the files are relative to the first configuration file specified with -f . You can use the —project-directory option to override this base path.
Use a -f with — (dash) as the filename to read the configuration from stdin . When stdin is used all paths in the configuration are relative to the current working directory.
The -f flag is optional. If you don’t provide this flag on the command line, Compose traverses the working directory and its parent directories looking for a docker-compose.yml and a docker-compose.override.yml file. You must supply at least the docker-compose.yml file. If both files are present on the same directory level, Compose combines the two files into a single configuration.
The configuration in the docker-compose.override.yml file is applied over and in addition to the values in the docker-compose.yml file.
Specifying a path to a single Compose file
You can use the -f flag to specify a path to a Compose file that is not located in the current directory, either from the command line or by setting up a COMPOSE_FILE environment variable in your shell or in an environment file.
For an example of using the -f option at the command line, suppose you are running the Compose Rails sample, and have a docker-compose.yml file in a directory called sandbox/rails . You can use a command like docker compose pull to get the postgres image for the db service from anywhere by using the -f flag as follows: docker compose -f
/sandbox/rails/docker-compose.yml pull db
Here’s the full example:
Use -p to specify a project name
Each configuration has a project name. If you supply a -p flag, you can specify a project name. If you don’t specify the flag, Compose uses the current directory name. See also the COMPOSE_PROJECT_NAME environment variable.
Use —profile to specify one or more active profiles
Calling docker compose —profile frontend up will start the services with the profile frontend and services without specified profiles. You can also enable multiple profiles, e.g. with docker compose —profile frontend —profile debug up the profiles frontend and debug will be enabled.
Set up environment variables
You can set environment variables for various docker compose options, including the -f and -p flags.
For example, the COMPOSE_FILE environment variable relates to the -f flag, and COMPOSE_PROJECT_NAME environment variable relates to the -p flag.
How to check the docker-compose file version?
I would like to make sure that I’m using version 3 of the compose file format. However, on https://docs.docker.com/compose/compose-file/ I was not able to find out how to do this.
My Docker version is 17.04.0-ce, build 4845c56 , and my Docker-Compose version is docker-compose version 1.9.0, build 2585387 . I’m not sure since when version 3 of the compose file format was introduced, however. How can I find this out?
2 Answers 2
It’s on your docker-compose.yml file. First parameter is Docker Compose version.
Docker Compose version file 3 was introduced in release 1.10.0 of Docker Compose and 1.13.0 release of Docker Engine.
Here you can see release notes for Docker Compose 1.10.0 which introduces version file 3: https://github.com/docker/compose/releases/tag/1.10.0
![]()
The docker compose version 3 syntax requires docker version 1.13 and docker-compose version 1.10 (see the release notes). See the release notes for the version compatibility matrix and upgrade instructions.
Note that the version 3 syntax is designed for docker swarm mode, and it was first supported with the docker stack deploy in docker release 1.13. There’s not much reason to upgrade to the version 3 syntax if you are still using docker-compose itself.
See also the compose file versioning page that describes the differences between the different yml versions.
-
The Overflow Blog
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.3.43278
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Докеризация стека LEMP под Ubuntu c помощью Compose
Docker-Compose — это инструмент командной строки для определения и для управления несколькими мульти-контейнерами приложений Docker. Фактически, Compose является скриптом на языке Python, может быть легко установлен с помощью команды pip (это команда для установки программного обеспечения Python из репозитория пакетов Python). Благодаря Compose можно запускать несколько Docker-контейнеров с помощью одной команды. Это позволит в создать контейнер как службу, что прекрасно подходит как для разработки и тестирования, так и для реальных задач.
С 2021 года статья потеряла актуальность после выхода свежих версий дистрибутива Ubuntu 18.04, Ubuntu 20.04 и т.д. Не рекомендуется действовать по данной методике.
Разберёмся, как использовать Docker-Compose для создания стека LEMP. Принято считать, что LEMP — это Linux+Nginx+MySQL+PHP. Каждый компонент будет запущен в собственном контейнере Docker.
- контейнер Nginx,
- PHP-контейнер,
- phpMYADMIN контейнер
- контейнер MySQL / MariaDB.
- Ubuntu сервер 16.04
- Root-привилегии
Шаг 1 — Установить Docker
На этом этапе надо установить Docker. Docker доступен в репозитории Ubuntu, но прежде нужно обновить всю систему:
Установите последнюю версию Docker из репозитория Ubuntu.
Запустите Докер и включите его в автозагрузку:
Теперь служба Docker запущена. Далее, вы можете попробовать запустить Докер с помощью тестовой команды:
В результате выполнения будет видно приветствие Docker в консоли
Шаг 2 – Установите Docker-Compose
На первом этапе был установлен Docker. Теперь следует установить Docker-Compose. Нам необходим python-pip для установки compose, поэтому следует установить python и python-pip с помощью apt:
Когда всё будет установлено, установите Docker-Compose таким образом:
Теперь проверим версию Docker-Compose :
Если Docker-Compose установлен, в консоли будет виден отчёт о номере версии.
Шаг 3 — Создание и настройка среды Docker
На этом этапе нужно будет настроить среду Docker-Compose. Для этого мы используем нового пользователя (не root ), поэтому нужно создать такого пользователя. Добавим нового пользователя с именем «robocop» (лучше выбрать собственное имя пользователя):
Добавьте нового пользователя в группу «Docker» и перезапустите Докер.
Теперь пользователь « robocop » может использовать Docker без sudo. Далее из-под супер-пользователя войдём в « robocop » через su:
Создайте новый каталог для создания среды Compose.
Это среда Docker-Compose, все файлы, которые будут находиться в контейнере Docker, должны располагаться в этом каталоге. Когда мы используем Docker-Compose, нам нужен файл .yml с именем «Docker-Compose.yml». В папке ‘lemp-compose’, создайте новые каталоги и файл «Docker -Compose.yml»:
- logs: Каталог журналов Nginx
- Nginx: содержит конфигурационные файлы Nginx, например файлы виртуальных хостов и т.д.
- public: каталог для веб-файлов, index.html и PHP
- DB-data: каталог базы данных.
Создаём файлы журналов error.log и access.log в каталоге «журналов»
Создаём новый файл конфигурации, который будет являться конфигурацией виртуального хоста nginx в папке «nginx»:
Используем следующие настройки:
Сохраните файл. Создайте новый файл index.html и PHP-файл в папке «public».
Теперь можно посмотреть структуру каталога с помощью команды:
Шаг 4 — Настройка файла doker-compose.yml
В предыдущем этапе мы создали каталоги и файлы, необходимые для наших контейнеров. На этом этапе нужно отредактировать файл «doker-compose.yml». В файле«doker-compose.yml» следует определить службы для стека LEMP, базовые образы для каждого контейнера, а также тома docker.
Заходим из-под пользователя « robocop » и правим файл «doker-compose.yml»:
Определим службу Nginx, для чего вставляем данную конфигурацию:
В этой конфигурации мы уже определили:
- nginx: имя службы
- image: используем «bitnami/nginx»
- ports: открыли контейнерный порт 80 на порт хоста 80
- links: увязали контейнер «nginx» и контейнер «phpfpm»
- volumes: монтируеv местные каталоги для контейнера (журнал, конфигурацию виртуального и корневой веб-каталог)
Определим службу PHP-fpm. Вставим настройки ниже блока Nginx:
Здесь мы задаём:
- phpfpm: определили имя службы
- image: определили базовый образ для службы phpfpm с образом «bitnami/php-fpm»
- ports: Запустим PHP-fpm на TCP-порту 9000 и прокинем его на порт 9000 хоста.
- volumes: монтируем корневую папку «public» к папке «myapps» в контейнере.
Определение службы MySQL
В третьем блоке следует вставить конфигурацию для контейнера СУБД MariaDB:
В данном случае мы задаём:
- MySQL: как имя службы
- image: контейнер основан на образе «mariadb»
- ports: контейнер службы использует порт 3306 для подключения MySQL, пробрасываем его на порт 3306 хоста.
- volumes: db-data
- environment: Необходимо определить переменную среды «MYSQL_ROOT_PASSWORD», задав пароль root
Настройка служб PHPMyAdmin
Для последнего блока вставьте конфигурацию ниже:
Мы используем Docker-образ «phpmyadmin», сопоставляем порт контейнера 80 и порт 8080 на хосте, связываем контейнер с контейнером mariadb, устанавливаем перезагрузку в always, определяем некоторые переменные среды, включая «PMA_HOST».
Шаг 5 – Запуск doker-compose
Теперь мы готовы запустить doker-compose.
Обратите внимание, что для запуска doker-compose, вы должны будете находиться в директории проекта doker-compose и определённо иметь файл YML с конфигурацией.
Выполните команду ниже, чтобы запустить стек LEMP:
Ключ -d позволяет выполнить запуск в фоновом режиме.
Новые контейнеры созданы, что можно проверить их с помощью следующей команды:
Мы должны увидеть, что созданы четыре контейнера с Nginx, PHP-FPM, MariaDB и PHPMyAdmin.
Шаг 6 — тестирование
Проверка портов, которые используются docker-proxy на хосте
Далее мы можем увидеть, что порт 80 задействован для контейнера Nginx, порт 3306 для контейнера MariaDB, порт 9000 для PHP-FPM, и порт 8080 для контейнера PhpMyAdmin. Обращение к порту 80 из веб-браузера позволит увидеть корневой файл index.html.
Убедитесь, что PHP-FPM работает, обратившись к странице /info.php на сервере.
Из командной строки можно получить доступ к контейнеру MySQL.
Можно создать новую базу данных:
Контейнер MariaDB живой, и мы создали новую базу данных ‘robocop_db’.
Далее, для доступа к PHPMyAdmin обратимся к порту 8080 в браузере.
Откроется страница для входа в phpMyAdmin, можно будет войти как root, с паролем » robocop 123 » . Вы будете автоматически подключены к контейнеру mysql, который был определен в переменной PMA_HOST.
Готово! LEMP-stack работает под управлением docker-Compose, состоящей из четырех контейнеров.