Docker Compose: A Beginner's Guide

Hello there, future Docker maestros! I'm excited to be your guide on this journey into the world of Docker Compose. As someone who's been teaching computer science for years, I've seen many students struggle with containerization concepts. But fear not! By the end of this tutorial, you'll be orchestrating containers like a pro.

Docker - Compose

What is Docker Compose?

Before we dive in, let's start with the basics. Imagine you're planning a big party (because who doesn't love a good analogy?). You need to coordinate the food, drinks, music, and decorations. Docker Compose is like your party planning tool, but for containers!

In technical terms, Docker Compose is a tool for defining and running multi-container Docker applications. It allows you to use a YAML file to configure your application's services, networks, and volumes, then create and start all the services from your configuration with a single command.

Docker Compose - Installation

Now, let's get Docker Compose installed on your system. The process is as easy as pie (mmm... pie).

For Windows and Mac Users

If you've already installed Docker Desktop, congratulations! You already have Docker Compose. It comes bundled with the installation. You can skip to the next section and do a happy dance.

For Linux Users

For our Linux friends, you'll need to install Docker Compose separately. Here's how:

  1. Download the current stable release of Docker Compose:
sudo curl -L "https://github.com/docker/compose/releases/download/1.29.2/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
  1. Apply executable permissions to the binary:
sudo chmod +x /usr/local/bin/docker-compose
  1. Verify the installation:
docker-compose --version

If you see the version number, you're good to go!

Creating Your First Docker-Compose File

Now that we have Docker Compose installed, let's create our first docker-compose.yml file. This file is like the recipe for your application - it tells Docker what ingredients (services) you need and how to prepare them.

Let's create a simple web application using Python Flask and Redis. Don't worry if you're not familiar with these technologies - we'll keep it simple!

Create a new directory for your project and navigate into it:

mkdir my_first_compose_project
cd my_first_compose_project

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

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

Let's break this down:

  • version: '3': This specifies the version of the Docker Compose file format we're using.
  • services: This section defines the containers we want to run.
  • web: This is our Flask application service.
    • build: .: This tells Docker to build an image from a Dockerfile in the current directory.
    • ports: - "5000:5000": This maps port 5000 on the host to port 5000 in the container.
  • redis: This is our Redis service.
    • image: "redis:alpine": This tells Docker to use the official Redis image from Docker Hub.

Creating the Flask Application

Now, let's create a simple Flask application. Create a file named app.py:

from flask import Flask
from redis import Redis

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

@app.route('/')
def hello():
    redis.incr('hits')
    return f'Hello World! I have been seen {redis.get("hits").decode("utf-8")} times.'

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

This simple app increments a counter in Redis each time the page is visited.

Creating the Dockerfile

Next, we need to create a Dockerfile to build our Flask application. Create a file named Dockerfile:

FROM python:3.7-alpine
WORKDIR /code
ENV FLASK_APP=app.py
ENV FLASK_RUN_HOST=0.0.0.0
RUN apk add --no-cache gcc musl-dev linux-headers
COPY requirements.txt requirements.txt
RUN pip install -r requirements.txt
EXPOSE 5000
COPY . .
CMD ["flask", "run"]

This Dockerfile:

  1. Starts from the Python 3.7 Alpine image
  2. Sets the working directory to /code
  3. Sets environment variables for Flask
  4. Installs necessary dependencies
  5. Copies and installs Python requirements
  6. Exposes port 5000
  7. Copies the current directory into the container
  8. Sets the command to run Flask

Creating the Requirements File

Lastly, we need to specify our Python dependencies. Create a file named requirements.txt:

flask
redis

Running Your Docker Compose Application

Now for the exciting part - running your application! In your terminal, run:

docker-compose up

You should see Docker Compose building your images and starting your services. Once it's done, open a web browser and go to http://localhost:5000. You should see your "Hello World" message, and the counter should increment each time you refresh the page.

Docker Compose Commands

Here's a handy table of some common Docker Compose commands:

Command Description
docker-compose up Create and start containers
docker-compose down Stop and remove containers, networks, images, and volumes
docker-compose ps List containers
docker-compose logs View output from containers
docker-compose build Build or rebuild services
docker-compose start Start services
docker-compose stop Stop services

Conclusion

Congratulations! You've just created and run your first multi-container application using Docker Compose. We've only scratched the surface of what Docker Compose can do, but I hope this tutorial has given you a solid foundation to build upon.

Remember, learning Docker and containerization is like learning to cook - it takes practice, but once you get the hang of it, you'll be whipping up complex, multi-container recipes in no time!

Happy composing, future Docker chefs!

Credits: Image by storyset