DevOps / Containerization and Docker

Using Docker Compose to Manage Multi-Container Applications

This tutorial introduces Docker Compose, a powerful tool for managing multi-container applications. With hands-on exercises, you'll learn how to define and orchestrate multiple se…

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Focuses on containerizing applications to ensure consistency across development and production environments.

1. Introduction

Goal

The goal of this tutorial is to provide an in-depth understanding of Docker Compose, a tool that enables the management of multi-container applications. This will include defining and orchestrating multiple services running in separate containers.

Learning Outcomes

By the end of this tutorial, you will be able to:
- Understand Docker Compose and its use cases.
- Define and manage multi-container applications using Docker Compose.
- Understand how to write a docker-compose.yml file.
- Implement best practices for using Docker Compose.

Prerequisites

  • Basic knowledge of Docker.
  • Docker and Docker Compose installed on your machine.

2. Step-by-Step Guide

What is Docker Compose?

Docker Compose is a tool for defining and managing multi-container Docker applications. It allows you to create a YAML file (docker-compose.yml) to define your services, network, and volumes. Then, with a single command, you can create and start all the services from your configuration.

Writing a docker-compose.yml file

A docker-compose.yml file is a YAML file that defines the services, networks, and volumes for a docker application.

Here's a simple example:

version: '3'
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"

In this file, we define two services: web and redis. The web service builds from the Dockerfile in the current directory and forwards the exposed port 5000 to port 5000 on the host. The redis service uses the latest redis:alpine image.

Running Docker Compose

After defining your services in a docker-compose.yml file, you can start your services by running:

docker-compose up

This command will start all the services defined in your docker-compose.yml file.

3. Code Examples

Example 1: Python Flask app with Redis

Here's a practical example of a Docker Compose application. The application will use Flask, a Python web framework, and Redis, an open-source in-memory database.

First, let's define our Flask application in app.py:

from flask import Flask
from redis import Redis

app = Flask(__name__)
redis = Redis(host='redis', port=6379)

@app.route('/')
def hello():
    count = redis.incr('hits')
    return 'Hello World! I have been seen {} times.\n'.format(count)

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)

This simple Flask app connects to Redis and increments a counter each time the root route is accessed.

Now, let's define our Dockerfile:

FROM python:3.7-alpine
WORKDIR /app
ADD . /app
RUN pip install flask redis
CMD ["python", "app.py"]

This Dockerfile creates a Python 3.7 image, sets the working directory to /app, adds the current directory files to /app in the image, installs the Flask and Redis libraries, and runs app.py.

Now, let's create our docker-compose.yml file:

version: '3'
services:
  web:
    build: .
    ports:
      - "5000:5000"
  redis:
    image: "redis:alpine"

This Docker Compose file defines two services, web and redis.

You can start the application by running docker-compose up. If you navigate to http://localhost:5000 in your web browser, you should see a message like "Hello World! I have been seen 1 times."

4. Summary

In this tutorial, we've introduced Docker Compose, a tool for defining and managing multi-container Docker applications. We've learned how to write a docker-compose.yml file to define our services, and how to start our services with the docker-compose up command.

To continue learning about Docker Compose, you can read the official Docker Compose documentation. For more practical examples, you can check out the Docker Compose samples on GitHub.

5. Practice Exercises

  1. Create a Docker Compose application with three services: a web server, a database, and a worker. The web server should serve a simple HTML page, the database should store data from the web server, and the worker should process tasks from a queue.

  2. Add a volume to the Docker Compose application from exercise 1 to persist data from the database.

  3. Add a network to the Docker Compose application from exercise 1 to enable communication between the web server and the worker.

Solutions to these exercises will vary depending on the technology stack you choose to use. However, the main focus should be on understanding how to define and manage services, volumes, and networks with Docker Compose. Make sure to test each service individually before testing the whole application.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Base64 Encoder/Decoder

Encode and decode Base64 strings.

Use tool

Word Counter

Count words, characters, sentences, and paragraphs in real-time.

Use tool

CSS Minifier & Formatter

Clean and compress CSS files.

Use tool

Random Password Generator

Create secure, complex passwords with custom length and character options.

Use tool

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help