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 как контейнера, т.к. считаю его неудобным.
Docker Compose lets you run complex applications using a single command. This means that containers can be deployed faster and more efficiently. Our tutorial guides you through the Docker Compose Windows installation step by step.
What are the requirements of Docker Compose on Windows?
Docker Compose is an integral part of Docker Desktop for Windows. To use the standalone version of Docker Compose, the following requirements must be met:
- Docker Engine: Compose is an extension of Docker Engine. So you need to have the Docker Server and Client binaries installed.
- Operating System: Windows, administrator rights
How to install Docker Compose on Windows step by step
To install and use Docker Compose, Docker Daemon and Docker Client should be running on your Windows server. Before getting started it’s best to ensure that the Docker service is running error-free.
Step 1: Start PowerShell
First, launch PowerShell using your administrator rights. Confirm “Yes” to allow the app to make changes to your device.
Step 2: Set up TLS security protocol
GitHub requires TLS1.2 as the default security protocol. Run the following command in Windows PowerShell:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
powershell
Step 3: Download and install Docker Compose
Download the latest version of Compose (v2.17.2) from GitHub:
Start-BitsTransfer -Source "https://github.com/docker/compose/releases/download/v2.17.2/docker-compose-Windows-x86_64.exe" -Destination $Env:ProgramFiles\Docker\docker-compose.exe
powershell
To install a different version, simply replace v2.17.2
in the target address with the desired version number.
Step 3: Test Docker Compose
Check if the installation was successful by displaying the current version of Compose:
docker compose version
powershell
You should see the following output:
Last Updated :
24 May, 2024
Docker is a powerful Container platform that allows you to create containers where you can run, deploy, and develop applications without worrying about different dependencies, services, and limitations of the operating system. The best part is the isolation of the container so you can use this container on different platforms. Now let’s talk about the ecosystem of Docker.
- Docker Engine: It is the core part of Docker which handles the different functionalities of Docker.
- Docker Compose: It is a tool which is provided by Docker used to maintain multi-container-based applications.
- Docker Hub: it is a cloud platform where all the Docker images are stored similar to Git Hub.
What Is Docker Compose?
Docker Compose is a multi-container-based application tool that will allow you to contain all the configurations and requirements for docker image building in a single YAML file. It is the single place where you can see what kind of services are required for the particular image and then you can manage and execute the configurations with commands. These are the basic details mentioned in the Docker-Compose file.
- Services and Dependencies
- Docker Networking
- Docker Port-mapping
- Docker Volumes
- Docker Environment Variables etc…
How To Install Docker Desktop On Windows
Step 1: Download The Docker Desktop For Windows
- Go to official website of Docker and search Docker Desktop Download.
- Click on the «Docker Desktop For Windows» button.
Step 2: Install Docker Desktop
- Run the downloaded software through clicking on Install option.
- Follow the Installation Wizard instructions.
- During the Installation, make sure to enable ‘Hyper-V windows Features’ option is selected.
Step 3: Run Docker Desktop
- After the installation of Docker Desktop has done successfully. Close the Applications and open it again from the Start Menu.
Step 4: Enabling WSL 2 (Windows Subsystem For Linux)
- Docker Desktop uses WSL2 as its default backend. Ensure that you have WSL2 installed.
- Ensure to follow the instructions provided by Docker Desktop to enable WSL2 during the first run.
- When your system restart this windows occurs on your screen. Finally the setup of the Docker Desktop has done successfully.
Step 5: Verifying Installation
- Open your command prompt or power shell.
- Run the following command to check the Docker CLI installation.
docker --version
- Run the following command to verify the docker can pull and run the containers.
docker pull ubuntu:latest
How to Install Compose standalone on Windows
Step 1: Open Powershell
- Open Powershell on your windows system
- and run as an administrator
Step 2: Run the following command
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Step 3 : Now run this command to download specific docker-compose version
Start-BitsTransfer -Source "https://github.com/docker/compose/releases/download/v2.24.5/docker-compose.exe" -Destination $Env:Program Files\Docker\docker-compose.exe
- in the -Source section you can specify the Docker-Compose version which you want to intsall.
- in the -Destination section you can specify the location where you download the file.
- after running this command wait until the downloading process is not completed.
Step 5: Verifying Installation
- After finishing the downloading process.
- Open your command prompt or power shell.
- Run the following command to check the Docker CLI installation.
docker --version
Docker Compose Tips And Tricks For Windows
Use Verified Images
Always use Verified Images it is a best practice which will give you confidence about the authenticity of an Docker Image. Verfied Images are well maintained and easy to understand because all process is well documented. The verified images is updated time to time and fixes bugs and issues related to Images. before using the image you can check on the Dockerhub and use only those images who have official tag and associated with well known organization.
- You can also use Docker inspect command to check the image is signed or not. this is the syntax
docker trust inspect IMAGE[:TAG] [IMAGE[:TAG]...]
Tip : you can check how does Docker Content Trust works and how it verify the images and if you want so you can also use it to verify your own Docker images.
Versioning
Mention the current Docker Compose version in the starting in your Docker File. so there might be less chance of getting the issues with the version. it is the best practice to use latest version and if you want so you can also specify the which O.S you use if you use light weight Os like alpine it will give you advantage and provide efficiency in fetching and pulling the request.
Efficient Catching In Layers
As we know that Time is everything. by following some simple techniques we can save the time, the steps in dockerfile is called as layers in docker compose. and when you run command for building the image so it go through each step. and docker temporarily store the layers which are rebuild. so the next time you rebuild the image so it will not taking too much time and redownload it. when you run the build command. it will speed up the process. The following are the simple techniques you follow for efficient catching:
- Take care of ordering of Layers.
- Use multi stage builds
- Take care of what files you are copying in Docker file
- If you want so can add large files to Dockerignore file i.e nodemodules.
Use Docker Volumes
Docker volumes are very useful feature. by using this feature you can share your data from one container to another container. you can mount your data to another container so if somehow your container are stopped are destroyed so your data is not destroyed with the container. and that’s how you saved your data. if you want so you can also create your custom volumes.
Enviroment Variables
Enviroment variables are the one of the most important factor of Docker File. Make sure to provide the Enviroment variable name according to it’s work which is readable and explain it’s related work and provide default values which will helps in different scenarios.
Special Tricks For Usage Of Docker Compose For Windows
- You can use some special Editors/Extentions which will highlight Docker syntax and it helps you to grab the right options.
- Docker required a large storage in your system so sometimes it will creating issues with low-end pc’s so you can use some alternatives of it or try to clear your storage time to time.
- make sure that the file you mentioned in docker compose file are in the same directory/project otherwise it will not getting access to it.
- You can explore the availability of creating your own network on your docker file which will give you the isolation which you required for better security.
- You can use caching techniques for saving the data. which will help you to reduce the image loading time.
Conclusion
Docker compose is a powerful tool for managing multi-container-based applications. by using Docker compose you can effectively manage what kind dependencies, servers , and networks etc required for your container. in this article we go through how we can install Docker Desktop to our system and what is Docker compose and some special tips and tricks how we can use Docker compose effectively.
How to Install Docker Compose on Windows Server 2016 / 2019 / 2022. In this tutorial we will introduce Docker with it’s main advantages then move onto installation phase on Windows server.
Imagine a situation where you want to use two containers in a single system. In such a case, building, running and connecting the container from separate Docker files can be very difficult. It will take a lot of your time and even affect your productivity. That is why you need to consider Docker Compose.
What Is Docker Compose?
A Docker tool used for defining and running multi container Docker applications. Every container running on this platform is isolated. However, they can interact with each other as and when needed.
Moreover, Docker Compose files are written in an easy scripting language called YAML. An XML based language whose acronym is Yet Another Markup Language. What makes this tool highly popular among users is its feature of providing access to activate all the services using a single command.
In a nutshell, instead of containing all the services in a huge container, Docker Compose splits them up into individually manageable containers. It proves to be highly advantageous both for building and deployment as you can manage all of them in distinct codebases.
You can use a Docker Compose in three processes:
- Firstly to build component images using Docker Files, or get them from the libraries.
- Secondly to determine every component service in the “docker-compose.yml” files.
- Lastly to run them together via “docker-compose” CLI.
Docker Compose Features
Docker Compose constitutes the following features:
- Supporting Environment Variables -here the Docker Compose enables you to customize containers based on different environments or users by adding variables in the Docker Compose files. This way, you tend to get more flexibility while setting up containers with Compose. Interestingly you can use this feature for almost anything from securely providing passwords to specifying a software version.
- Reusing Existing Containers – where Docker Compose recreates containers that have changed since the last run. If it notices no changes, it re uses the existing container. It relies on the ability of the software to cache container configuration, thereby allowing you to set up your services faster.
- Volume Data Preservation – with Docker Compose it saves data used by the services. You do not have to worry about losing data created in containers. If you have containers from the previous run, it will find them and copy their volumes to the new run.
Advantages Of Docker Compose
Some of the crucial benefits of Docker Compose are as follows:
- Immediate And Straightforward Configurations – Since Docker Compose uses YAML scripts and environment variables, configuring and modifying application services is very effortless.
- Provides Portability And CI/CD Support – All the services are defined inside of the Docker Compose files, making it effortless for developers to access and share the entire configuration. If they pull the YAML files and source code, an environment can be launched in just a matter of minutes. This way, setting and enabling CI/CD pipelines is very easy.
- Internal Communication Security – With the help of Docker Compose, you can create a network for all the services to share. It adds an extra security layer for the app as the services cannot be accessed externally.
- Using Resources Efficiently -by using Docker Compose, you can host multiple environments on one host. When you run everything on a single piece of hardware, you save a lot of resources. This way, it can cache configuration and re use existing containers contributing to resource efficiency.
Follow this post to show you how to install Docker Compose on Windows Server 2016, 2019 and 2022.
Install Docker Compose on Windows Server 2016, 2019 and 2022
Prerequisites
- A server running Windows Server 2016, 2019 or 2022 operating system along with RDP access.
- A user with administrative privileges.
- Minimum 4 GB of RAM with 2 Cores CPU.
Verify Docker Installation
Before installing Docker Compose, you will need to make sure Docker is installed on your Windows server. To verify the Docker installation, open your Windows command prompt and run the following command:
If Docker is installed on your system, you will get the following information:
Client: Docker Engine - Enterprise
Version: 19.03.2
API version: 1.40
Go version: go1.12.8
Git commit: c92ab06ed9
Built: 09/03/2019 16:38:11
OS/Arch: windows/amd64
Experimental: false
Server: Docker Engine - Enterprise
Engine:
Version: 19.03.2
API version: 1.40 (minimum version 1.24)
Go version: go1.12.8
Git commit: c92ab06ed9
Built: 09/03/2019 16:35:47
OS/Arch: windows/amd64
Experimental: false
Install Docker Compose
Before installing Docker Compose, you will need to enable TLS12 in PowerShell to download the Docker Compose binary from the Git Hub.
First step is to open the PowerShell as an administrator user. Run the following command to enable the Tls12:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Second step is to change the directory to the Docker directory with the following command:
cd C:\Program Files\Docker>
Next step is to download the latest version of Docker Compose binary from the Git Hub with the following command:
Invoke-WebRequest "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-Windows-x86_64.exe" -UseBasicParsing -OutFile docker-compose.exe
Once the Docker Compose is downloaded, you can verify the Docker Compose version with the following command:
docker-compose.exe version
You will get the Docker Compose version in the following output:
docker-compose version 1.29.2, build 5becea4c
docker-py version: 5.0.0
CPython version: 3.9.0
OpenSSL version: OpenSSL 1.1.1g 21 Apr 2020
Docker Compose Help
If you are new to Docker Compose and don’t know all option to run it, then use this command to see the list of all options:
docker-compose.exe --help
You will get the following list:
Commands:
build Build or rebuild services
config Validate and view the Compose file
create Create services
down Stop and remove resources
events Receive real time events from containers
exec Execute a command in a running container
help Get help on a command
images List images
kill Kill containers
logs View output from containers
pause Pause services
port Print the public port for a port binding
ps List containers
pull Pull service images
push Push service images
restart Restart services
rm Remove stopped containers
run Run a one-off command
scale Set number of containers for a service
start Start services
stop Stop services
top Display the running processes
unpause Unpause services
up Create and start containers
version Show version information and quit
Create a Sample IIS Container with Docker Compose
To use Docker Compose, you will need to create a docker-compose.yml file where you can define your all applications, interconnect all with each other and run them using a single command.
Let’s create a docker-compose.yml file to launch a simple IIS container. To do so, open your Notepad++ editor and add the following configurations:
version: "2.1"
services:
iis-demo:
build: .
image: "iis-demo:1.0"
ports:
- "80"
networks:
nat:
ipv4_address: 172.24.128.2
volumes:
- "c:/temp:c:/inetpub/logs/LogFiles"
environment:
- "env1=LIVE1"
- "env2=LIVE2"
- "HOSTS=1.2.3.4:TEST.COM"
networks:
nat:
external: true
Save the file with name docker-compose.yml.
Next step is to create a Docker file using the Notepad++ editor using the following content:
FROM microsoft/iis
# install ASP.NET 4.5
RUN dism /online /enable-feature /all /featurename:IIS-ASPNET45 /NoRestart
# enable windows eventlog
RUN powershell.exe -command Set-ItemProperty HKLM:\SYSTEM\CurrentControlSet\Control\WMI\Autologger\EventLog-Application Start 1
# set IIS log fields
RUN /windows/system32/inetsrv/appcmd.exe set config /section:system.applicationHost/sites /siteDefaults.logFile.logExtFileFlags:"Date, Time, ClientIP, UserName, SiteName, ServerIP, Method, UriStem, UriQuery, HttpStatus, Win32Status, TimeTaken, ServerPort, UserAgent, Referer, HttpSubStatus" /commit:apphost
# deploy webapp
COPY publish /inetpub/wwwroot/iis-demo
RUN /windows/system32/inetsrv/appcmd.exe add app /site.name:"Default Web Site" /path:"/iis-demo" /physicalPath:"c:\inetpub\wwwroot\iis-demo"
# set entrypoint script
ADD SetHostsAndStartMonitoring.cmd \SetHostsAndStartMonitoring.cmd
ENTRYPOINT ["C:\\SetHostsAndStartMonitoring.cmd"]
# declare volumes
VOLUME ["c:/inetpub/logs/LogFiles"]
Save the file with name Dockerfile.
Following step is to open your PowerShell as a administrator and change the directory to the directory where your docker-compose.yml and Dockerfile are saved.
Now run the following command to download IIS image and start the container:
Once the IIS container is started, you can verify the running container using the following command:
To check the container logs, run the following command:
If you want to stop the IIS container, run the following command:
That is great! We have learned How to Install Docker Compose on Windows Server 2016 / 2019 / 2022. it is time to summarize.
How to install Docker Compose on Windows Server 2016, 2019 and 2022 Conclusion
In this post, we explained how to install Docker Compose on Windows server 2016, 2019 and 2022. We also explained how to create a Docker file and docker-compose.yml file to launch the IIS demo container. I hope you can now easily launch your container using Docker Compose on Windows machine.
Docker Compose is very useful tool that make it easier orchestrate multiple containers to work together, especially in the case where you need to orchestrate more complex applications with multiple services. Docker compose also helps developers to automate the deployment of their code.
Please take a look at our Docker content here.
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