shape
shape

Docker Compose for Multi-Container Applications: A Tutorial

  • Home
  • DevOps
  • Docker Compose for Multi-Container Applications: A Tutorial

Docker Compose is a tool for defining and running multi-container Docker applications. If you’ve ever worked with Docker, you know that containers can run individual services like a web server or a database. However, most applications require multiple services to work together—web servers, databases, caches, etc. Managing these services across different containers can be cumbersome if done manually. Docker Compose simplifies this by allowing you to define, configure, and run multi-container Docker applications with a single YAML file.

In this tutorial, we will walk you through the process of using Docker Compose to manage a multi-container application. By the end of the tutorial, you’ll be able to define your services and deploy them efficiently.


What Is Docker Compose?

Docker Compose allows you to define the configuration for all the services that an application needs within a single YAML file (docker-compose.yml). With a single command, you can start up all services defined in the file.

Benefits of Docker Compose:
  • Simplified Service Management: You define all services in one place.
  • Automation: Easily build, scale, and manage multi-container applications.
  • Reproducibility: Share your configuration with others for consistent environments.
  • Isolation: Services run in isolated containers, avoiding dependency clashes.

Prerequisites

Before we dive into Docker Compose, make sure you have the following installed:

  1. Docker: You need Docker installed on your machine. If you haven’t done so already, install Docker.
  2. Docker Compose: Docker Compose is typically included with Docker Desktop. If you’re on Linux, you can install Docker Compose separately.

Once both are installed, verify the installation by running:

bash

 code

docker --version

docker-compose --version


Step 1: Understanding Docker Compose YAML File

Docker Compose uses a YAML file (docker-compose.yml) to define the services, networks, and volumes that your application requires. Here’s a basic structure of the file:

yaml

 code

version: “3.8”  # version of the Docker Compose file format

services:

  service_name:

    image: image_name

    ports:

      “8080:80”

    networks:

      network_name

networks:

  network_name:

    driver: bridge

Key Elements:
  • version: Specifies the version of the Docker Compose file format.
  • services: The different containers you want to run, with their specific configurations.
  • networks: Defines network configurations for container communication.
  • volumes: Specifies shared data volumes between containers.

Step 2: Creating a Simple Multi-Container Application

For this tutorial, we’ll set up a simple multi-container application with two services:

  1. Web App: A simple Node.js application that listens on port 3000.
  2. Database: A MySQL database that our Node.js app will interact with.
Directory Structure:

go

 code

docker-compose-tutorial/

├── app/

│   └── server.js

├── docker-compose.yml

└── package.json

Step 2.1: Writing the Web App

Create a directory named app and inside it, create a server.js file for our Node.js web application. This simple server will connect to the MySQL database.

javascript

 code

// server.jsconst express = require(‘express’);const mysql = require(‘mysql’);const app = express();const port = 3000;

const db = mysql.createConnection({

  host: ‘db’// refers to the database container name

  user: ‘root’,

  password: ‘password’,

  database: ‘mydb’

});

db.connect(err => {

  if (err) {

    console.error(‘Error connecting to DB: ‘, err);

    return;

  }

  console.log(‘Connected to DB’);

});

app.get(‘/’, (req, res) => {

  res.send(‘Hello, Docker Compose!’);

});

app.listen(port, () => {

  console.log(`App listening at http://localhost:${port}`);

});

Next, create a package.json file to manage dependencies:

json

 code

{

  “name”: “docker-compose-web-app”,

  “version”: “1.0.0”,

  “description”: “Simple Web App with MySQL”,

  “main”: “server.js”,

  “scripts”: {

    “start”: “node server.js”

  },

  “dependencies”: {

    “express”: “^4.17.1”,

    “mysql”: “^2.18.1”

  }}

To install the required dependencies, run:

bash

 code

npm install

Step 2.2: Writing the Docker Compose Configuration

Now let’s create the docker-compose.yml file to define our services.

yaml

 code

version: ‘3.8’

services:

  app:

    build: ./app

    ports:

      “3000:3000”

    networks:

      my_network

    depends_on:

      db

    environment:

      MYSQL_HOST=db

      MYSQL_USER=root

      MYSQL_PASSWORD=password

      MYSQL_DATABASE=mydb

  db:

    image: mysql:5.7

    environment:

      MYSQL_ROOT_PASSWORD: password

      MYSQL_DATABASE: mydb

    networks:

      my_network

    ports:

      “3306:3306”

networks:

  my_network:

    driver: bridge

Explanation:
  • app: The web app container.
  • build: ./app: This tells Docker Compose to build the app using the Dockerfile in the ./app directory.
  • depends_on: Ensures that the db container starts before the app container.
  • environment: Passes environment variables like database credentials to the container.
  • db: The MySQL database container.
  • image: mysql:5.7: Pulls the MySQL image from Docker Hub.
  • environment: Sets environment variables such as the MySQL root password and database name.
  • ports: Exposes MySQL’s default port (3306).

Step 3: Building and Running the Application

With everything in place, it’s time to build and run the multi-container application using Docker Compose.

Navigate to the project folder:

bash

 code

cd docker-compose-tutorial

Build and start the services:

bash

 code

docker-compose up --build

This command will:

  • Build the Docker images as needed.
  • Start the services in the correct order (app depends on db).

After a few moments, you should see output indicating that both containers are up and running.


Step 4: Accessing the Application

Open your browser and go to http://localhost:3000. You should see the message “Hello, Docker Compose!” displayed. This means that the web application is up and running and connected to the MySQL database.


Step 5: Stopping the Containers

Once you’re done with the tutorial, you can stop the running containers with:

bash

 code

docker-compose down

This will stop and remove the containers, but the data inside the database will persist because we didn’t define a volume. To clean everything up, including volumes, use:

bash

 code

docker-compose down -v


Conclusion

In this tutorial, we demonstrated how to use Docker Compose to manage multi-container applications. By defining both a Node.js web app and a MySQL database in a single docker-compose.yml file, we were able to easily start and manage the containers.

Key Takeaways:
  • Docker Compose simplifies the management of multiple containers.
  • You can define services, networks, and volumes all in one YAML file.
  • Use docker-compose up to build and start your containers.
  • depends_on ensures services start in the correct order.

Docker Compose is an invaluable tool for developers who need to manage complex applications with multiple containers. Try adding more services to your configuration as your application grows, and enjoy the ease of managing your containers with just a few simple commands!


Next Steps:
  1. Experiment with adding more services like Redis, Nginx, or a frontend framework.
  2. Explore Docker Compose file options like scaling, logging, and persistent storage.
  3. Learn how to deploy multi-container apps with Docker Compose to cloud platforms like AWS or Azure.

Got Questions?

Feel free to leave a comment below or reach out for further clarification. Happy Docking!

Additional learning resources:
  • C LANGUAGE COMPLETE COURSE – IN HINDI – Link
  • CYBER SECURITY TUTORIAL SERIES – Link
  • CODING FACTS SERIES – Link
  • SKILL DEVELOPMENT SERIES – Link
  • PYTHON PROGRAMMING QUIZ – Link
  • CODING INTERVIEW QUIZ – Link
  • JAVA PROGRAMMING QUIZ – Link
  • C PROGRAMMING QUIZ – Link

Comments are closed

0
    0
    Your Cart
    Your cart is emptyReturn to shop