close
The Wayback Machine - https://web.archive.org/web/20241013191110/https://www.geeksforgeeks.org/docker-compose/
Open In App

Docker – Compose

Last Updated : 08 Oct, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

An open-source platform called Docker makes it simple to design, ship, and deploy applications. It runs an application in an isolated environment by compiling all of its dependencies into a so-called container. for additional information on Docker. In a normal case, a number of services, such as a database and load balancing, are required to support an application. We’ll look at Docker Compose’s assistance with setting up many services in this article. Also, we will see a demonstration of installing and utilizing Docker Compose.

What is Docker Compose?

Docker Compose will execute a YAML-based multi-container application. The YAML file consists of all configurations needed to deploy containers Docker Compose, which is integrated with Docker Swarm, and provides directions for building and deploying containers. With Docker Compose, each container is constructed to run on a single host.

Docker Compose simplifies the management of multi-container Docker applications. If you’re looking to master Docker Compose and its role in the larger DevOps lifecycle, the DevOps Engineering – Planning to Production course offers hands-on examples of managing multi-container applications

Install Docker Compose

We can run Docker Compose on macOs, Widows, and 64-bit Linux. 

  • For any significant activity, Docker Compose depends on Docker Engine. Depending on your arrangement, we must ensure that Docker Engine is installed either locally or remotely.
  • A desktop system such as Docker for Mac and Windows comes with Docker Compose preinstalled. 
  • Install Docker first as instructed in Docker installation on the Linux system before beginning the installation of Docker Compose. 

How to Install Docker Compose on Ubuntu? A Step-By-Step Guide

Step 1: Update the package Manager

  • The following scripts will install the most recent version of Docker Compose and update the package management.
sudo apt-get update

Step 2: Download the Software

  • Here we are using the Ubuntu flavor in the Linux Operating system. So the package manager is “apt-get” If you want to install it in Redhat Linux then the package manager will be “yum”.

Step 3: Apply Permissions

  • Apply the Executable permissions to the software with the following commands:
sudo chmod +x /usr/local/bin/docker-compose

Step 4: Verify the Download Software

  • Verify the whether the docker compose is successfully installed or not with the following command:
docker-compose --version

Docker Container

A docker container is a lightweight Linux-based system that packages all the libraries and dependencies of an application, prebuilt and ready to be executed. It is an isolated running image that makes the application feel like the whole system is dedicated to it. Many large organizations are moving towards containers from VMs as they are light and simple to use and maintain. But when it comes to using containers for real-world applications, usually one container is not sufficient. For example, Let’s assume Netflix uses a microservices architecture. Then it needs services for authentication, Login, Database, Payment, etc, and for each of these services, we want to run a separate container. It is preferred for a container to have only a single purpose.

Now, imagine writing separate docker files, and managing configuration and networks for each container. This is where Docker Compose comes into the picture and makes our lives easy.

Why Docker Compose?

As discussed earlier,  a real-world application has a separate container for each of its services. And we know that each container needs to have a Dockerfile. It means we will have to write maybe hundreds of docker files and then manage everything about the containers individually, That’s cumbersome. 

Hence we use docker-compose, which is a tool that helps in the definition and running of multi-container applications. With the help of Docker Compose you can start and stop the services by using its YAML file. Docker-compose allows us to start and stop all of the services with just a few simple commands and a single YAML file for each configuration.

In contrast to utilizing a prebuilt image from Docker Hub, which you may configure with the docker-compose.yaml file, if you are using a custom image, you will need to declare its configurations in a separate Dockerfile. These are the features that docker-compose support:

  • All the services are isolated running on a single host.
  • Containers are recreated only when there is some change.
  • The volume data is not reset when creating new containers, volumes are preserved.
  • Movement of variables and composition within environments.
  • It creates a virtual network for easy interaction within the environments.

Now, let’s see how we can use docker-compose, using a simple project.

How to Use Docker Compose?

In this project, we will create a straightforward Restfull API that will return a list of fruits. We will use a flask for this purpose. And a PHP application will request this service and show it in the browser. Both services will run in their own containers.

  • First, Create a separate directory for our complete project. Use the following command.
mkdir dockerComposeProject
  • Move inside the directory.
cd dockerComposeProject

Step 1: Create API

we will create a custom image that will use Python to serve our Restful API defined below. Then the service will be further configured using a Dockerfile.

  • Then create a subdirectory for the service we will name it product. and move into the same.
mkdir product
cd product

Step 2: Build Python  api.py

  • The following is the python file that helps in making an API call:
  • Create a Dockerfile to define the container in which the above API will run.
Python
from flask import Flask
from flask_restful import Resource, Api

# create a flask object
app = Flask(__name__)
api = Api(app)

# creating a class for Fruits that will hold
# the accessors
class Fruits(Resource):
    def get(self):
        # returns a dictionary with fruits
        return {
            'fruits': ['Mango', 'Pomegranate', 'Orange', 'Litchi']
        }

# adds the resources at the root route
api.add_resource(Fruits, '/')

# if this file is being executed then run the service
if __name__ == '__main__':
    # run the service
    app.run(host='0.0.0.0', port=80, debug=True)

step 3: Create requirements.txt

flask
flask-restful


Step 4: Create Dockerfile For Python API 

FROM python:3
COPY . /usr/src/app
WORKDIR /usr/src/app
RUN pip install --no-cache-dir -r requirements.txt
CMD ["python", "api.py"]

FROM accepts an image name and a version that the docker will download from the docker hub. The current working directory’s contents can be copied to the location where the server expects the code to be by using the copy command. Moreover, the CMD command takes a list of commands to start the service once the container has been started.

Step 5: Create Php HTML Website 

Let’s create a simple website using PHP that will use our API.

  • Move to the parent directory and create another subdirectory for the website.
cd ..
mkdir website
cd website

index.php

<!DOCTYPE html>
<html lang="en">
<head>
<title>Fruit Service</title>
</head>
<body>
<h1>Welcome to India's Fruit Shop</h1>
<ul>
<?php
$json = file_get_contents('http://fruit-service');
$obj = json_decode($json);
$fruits = $obj->fruits;
foreach ($fruits as $fruit){
echo "<li>$fruit</li>";
}
?>
</ul>
</body>
</html>
  • Now create a compose file where we will define and configure the two services, API and the website.
  • Move out of the website subdirectory using the following code.
cd ..
  • And then create the file name as . docker-compose.yaml 

Step 6: Create Docker-compose.yaml file 

  • The following is the sample docker compose file code:
version: "3"

services:
fruit-service:
build: ./product
volumes:
- ./product:/usr/src/app
ports:
- 5001:80

website:
image: php:apache
volumes:
- ./website:/var/www/html
ports:
- 5000:80
depends_on:
- fruit-service

Docker-compose.yaml file Explanation

The first line is optional where we specify the version of the docker-compose tool. Next services define a list of services that our application is going to use. The first service is fruit service which is our API and the second one is our website. The fruit service has a property build that contains the dockerfile that is to be built and created as an image. Volumes define storage mapping between the host and the container so that we can make live changes. Finally, port property exposes the containers port 80 through the host’s 5001.

The website service does not use a custom image but we download the PHP image from the Docker hub and then map the websites folder that contains our index.php to /var/www/html (PHP expects the code to be at this location). Ports expose the container port. Finally, the depends_on specifies all the services on which the current service depends.

  • The folder structure after creating all the required files and directory will be as follows:

Docker Compose folder structure

Run the application stack with Docker Compose

  • Now that we have our docker-compose.yml file, we can run it.
  • To start the application, enter the following command.
docker-compose up -d 

Now all the services will start and our website will be ready to be used at localhost:5000.

  • Open your browser and enter localhost:5000.

Output

Application from internet

  • To stop the application, either press CTRL + C or
docker-compose stop

Advantages of Docker Compose

The following are the advantages of Docker Compose:

  • Simplifies Multi-Container Management: Docker Compose facilitates with features such as define, configure, and run multiple containers with a single YAML file, streamlining the management of complex applications.
  • Facilitates Environment Consistency: It facilitates with the development, testing, and production environments that are consistent with reducing the risk of environment-related issues.
  • Automates Multi-Container Workflows: With Docker Compose, you can easily automate the setup and teardown of multi-container environments, making it ideal for CI/CD pipelines and development workflows.
  • Efficient Resource Management: It enables efficient allocation and management of resources across multiple containers, improving application performance and scalability.

Disadvantages of Docker Compose

The following are the disadvantages of Docker Compose:

  • Limited Scalability: Docker Compose is not developed for large scaling mechanism which can limit its effectiveness for managing complex deployments.
  • Single Host Limitation: Docker Compose will operate on a single host, making it unsuitable for distributed applications with requiring multi-host orchestration.
  • Basic Load Balancing: It lacks with advanced load balancing and auto-scaling features found in more robust orchestration tools like Kubernetes.
  • Less Robust Monitoring: Docker Compose provides minimal built-in monitoring and logging capabilities compared to more comprehensive solutions.

Features of Docker Compose

The following are the features of Docker Compose:

  • Multi-Container Deployment: it facilitates with easily define and run applications with multiple containers using a single YAML file.
  • Service Isolation: Each service runs in its own container, with ensuring the isolation and reducing conflicts between services.
  • Simplified Configuration: It helps in centralizing all the configurations, including networking, volumes, and dependencies, in the docker-compose.yml file.
  • Scalability: It provides the effortlessly scaling of services up or down with a single command, allowing for flexible and dynamic resource management.

Best Practices of Docker Compose

The following are the some of the best practices of Docker Compose:

  • Use Environment Variables: It is suggestable to store configuration values and secrets in environment variables to keep your docker-compose.yml clean and secure.
  • Keep Services Lightweight: It is preferred to design each service to handle a single responsibility to ensure modularity and ease of maintenance.
  • Leverage Volumes: Usage of volumes with enhancing in maintaining the persistent data storage, allowing data to persist across container restarts and updates.
  • Version Control Your Compose Files: It is preferred to maintain your docker-compose.yml file in version control (e.g., Git) to track changes and collaborate with your team effectively.

Conclusion

In this article, we learned about Docker Compose, and why and when to use it. And demonstrated its usuage through a simple project. It helps in automating the creating process of containers through services, networks and volumes with through respective keywords availability. Through using docker compose management and automation of containers and its volumes, networks will be easier.

Docker Compose – FAQs

What is Docker Compose used for?

Docker Compose is docker native automation tool that is used for defining and running multi-container Docker applications.

Is Docker Compose still used?

Yes, Docker Compose is widely used for development, testing, and small-scale deployments.

When should Docker Compose be used?

Docker Compose should be used when managing multi-container applications with simplified configuration.

Do I need a Dockerfile and docker-compose?

Yes, a Dockerfile helps in defining the image build process, while docker-compose.yml orchestrates the containers.






Previous Article
Next Article

Similar Reads

Docker Compose vs Docker Swarm
Docker is one of the most widely used container-based software on the market. Docker is an open-source platform for creating, deploying, and managing containerized applications. Docker allows us to simply bundle our apps into containers and can be deployable on any platform that supports docker software acting as a platform independent. What Is Doc
6 min read
Getting started with Spring Boot 3, Kafka over docker with docker-compose.yaml
We will create two Spring Boot 3.x applications (Producer and Consumer) requiring Java 17 to get started. We need a queuing service to pass messages from the producer Spring service to the consumer Spring service. Here, we will use Kafka. Confluent provides Docker images that are easy to use for setting up the Kafka environment. Since we will use a
5 min read
Installation of Docker Compose
Docker Compose is a powerful tool that helps in simplifying the orchestration of multi-container docker applications. In this we have to configure the application services inside the Yaml file and docker-compose will read the configuration data from that Yaml script. Before Moving into the installation process, make sure that you have Docker alread
4 min read
Difference Between Docker Compose And Kubernetes
Docker Compose and Kubernetes are two prominent container orchestration solutions with distinct features and capabilities. It simplifies application stack management by allowing you to handle services, networks, and volumes in a single, understandable YAML configuration file. Kubernetes integrates nicely with other popular CI/CD technologies like J
5 min read
Docker Compose CLI Registry
Docker Compose is a powerful tool that is used to manage multi-container docker applications. Here in this guide, I will first discuss about Docker Compose CLI Registry. Then I will discuss the steps to set up the Docker Compose CLI Registry on an Ubuntu machine. After this, I will guide you through the important Docker Compose commands to manage m
4 min read
Docker Compose - How To Execute Multiple Commands?
Docker Compose is an orchestration tool that comes with Docker and enables users to run and manage multi-container applications using a YAML format file. Docker Compose comes pre-installed with Docker and does not require any additional installation or activation. In this article, we will explore what Docker Compose is. and how we can execute multi
7 min read
How do you Mount Volume in Docker Compose File ?
Docker is a containerization tool that encapsulates the application along with its dependencies and runtime into compact units called docker containers. On the other hand, Docker Compose is a service through which multiple Docker container applications can be managed easily. In this guide I will first what is Docker. Then I will discuss what is Doc
4 min read
Docker Compose for Python Applications: A Comprehensive Guide
In the domain of present day software development, Python has arisen as a powerhouse language, leaned toward for its simplicity, readability, and flexibility. With Python, developers can make a wide cluster of uses, from web services and APIs to data handling pipelines and AI models. Notwithstanding, conveying and overseeing Python applications acr
6 min read
How to Configure NGINX in Docker Compose?
In modern web development, the act of containerization has acquired widespread reception because of its proficiency, portability, and adaptability benefits, containerization allows developers to package applications and their conditions into lightweight, isolated containers, ensuring consistency across various conditions and working on deployment p
7 min read
Docker Compose Port Mapping
Docker is an essential tool that simplifies the deployment process by encapsulating applications within a container. To facilitate various types of communication in a Docker container, we need to expose port. Here in this guide, I will first cover what is Docker and Docker Compose and how Docker has become an essential tool among developers. Then I
5 min read
Docker Compose For Windows: Tips And Tricks
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
7 min read
Docker Compose vs. Dockerfile with Code Examples
Docker is an open-source platform that empowers developers to automate the deployment of applications inside lightweight, portable containers. Containers encapsulate an application and its conditions, ensuring consistency across various conditions, from advancement to production, the Dockerfile and the Docker Compose file are two essential Docker t
7 min read
Docker Compose Tool To Run aMulti Container Applications
The article talks about how to run multi-container applications using a single command. Docker Compose is a tool for defining and running multi-container Docker applications. With Compose, you can configure a file (YAML file) to configure your docker containers. Then Once you configured the Yaml file with a single command, you create and start all
8 min read
Docker Compose For Java Applications: Simplifying Deployment
Docker is an open-source platform for developers and sysadmins to build, ship, and run distributed applications. If we want to define and run more than one container then we should go for docker compose. We have to configure multiple container environments in a single file so that it simplifies the deployment process. In Java applications, Docker C
8 min read
Docker Compose for PHP Applications: Best Practices
In the domain of web development, PHP provides the service as a widely utilized scripting language in being part of websites web applications, and APIs. It is embedded in HTML and is executed on the server side. It produces the dynamic web page content helping manage the dependencies, configurations, and deployment processes. It is increasingly cha
8 min read
Docker Compose up, down, stop start difference
Docker Compose has been a technology of tremendous importance in recent DevOps and software development practices because it provides a powerful toolset for the management of multi-container Docker applications. The basic commands for Docker Compose, such as up, down, stop, and start, are at the core of Docker Compose. Its main functionality orches
6 min read
How To Install and Use Docker Compose on Ubuntu 22.04
Docker is a platform that provides virtual containers on which an application can be deployed independent of the underlying OS of the server. Further, the container can be created from a replica called docker image which contains all the dependencies and can run on any OS that has a docker engine, with similar results. What is docker-compose?Docker
6 min read
How to Use Docker Compose With Jenkins
In the fast-paced world of software development, it is mainly ensured by automation of repetition and task persistence. This is where Docker Compose and Jenkins come into play. Docker Compose is a tool for defining and running multi-container Docker applications. On the other hand, Jenkins is a widely used and popular automation server, open source
8 min read
Docker Compose Restart Policy
The capability of delivering application availability and resilience in the dynamic world of software development is enormous. Docker Compose is among the powerful tools in the Docker ecosystem that make multi-container application management very easy by letting developers describe services, networks, and volumes in a single YAML file. An importan
8 min read
Docker Compose YAML Explained: A Deep Dive into Configuration
Containerization is one of the recent revolutionary ways to develop, deploy, and manage applications in the dynamic software development arena. Docker remains in its premier position as one of the de facto platforms in containerization that helps developers package applications with their dependencies into isolated containers, making them run consi
9 min read
docker compose override
Docker is a widely used platform designed to help developers build, share, and run container applications. We handle the tedious setup so that you can focus on the code service that offers free and premium tiers. The software that hosts containers is known as Docker Engine. The docker-compose.override.yml file mainly allows you to customize Docker
5 min read
What is the difference between Podman and Docker Compose?
Podman and Docker Compose are two tools with related functions concerning the operation of containers but each satisfies a different role in the container taxonomy. Podman is a container engine to collects, operates, manages, and runs containerized applications without a daemon, which is more secure and has no daemon problem than Docker. While Dock
7 min read
How to Fix the "Docker Compose Command Not Found" Error
To determine and operate multi-container Docker applications, you'll need Docker Compose. The "Docker Compose command not found" error is a frequent problem that many engineers encounter, nevertheless. This problem usually arises from an incorrect setup or non-existence of the Docker Compose binary in the PATH of the system. We'll look at how to re
5 min read
What does Flag do in Docker Compose?
Docker Compose is a tool that is mostly used to create and execute multi-container apps. It is the secret to opening the door to a more simplified and effective deployment and development process. What is Docker Compose?Docker Compose makes it simple to manage services, networks, and volumes in a single, understandable YAML configuration file, stre
5 min read
How to Configure Memory Limits in Docker Compose: A Comprehensive Guide
When you run Docker-contained applications, there is a need for the proper management of resource allocation to allow for stability and performance. Docker Compose is a tool for defining and running multi-container Docker applications. Through it, one can define resource constraints, such as memory limit, for your containers, by limiting the amount
6 min read
Managing Secrets in Docker Compose v3.1
In modern application development, a high level of concern in the security of sensitive information like passwords, API keys, and certificates is a must. It is all about managing the secrets in such a manner that they cannot be disclosed in the code or the version control with the containerized environment. With Docker Compose v3.1, there was a ver
5 min read
Docker Compose Healthchecks: Ensuring Container Availability
The world of containerized applications needs every single one of these containers to operate according to their standards in order to provide stable and reliable services. Docker Compose helps in managing multi-container applications, but just running containers is not enough. Issues like application crashes, network failure, or dependency problem
6 min read
Viewing Docker-Compose Healthcheck Logs
Docker health check is a feature provided by the docker itself, it is used for the purpose of maintaining the docker container and its performance. it makes sure to maintain the health check logs of the docker-compose to make sure that the container is performing as it should. What Is Docker Compose?Docker Compose is a tool that is used to simply t
3 min read
Docker Compose integration for Amazon Elastic Container Service
Docker Compose is widely used for defining and managing multi-container Docker applications. It eases the process, since the developer can put services, networks, and volumes that form part of an application into one file using YAML. This makes it very easy to handle development environments which are complex in nature. On the other hand, Amazon El
5 min read
Building and Managing .NET Applications with Docker Compose
Modern software development involves putting together applications from a variety of services that have to collaborate. For .NET developers, this can be really complex if everything is done in the development environment. Docker Compose provides an easy way for developers to define and manage multi-container applications, docker Compose uses a simp
5 min read
Article Tags :