Docker Compose Example

Docker Compose Example

Docker Compose Example: Multi-Container Application

In this example, we will set up a simple application with Docker Compose. The application will have:

  1. A Web service running a Node.js Express app.

  2. A Database service running MySQL.

  3. We'll connect both services via a custom network.

We'll also demonstrate the structure of a docker-compose.yml file, which makes it easier to define and manage multiple containers.

Docker Compose Example

1. Create Project Directory

Create a new project directory and navigate into it:

mkdir my-docker-compose-app cd my-docker-compose-app

2. Create docker-compose.yml File

Create a file named docker-compose.yml and add the following content:

version: '3.8' services: web: build: ./web ports: - "8080:3000" networks: - my-network depends_on: - db environment: DB_HOST: db DB_USER: root DB_PASSWORD: rootpassword db: image: mysql:5.7 environment: MYSQL_ROOT_PASSWORD: rootpassword MYSQL_DATABASE: myapp networks: - my-network volumes: - db-data:/var/lib/mysql volumes: db-data: networks: my-network: driver: bridge

Explanation:

  • web service:

    • Builds the Docker image from the ./web directory (we will create this directory next).

    • Exposes the port 3000 inside the container to 8080 the host machine.

    • Connects to the custom network my-network.

    • depends_on ensures the db Service is ready before the web Service starts.

    • Environment variables (DB_HOST, DB_USER, DB_PASSWORD) are passed to the Node.js app for database configuration.

  • db service:

    • Uses the official MySQL 5.7 image.

    • Sets up the MySQL root password and creates a default database (myapp).

    • Uses a volume db-data for persistent storage of the database.

  • volumes:

    • Defines a named volume db-data for persistent database storage.

  • networks:

    • Defines a custom network my-network to allow communication between containers.

3. Create Web Application (Node.js/Express)

Now, create the web service (Node.js Express app).

  1. Inside the my-docker-compose-app directory, create a new directory web:

    mkdir web cd web
  2. Initialize a new Node.js project:

    npm init -y
  3. Install Express:

    npm install express mysql2
  4. Create the app.js file inside the web directory:

    const express = require('express'); const mysql = require('mysql2'); const app = express(); const port = 3000; const connection = mysql.createConnection({ host: process.env.DB_HOST, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: 'myapp', }); app.get('/', (req, res) => { connection.query('SELECT "Hello from Docker Compose!" AS message', (err, results) => { if (err) { res.status(500).send('Database error'); return; } res.send(results[0].message); }); }); app.listen(port, () => { console.log(`App is running at http://localhost:${port}`); });
    • The app connects to the MySQL database  mysql2 and fetches a simple message from the database.

    • The DB_HOST, DB_USER, and DB_PASSWORD Environment variables are used to configure the database connection.

  5. Create a Dockerfile inside the web directory:

    # Use official Node.js image FROM node:14 # Set the working directory WORKDIR /app # Copy package.json and install dependencies COPY package.json ./ RUN npm install # Copy the rest of the application code COPY . . # Expose port 3000 EXPOSE 3000 # Command to run the app CMD ["node", "app.js"]

    This Dockerfile:

    • Uses the official Node.js 14 image.

    • Copies the project files and installs dependencies.

    • Exposes port 3000 (default port for the app).

    • Specifies the command to run the app.

4. Start the Application with Docker Compose

Return to the root project directory (my-docker-compose-app), and run:

docker-compose up -d --build
  • The The --build flag ensures that Docker Compose builds the images before starting the containers.

  • The -d flag runs the containers in detached mode (in the background).

5. Verify the Services

  1. Check the status of your containers:

    docker-compose ps

    You should see both the web and db Services listed as running.

  2. Access the web service:

    Open your browser and go to http://localhost:8080. You should see:

    Hello from Docker Compose!

    This message is coming from the database through the Node.js app.

6. View Logs

To view the logs of the web service, use:

docker-compose logs web

To view the logs of the database service:

docker-compose logs db

7. Stop the Application

To stop the services and remove the containers, use:

docker-compose down

This will stop and remove all containers, networks, and volumes created by Docker Compose.

Summary of Key Concepts

  • Multi-Container Applications: Docker Compose allows you to manage multiple related containers (e.g., a web app and a database) with a single command docker-compose.yml file.

  • Networking: Services in the docker-compose.yml file can communicate with each other over a custom network.

  • Volumes: Volumes are used to persist data (e.g., MySQL data) across container restarts.

  • Dependencies: You can specify service dependencies  depends_on to ensure proper startup order.

  • Easy Configuration: Using a docker-compose.yml file, you can define and run applications with multiple containers using simple commands like docker-compose up.

Souy Soeng

Souy Soeng

Hi there 👋, I’m Soeng Souy (StarCode Kh)
-------------------------------------------
🌱 I’m currently creating a sample Laravel and React Vue Livewire
👯 I’m looking to collaborate on open-source PHP & JavaScript projects
💬 Ask me about Laravel, MySQL, or Flutter
⚡ Fun fact: I love turning ☕️ into code!

Post a Comment

CAN FEEDBACK
close