How to install docker compose
How to install docker compose
Install Docker Compose CLI plugin
Estimated reading time: 6 minutes
On this page you can find instructions on how to install the Compose plugin for Docker CLI on Linux and Windows Server operating systems.
Note that installing Docker Compose as a plugin requires Docker CLI.
Installing Compose on Linux systems
In this section, you can find various methods for installing Compose on Linux.
Installation methods
The following other methods are possible:
Using the automated convenience scripts (for testing and development environments). These scripts install Docker Engine and Docker CLI with the Compose plugin. For this route, go to the Docker Engine install page and follow the provided instructions. After installing Desktop for Linux, this is the recommended route.
Setting up Docker’s repository and using it to install Docker CLI Compose plugin. See the Install using the repository section on this page. This is the second best route.
Installing the Docker CLI Compose plugin manually. See the Install the plugin manually section on this page. Note that this option requires you to manage upgrades manually as well.
Install using the repository
These instructions assume you already have Docker Engine and Docker CLI installed and now want to install the Compose plugin. For other Linux installation methods see this summary.
If you have already set up the Docker repository jump to step 2.
Set up the repository. Go to the “Set up the repository” section of the chosen Linux distribution. found on the Docker Engine installation pages to check the instructions.
Update the apt package index, and install the latest version of Docker Compose:
Or, if using a different distro, use the equivalent package manager instructions.
Alternatively, to install a specific version of Compose CLI plugin:
a. List the versions available in your repo:
b. From the list obtained use the version string you can in the second column to specify the version you wish to install.
c. Install the selected version:
where is, for example, 2.3.3
Verify that Docker Compose is installed correctly by checking the version.
Install the plugin manually
These instructions assume you already have Docker Engine and Docker CLI installed and now want to install the Compose plugin.
Note as well this option requires you to manage upgrades manually. Whenever possible we recommend any of the other installation methods listed. For other Linux installation methods see this summary.
To download and install the Compose CLI plugin, run:
Apply executable permissions to the binary:
or, if you chose to install Compose for all users:
Test the installation.
Compose standalone: If you need to use Compose without installing the Docker CLI, the instructions for the standalone scenario are similar. Note the target folder for the binary’s installation is different as well as the compose syntax used with the plugin (space compose) or the standalone version (dash compose).
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:
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.
Run a PowerShell as an administrator. When asked if you want to allow this app to make changes to your device, click Yes in order to proceed with the installation.
GitHub now requires TLS1.2. In PowerShell, run the following:
Run the following command to download the latest release of Compose (v2.7.0):
To install a different version of Compose, substitute v2.7.0 with the version of Compose you want to use.
Get started with Docker Compose
Estimated reading time: 12 minutes
On this page you build a simple Python web application running on Docker Compose. The application uses the Flask framework and maintains a hit counter in Redis. While the sample uses Python, the concepts demonstrated here should be understandable even if you’re not familiar with it.
Prerequisites
Make sure you have already installed both Docker Engine and Docker Compose. You don’t need to install Python or Redis, as both are provided by Docker images.
Step 1: Setup
Define the application dependencies.
Create a directory for the project:
Create a file called app.py in your project directory and paste this in:
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 our 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 this in:
Step 2: Create a Dockerfile
In this step, you write a Dockerfile that builds 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:
This tells Docker to:
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:
Web service
Redis service
The redis service uses a public Redis image pulled from the Docker Hub registry.
Step 4: Build and run your app with Compose
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 you’re using Docker natively on Linux, Docker Desktop for Mac, or Docker Desktop for Windows, then the web app should now be listening on port 8000 on your Docker daemon host. Point your web browser to http://localhost:8000 to find the Hello World message. If this doesn’t resolve, you can also try http://127.0.0.1:8000.
You should see a message in your browser saying:
Refresh the page.
The number should increment.
Switch to another terminal window, and type docker image ls to list local images.
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:
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_ENV 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.
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.
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! :
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
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:
At this point, you have seen the basics of how Compose works.
Use Docker Compose
Estimated reading time: 12 minutes
Docker Compose is a tool that was developed to help define and share multi-container applications. With Compose, we can create a YAML file to define the services and with a single command, can spin everything up or tear it all down.
The big advantage of using Compose is you can define your application stack in a file, keep it at the root of your project repo (it’s now version controlled), and easily enable someone else to contribute to your project. Someone would only need to clone your repo and start the compose app. In fact, you might see quite a few projects on GitHub/GitLab doing exactly this now.
So, how do we get started?
Install Docker Compose
If you installed Docker Desktop/Toolbox for either Windows or Mac, you already have Docker Compose! Play-with-Docker instances already have Docker Compose installed as well. If you are on a Linux machine, you will need to install Docker Compose.
After installation, you should be able to run the following and see version information.
Create the Compose file
In the compose file, we’ll start off by defining the schema version. In most cases, it’s best to use the latest supported version. You can look at the Compose file reference for the current schema versions and the compatibility matrix.
Next, we’ll define the list of services (or containers) we want to run as part of our application.
And now, we’ll start migrating a service at a time into the compose file.
Define the app service
To remember, this was the command we were using to define our app container.
If you are using PowerShell then use this command:
First, let’s define the service entry and the image for the container. We can pick any name for the service. The name will automatically become a network alias, which will be useful when defining our MySQL service.
Typically, you will see the command close to the image definition, although there is no requirement on ordering. So, let’s go ahead and move that into our file.
One advantage of Docker Compose volume definitions is we can use relative paths from the current directory.
Finally, we need to migrate the environment variable definitions using the environment key.
Define the MySQL service
Now, it’s time to define the MySQL service. The command that we used for that container was the following:
If you are using PowerShell then use this command:
We will first define the new service and name it mysql so it automatically gets the network alias. We’ll go ahead and specify the image to use as well.
Finally, we only need to specify the environment variables.
At this point, our complete docker-compose.yml should look like this:
Run the application stack
Now that we have our docker-compose.yml file, we can start it up!
When we run this, we should see output like this:
You’ll notice that the volume was created as well as a network! By default, Docker Compose automatically creates a network specifically for the application stack (which is why we didn’t define one in the compose file).
If you have run the command already, you’ll see output that looks like this:
Tip: Waiting for the DB before starting the app
When the app is starting up, it actually sits and waits for MySQL to be up and ready before trying to connect to it. Docker doesn’t have any built-in support to wait for another container to be fully up, running, and ready before starting another container. For Node-based projects, you can use the wait-port dependency. Similar projects exist for other languages/frameworks.
At this point, you should be able to open your app and see it running. And hey! We’re down to a single command!
See the app stack in Docker Dashboard
If we look at the Docker Dashboard, we’ll see that there is a group named app. This is the “project name” from Docker Compose and used to group the containers together. By default, the project name is simply the name of the directory that the docker-compose.yml was located in.
Tear it all down
When you’re ready to tear it all down, simply run docker-compose down or hit the trash can on the Docker Dashboard for the entire app. The containers will stop and the network will be removed.
The Docker Dashboard does not remove volumes when you delete the app stack.
Once torn down, you can switch to another project, run docker-compose up and be ready to contribute to that project! It really doesn’t get much simpler than that!
Recap
In this section, we learned about Docker Compose and how it helps us dramatically simplify the defining and sharing of multi-service applications. We created a Compose file by translating the commands we were using into the appropriate compose format.
At this point, we’re starting to wrap up the tutorial. However, there are a few best practices about image building we want to cover, as there is a big issue with the Dockerfile we’ve been using. So, let’s take a look!
How To Install and Use Docker Compose on Ubuntu 20.04
Introduction
Docker simplifies the process of managing application processes in containers. While containers are similar to virtual machines in certain ways, they are more lightweight and resource-friendly. This allows developers to break down an application environment into multiple isolated services.
For applications depending on several services, orchestrating all the containers to start up, communicate, and shut down together can quickly become unwieldy. Docker Compose is a tool that allows you to run multi-container application environments based on definitions set in a YAML file. It uses service definitions to build fully customizable environments with multiple containers that can share networks and data volumes.
In this guide, you’ll demonstrate how to install Docker Compose on an Ubuntu 20.04 server and how to get started using this tool.
Prerequisites
To follow this article, you will need:
Step 1 — Installing Docker Compose
To make sure you obtain the most updated stable version of Docker Compose, you’ll download this software from its official Github repository.
Next, set the correct permissions so that the docker-compose command is executable:
To verify that the installation was successful, you can run:
You’ll see output similar to this:
Docker Compose is now successfully installed on your system. In the next section, you’ll see how to set up a docker-compose.yml file and get a containerized environment up and running with this tool.
Step 2 — Setting Up a docker-compose.yml File
To demonstrate how to set up a docker-compose.yml file and work with Docker Compose, you’ll create a web server environment using the official Nginx image from Docker Hub, the public Docker registry. This containerized environment will serve a single static HTML file.
Start off by creating a new directory in your home folder, and then moving into it:
In this directory, set up an application folder to serve as the document root for your Nginx environment:
Using your preferred text editor, create a new index.html file within the app folder:
Place the following content into this file:
Next, create the docker-compose.yml file:
Insert the following content in your docker-compose.yml file:
The docker-compose.yml file typically starts off with the version definition. This will tell Docker Compose which configuration version you’re using.
The volumes directive will create a shared volume between the host machine and the container. This will share the local app folder with the container, and the volume will be located at /usr/share/nginx/html inside the container, which will then overwrite the default document root for Nginx.
Save and close the file.
You have set up a demo page and a docker-compose.yml file to create a containerized web server environment that will serve it. In the next step, you’ll bring this environment up with Docker Compose.
Step 3 — Running Docker Compose
With the docker-compose.yml file in place, you can now execute Docker Compose to bring your environment up. The following command will download the necessary Docker images, create a container for the web service, and run the containerized environment in background mode:
Docker Compose will first look for the defined image on your local system, and if it can’t locate the image it will download the image from Docker Hub. You’ll see output like this:
Your environment is now up and running in the background. To verify that the container is active, you can run:
This command will show you information about the running containers and their state, as well as any port redirections currently in place:
You can now access the demo application by pointing your browser to either localhost:8000 if you are running this demo on your local machine, or your_server_domain_or_IP :8000 if you are running this demo on a remote server.
You’ll see a page like this:
The shared volume you’ve set up within the docker-compose.yml file keeps your app folder files in sync with the container’s document root. If you make any changes to the index.html file, they will be automatically picked up by the container and thus reflected on your browser when you reload the page.
In the next step, you’ll see how to manage your containerized environment with Docker Compose commands.
Step 4 — Getting Familiar with Docker Compose Commands
To check the logs produced by your Nginx container, you can use the logs command:
You’ll see output similar to this:
If you want to pause the environment execution without changing the current state of your containers, you can use:
To resume execution after issuing a pause:
The stop command will terminate the container execution, but it won’t destroy any data associated with your containers:
If you want to remove the containers, networks, and volumes associated with this containerized environment, use the down command:
In case you want to also remove the base image from your system, you can use:
Note: Please refer to our guide on How to Install and Use Docker for a more detailed reference on Docker commands.
Conclusion
In this guide, you’ve seen how to install Docker Compose and set up a containerized environment based on an Nginx web server image. You’ve also seen how to manage this environment using Compose commands.
For a complete reference of all available docker-compose commands, check the official documentation.
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.
Установка Docker Compose в Ubuntu 18.04
Введение
Docker — это отличный инструмент для автоматизации развертывания приложений Linux внутри контейнеров ПО, но для использования всех его возможностей необходимо, чтобы каждый компонент приложения запускался в своем собственном контейнере. Для сложных приложений с большим количеством компонентов, организация совместных запуска, коммуникации и остановки всех контейнеров может быстро стать очень непростой и запутанной задачей.
Сообщество Docker предложило популярное решение, которое называется Fig и позволяет вам использовать единый файл YAML для организации совместной работы всех ваших контейнеров и конфигураций. Оно стало настолько популярным, что команда Docker решила создать Docker Compose на базе исходного кода Fig, который в настоящее является устаревшим инструментом и не поддерживается. Docker Compose упрощает организацию процессов контейнеров Docker, включая запуск, остановку и настройку связей и томов внутри контейнера.
В этом обучающем модуле мы расскажем вам, как установить последнюю версию Docker Compose для управления приложениями с несколькими контейнерами.
Предварительные требования
Для выполнения этого руководства вам потребуется сервер Ubuntu 18.04 и следующее:
После установки всех необходимых компонентов мы сможем двигаться дальше.
Примечание. Хотя в предварительных условиях содержатся указания по установке Docker в Ubuntu 18.04 команды docker в этой статье должны работать в других операционных системах, где установлен Docker.
Шаг 1 — Установка Docker Compose
Мы проверим текущую версию и при необходимости обновим ее с помощью следующей команды:
После этого мы настроим разрешения:
Затем мы проверим, что установка прошла успешно, с помощью проверки версии:
В результате должна быть выведена установленная нами версия:
Теперь, когда мы установили Docker Compose, мы можем запустить пример «Hello World».
Шаг 2 — Запуск контейнера с помощью Docker Compose
В общедоступном реестре Docker, Docker Hub, содержится образ Hello World, используемый для демонстрации и тестирования. Он демонстрирует минимальные параметры конфигурации, необходимые для запуска контейнера с помощью Docker Compose: файл YAML, вызывающий отдельный образ:
Сначала мы создадим директорию для файла YAML и перейдем в нее:
Затем мы создадим в этой директории файл YAML:
Поместите в файл следующие данные, сохраните его и закройте текстовый редактор:
Мы можем вручную просмотреть образы в нашей системе с помощью команды docker images :
Когда локальные образы отсутствуют, будут отображены только заголовки столбцов:
Далее, находясь в директории
При первом запуске команды, если локальный образ с именем hello-world отсутствует, Docker Compose будет загружать его из открытого репозитория Docker Hub:
После загрузки образа docker-compose создает контейнер, помещает в него и запускает программу hello, что, в свою очередь, подтверждает, что установка, выполнена успешно:
Затем программа отображает объяснение того, что она сделала:
Контейнеры Docker продолжают работать, пока команда остается активной, поэтому после завершения работы hello контейнер останавливается. Следовательно, когда мы просматриваем активные процессы, заголовки столбцов будут появляться, но контейнер hello-world не будет появляться в списке, поскольку он не запущен.
Так мы можем получить информацию, которая нам потребуется для удаления контейнера, когда мы закончим работать с ним.
Шаг 3 — Удаление образа (необязательно)
После удаления всех контейнеров, которые содержат образ, мы можем удалить образ:
Заключение
Мы установили Docker Compose, протестировали установку, запустив пример Hello World, и удалили тестовый образ и контейнер.
Хотя пример Hello World использовался для подтверждения корректности установки, простая конфигурация не демонстрирует одно из главных преимуществ Docker Compose — возможность одновременного запуска группы контейнеров Docker. Чтобы увидеть силу Docker Compose в действии, вы можете ознакомиться с практическим примером в статье Настройка среды непрерывного интеграционного тестирования с помощью Docker и Docker Compose в Ubuntu 16.04 (обратите внимание, что эта статья для Ubuntu 16.04, а не 18.04)
Want to learn more? Join the DigitalOcean Community!
Join our DigitalOcean community of over a million developers for free! Get help and share knowledge in our Questions & Answers section, find tutorials and tools that will help you grow as a developer and scale your project or business, and subscribe to topics of interest.