Followers

Docker Compose Multi Docker files

Let's create a real-time example where we have two containers, one for a Python application and another for a Node.js application, both ...

Let's create a real-time example where we have two containers, one for a Python application and another for a Node.js application, both using the same MySQL database. We'll use Docker Compose to set up this scenario.

Here's the directory structure and files for the example:

myapp/
│
├── docker-compose.yml
├── python-app/
│   ├── Dockerfile
│   └── app.py
│
├── node-app/
│   ├── Dockerfile
│   └── app.js
│
└── init.sql
  1. docker-compose.yml - Defines the services and their configurations.
  2. python-app/Dockerfile - Dockerfile for the Python application.
  3. python-app/app.py - Python application code.
  4. node-app/Dockerfile - Dockerfile for the Node.js application.
  5. node-app/app.js - Node.js application code.
  6. init.sql - SQL script to initialize the MySQL database.

Now, let's configure these files:

docker-compose.yml:

version: '3'

services:
  mysql:
    image: mysql:latest
    container_name: mysql-container
    environment:
      MYSQL_ROOT_PASSWORD: root_password
      MYSQL_DATABASE: mydb
    volumes:
      - mysql-data:/var/lib/mysql
    ports:
      - "3306:3306"

  python-app:
    build:
      context: ./python-app
    container_name: python-app-container
    depends_on:
      - mysql
    environment:
      MYSQL_HOST: mysql
      MYSQL_USER: root
      MYSQL_PASSWORD: root_password
      MYSQL_DB: mydb

  node-app:
    build:
      context: ./node-app
    container_name: node-app-container
    depends_on:
      - mysql
    environment:
      MYSQL_HOST: mysql
      MYSQL_USER: root
      MYSQL_PASSWORD: root_password
      MYSQL_DB: mydb

volumes:
  mysql-data:

python-app/Dockerfile:

FROM python:3.8

WORKDIR /app

COPY . .

RUN pip install mysql-connector-python

CMD ["python", "app.py"]

python-app/app.py (Python application code):

import mysql.connector

MYSQL_HOST = "mysql"
MYSQL_USER = "root"
MYSQL_PASSWORD = "root_password"
MYSQL_DB = "mydb"

try:
    connection = mysql.connector.connect(
        host=MYSQL_HOST,
        user=MYSQL_USER,
        password=MYSQL_PASSWORD,
        database=MYSQL_DB
    )

    cursor = connection.cursor()

    # Create a table if it doesn't exist
    cursor.execute("""
        CREATE TABLE IF NOT EXISTS employees (
            id INT AUTO_INCREMENT PRIMARY KEY,
            first_name VARCHAR(255),
            last_name VARCHAR(255),
            email VARCHAR(255)
        )
    """)

    connection.commit()

    print("Table 'employees' created or already exists.")

except Exception as e:
    print("Error:", str(e))

finally:
    if connection.is_connected():
        cursor.close()
        connection.close()

node-app/Dockerfile:

FROM node:14

WORKDIR /app

COPY . .

RUN npm install

CMD ["node", "app.js"]

node-app/app.js (Node.js application code):

const mysql = require('mysql');

const MYSQL_HOST = "mysql";
const MYSQL_USER = "root";
const MYSQL_PASSWORD = "root_password";
const MYSQL_DB = "mydb";

const connection = mysql.createConnection({
    host: MYSQL_HOST,
    user: MYSQL_USER,
    password: MYSQL_PASSWORD,
    database: MYSQL_DB
});

connection.connect((err) => {
    if (err) {
        console.error('Error connecting to MySQL:', err);
        return;
    }
    console.log('Connected to MySQL database');
});

// Define your Node.js application logic here
// For example, you can perform database queries, etc.

connection.end();

In this example:

  • We have a MySQL service defined in docker-compose.yml, which sets up the MySQL container with a root password and a database named mydb. We also map port 3306 to allow connections to MySQL from the host.

  • The Python and Node.js applications (defined in their respective Dockerfiles and code files) connect to the MySQL database using the provided environment variables (e.g., MYSQL_HOSTMYSQL_USERMYSQL_PASSWORDMYSQL_DB) in the docker-compose.yml file.

  • Both applications create or use the employees table in the mydb database. You can replace the application logic with your specific use case.

To run this example, navigate to the directory containing docker-compose.yml and run:

docker-compose up -d

This will start the MySQL container and both the Python and Node.js application containers. They will share the same MySQL database (mydb) for their data storage needs.

COMMENTS

Name

Ansible,6,AWS,1,Azure DevOps,1,Containerization with docker,2,DevOps,2,Docker Quiz,1,Docker Swarm,1,DockerCompose,1,ELK,2,git,2,git quiz,1,Git Worksheet,1,ITIL,1,ITSM,1,Jira,3,Kubernetes,1,Kubernetes Quiz,5,SAST DAST Security Testing,1,SDLC Quiz,5,SonarQube,3,Splunk,2,vagrant kubernetes,1,Windows,1,YAML Basics,1,
ltr
item
DevOpsWorld: Docker Compose Multi Docker files
Docker Compose Multi Docker files
DevOpsWorld
https://www.devopsworld.co.in/2023/10/docker-compose-multi-docker-files.html
https://www.devopsworld.co.in/
https://www.devopsworld.co.in/
https://www.devopsworld.co.in/2023/10/docker-compose-multi-docker-files.html
true
5997357714110665304
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content