Logo

dev-resources.site

for different kinds of informations.

Day 04: Docker Compose: Managing multi-container applications

Published at
1/15/2025
Categories
webdev
docker
beginners
devops
Author
harshpandhe
Categories
4 categories in total
webdev
open
docker
open
beginners
open
devops
open
Author
11 person written this
harshpandhe
open
Day 04: Docker Compose: Managing multi-container applications

As your projects grow in complexity, managing multiple containers manually can become a challenge. This is where Docker Compose comes into play.

In this article, we’ll explore what Docker Compose is, its benefits, and how to use it to simplify the orchestration of multi-container applications.


What is Docker Compose?

Docker Compose is a tool that allows you to define and manage multi-container Docker applications using a simple YAML configuration file. Instead of running multiple docker run commands, you can use Docker Compose to start, stop, and manage all the containers in your application with a single command.


Key Benefits of Docker Compose

I. Simplified Configuration:

  • Define all containers, networks, and volumes in a single docker-compose.yml file.

II. Dependency Management:

  • Docker Compose ensures containers start in the correct order, respecting dependencies.

III. Ease of Use:

  • Manage the lifecycle of multi-container applications with commands like docker-compose up and docker-compose down.

VI. Consistency Across Environments:

  • Use the same configuration file for development, testing, and production.

Getting Started with Docker Compose

Prerequisites

  • Docker Compose comes pre-installed with Docker Desktop on Windows and macOS.
  • Linux users can install it separately by following the Docker Compose installation guide.

Verify the installation by running:

docker-compose --version
Enter fullscreen mode Exit fullscreen mode

Checking Docker-Compose Version


Example: A Multi-Container Application

Let’s create a simple application with the following components:

  • A Python Flask web application.
  • A Redis database.

1. Define the docker-compose.yml File

Create a file named docker-compose.yml in your project directory:

version: '3.9'
services:
  web:
    build: .
    working_dir: /app
    volumes:
      - .:/app
    ports:
      - "5000:5000"
    depends_on:
      - redis

  redis:
    image: redis:alpine
Enter fullscreen mode Exit fullscreen mode

2. Add the Flask Application Code

Create a file named app.py in the same directory:

from flask import Flask
import redis

app = Flask(__name__)
client = redis.Redis(host="redis", port=6379)


@app.route("/")
def hello():
    client.incr("hits")
    return f"Hello, Docker Compose! This page has been viewed {client.get('hits').decode()} times."


if __name__ == "__main__":
    app.run(host="0.0.0.0", port=5000)
Enter fullscreen mode Exit fullscreen mode

3. Write a Dockerfile

Here’s a simple Dockerfile to containerize our Python application:

FROM python:3.9-slim

# Set the working directory in the container
WORKDIR /app

# Copy requirements.txt into the container
COPY requirements.txt .

# Install dependencies
RUN pip install --no-cache-dir -r requirements.txt

# Copy application code into the container
COPY . .

# Set the default command to run the application
CMD ["python", "app.py"]
Enter fullscreen mode Exit fullscreen mode

4. Adding requirements.txt

Ensure your dependencies are listed in a requirements.txt file. For instance:

flask
redis
Enter fullscreen mode Exit fullscreen mode

5. Start the Application

Run the following command in the terminal:

Starting the Application

docker-compose up
Enter fullscreen mode Exit fullscreen mode

Docker-Compose Up

Docker Compose will:

  • Pull the required images.
  • Create and start the containers.
  • Display logs for all containers.

Stopping Using Ctrl+C

5. Access the Application

Open your browser and navigate to http://localhost:5000. You’ll see the Flask app running, with Redis tracking the number of visits.

Web-Page


Managing the Application with Docker Compose

Stop the Application

Use the following command to stop and remove containers, networks, and volumes:

docker-compose down
Enter fullscreen mode Exit fullscreen mode

In Process of Stopping

Stopped

Running in Detached Mode

To run containers in the background, add the -d flag:

docker-compose up -d
Enter fullscreen mode Exit fullscreen mode

Viewing Logs

View logs for all containers with:

docker-compose logs
Enter fullscreen mode Exit fullscreen mode

Docker-Compose Logs

Or for a specific service:

docker-compose logs web
Enter fullscreen mode Exit fullscreen mode

Docker-Compose logs web


Conclusion

Docker Compose is a powerful tool for managing multi-container applications, simplifying deployment and orchestration. With just a single YAML file, you can define, manage, and scale your services effortlessly.

In the next article, we’ll dive into Docker Use Cases, exploring real-world scenarios and best practices for utilizing Docker effectively. Stay tuned!

devops Article's
30 articles in total
DevOps bridges the gap between development and operations, emphasizing collaboration, automation, and continuous delivery in software development.
Favicon
Day 04: Docker Compose: Managing multi-container applications
Favicon
AWS Certification Syllabus [Updated 2025]
Favicon
Research DevOps metrics and KPIs
Favicon
Kafka server with SASL_OAUTHBEARER
Favicon
Introduction to Terraform: Revolutionizing Infrastructure as Code
Favicon
Amazon S3 vs. Glacier: Data Archival Explained
Favicon
Be sure to check out our new bug bounty platform!
Favicon
Làm thế nào để quản lý secrets hiệu quả trên nhiều nền tảng chỉ với một công cụ?
Favicon
Как создать свой VPN и получить доступ ко всему?
Favicon
Building a Weather Data Collection System with AWS S3 and OpenWeather API
Favicon
Terraform input validation
Favicon
NXP i.MX8MP Platform Porting Driver Tutorial
Favicon
Stop Worrying About EC2 Patching – Automate It Like a Pro!
Favicon
How Pinterest uses Kafka for Long-Term Data Storage
Favicon
Something You Didn't Know About AWS Availability Zones
Favicon
Advanced Load Balancing with Traefik: An Introduction to Progressive Delivery, Mirroring, Sticky Sessions, and Health Checks
Favicon
Psychotherapy Technology Advancements
Favicon
Any recommendations of open source asset inventory ?
Favicon
AIOps : Investigation par l’IA dans Kubernetes avec HolmesGPT, Ollama et RunPod …
Favicon
How to Solve Common Kubernetes Multi-Cluster Deployment Issues
Favicon
Power Up Your AWS Game: Create EC2 Instances, Install Apache, and Connect with PowerShell
Favicon
Effortless vCluster Management with Sveltos: An Event-Driven Approach
Favicon
Docker vs kubernetes
Favicon
🚀 Week 3 Recap: Learning in Public – Software Engineering with DevOps 🚀
Favicon
HashiCorp Vault Setup Guide for NEAR Protocol Accounts
Favicon
Mastering Kubernetes Storage: A Deep Dive into Persistent Volumes and Claims
Favicon
Configuring Public IP addresses in Azure
Favicon
SPL: a database language featuring easy writing and fast running
Favicon
Cloud computing can be confusing, but it doesn't have to be! ☁️🤔 In the latest episode of Cloud in List of Threes (CiLoTs), I’m serving up easy-to-digest (pun intended 🤭) explanations analogy to explain Regions, Availability Zones, and Edge Locations
Favicon
[Boost]

Featured ones: