DEV Community

Adekunle Osatuyi
Adekunle Osatuyi

Posted on

Building a Multi-Container App using Docker

Aim of this project is to containerize a Node.js and MySQL stack using Docker Compose.

Project Structure
node-mysql-compose/
├── app/
│ ├── Dockerfile
│ ├── server.js
│ └── package.json
├── docker-compose.yml
└── .env

Step 1: Make a Directory
mkdir node-mysql-compose

Step 2: Create app/ inside node-mysql-compose and cd into the app/ then create the files inside the app/

Dockerfile
FROM node:18
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]

server.js
`const express = require('express');
const mysql = require('mysql2');
const app = express();
const port = 3000;

const dbConfig = {
host: 'db',
user: 'root',
password: process.env.MYSQL_ROOT_PASSWORD,
database: process.env.MYSQL_DATABASE
};

function connectWithRetry() {
const db = mysql.createConnection(dbConfig);

db.connect(err => {
if (err) {
console.log('❌ MySQL not ready, retrying in 5 seconds...');
setTimeout(connectWithRetry, 5000);
} else {
console.log('✅ Connected to MySQL!');
}
});
}

connectWithRetry();

app.get('/', (req, res) => {
res.send('Hello Guest, Welcome to Lubemart Multi-Container App using Node.js and MySQL!');
});

app.listen(port, '0.0.0.0', () => {
console.log(App running on port ${port});
});`

package.json
{
"name": "node-mysql-app",
"version": "1.0.0",
"main": "server.js",
"dependencies": {
"express": "^4.18.2",
"mysql2": "^3.2.0"
}
}

Step 3a: (Create File) docker-compose.yml
services:
db:
image: mysql:5.7
restart: always
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MYSQL_DATABASE: ${MYSQL_DATABASE}
volumes:
- db_data:/var/lib/mysql
networks:
- mynetwork2

app:
build: ./app
ports:
- "3000:3000"
environment:
MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD}
MYSQL_DATABASE: ${MYSQL_DATABASE}
depends_on:
- db
networks:
- mynetwork2

volumes:
db_data:

networks:
mynetwork2:
driver: bridge

Step 3b: (Create File) .env
MYSQL_ROOT_PASSWORD=example
MYSQL_DATABASE=testdb

Top comments (0)