Have you ever spent hours, or even days, trying to configure a local development environment only to be met with the dreaded “it works on my machine” syndrome? In the modern era of software development, consistency across different environments is not just a luxury—it is a necessity. This tutorial setup docker compose mysql node js redis will guide you through the process of containerizing a full-stack architecture, ensuring that your application runs seamlessly from your local laptop to the production cloud.
Docker has revolutionized the way we build, ship, and run applications. According to recent industry surveys, over 70% of high-performing DevOps teams utilize containerization to accelerate their deployment cycles. By the end of this comprehensive guide, you will have a robust, production-ready boilerplate that integrates a Node.js backend, a MySQL relational database, and a Redis caching layer, all orchestrated by Docker Compose.
Table of Contents
- Why Use Docker Compose for Node.js, MySQL, and Redis?
- Prerequisites for This Tutorial
- Designing the Project Structure
- Step 1: Setting Up the Node.js Application
- Step 2: Crafting the Dockerfile for Node.js
- Step 3: Configuring MySQL for Persistence
- Step 4: Implementing Redis for Caching
- Step 5: Orchestrating with docker-compose.yml
- Step 6: Running and Testing the Entire Stack
- Troubleshooting Common Docker Issues
- Best Practices for Production Environments
- Conclusion and Next Steps
Why Use Docker Compose for Node.js, MySQL, and Redis?
Before diving into the technical implementation, it is crucial to understand why this specific stack is so popular and why Docker Compose is the right tool for the job. Scaling a application manually involves installing specific versions of runtimes and databases on every developer’s machine. This leads to version mismatches and “dependency hell.”
Docker Compose allows you to define a multi-container application in a single YAML file. This means your tutorial setup docker compose mysql node js redis workflow becomes a simple command: docker-compose up. The benefits include:
- Isolation: Each service runs in its own container with its own dependencies.
- Scalability: You can easily scale individual services (like adding more Node.js instances) without affecting others.
- Environment Parity: The environment on your local machine is identical to the one in staging or production.
- Microservices Ready: This setup follows the microservices philosophy, making it easier to swap out components in the future.
Prerequisites for This Tutorial
To follow along with this tutorial setup docker compose mysql node js redis, you will need the following tools installed on your system:
- Docker Desktop: Includes Docker Engine and Docker Compose. Available for Windows, macOS, and Linux.
- Node.js (Local): While we will run Node inside Docker, having it locally (v18 or higher) helps with initial package installation.
- A Code Editor: Visual Studio Code is highly recommended due to its excellent Docker extensions.
- Basic CLI Knowledge: Familiarity with the terminal or command prompt.
Designing the Project Structure
A clean project structure is the foundation of a maintainable codebase. For this tutorial, we will organize our files to keep the application logic separate from the infrastructure configuration. Create a new directory named node-docker-stack and set it up as follows:
node-docker-stack/
├── app/
│ ├── index.js
│ ├── package.json
│ └── .dockerignore
├── mysql-data/ (auto-generated)
├── Dockerfile
├── docker-compose.yml
└── .env
Step 1: Setting Up the Node.js Application
First, let’s create a simple Express.js application that connects to both MySQL and Redis. Navigate to the app/ directory and initialize a new Node project.
Run the following command in your terminal:
npm init -y
Next, install the necessary dependencies:
npm install express mysql2 redis dotenv
Now, create the index.js file. This script will act as our server, attempting to connect to the database and the cache upon startup. This is a critical part of our tutorial setup docker compose mysql node js redis because it demonstrates how services communicate over a virtual network.
const express = require('express');
const mysql = require('mysql2');
const redis = require('redis');
const app = express();
const PORT = process.env.PORT || 3000;
// MySQL Connection
const db = mysql.createConnection({
host: process.env.MYSQL_HOST,
user: process.env.MYSQL_USER,
password: process.env.MYSQL_PASSWORD,
database: process.env.MYSQL_DATABASE
});
// Redis Connection
const redisClient = redis.createClient({
url: `redis://${process.env.REDIS_HOST}:6379`
});
redisClient.on('error', (err) => console.log('Redis Client Error', err));
app.get('/', async (req, res) => {
res.send('Node.js, MySQL, and Redis are running in Docker!');
});
app.listen(PORT, async () => {
await redisClient.connect();
console.log(`Server running on port ${PORT}`);
});
Step 2: Crafting the Dockerfile for Node.js
The Dockerfile is the blueprint for our Node.js container. We will use a multi-stage approach or a streamlined version for this tutorial to keep things efficient. In the root directory, create a Dockerfile:
FROM node:18-alpine # Create app directory WORKDIR /usr/src/app # Install app dependencies COPY app/package*.json ./ RUN npm install # Bundle app source COPY app/ . EXPOSE 3000 CMD [ "node", "index.js" ]
Pro Tip: Always include a .dockerignore file in your app/ folder to prevent node_modules and logs from being copied into the image. This significantly reduces image size and build time.
Step 3: Configuring MySQL for Persistence
When using MySQL in Docker, the biggest concern is data persistence. By default, data inside a container is ephemeral—if the container is deleted, the data is gone. To solve this in our tutorial setup docker compose mysql node js redis, we use Docker Volumes.
We will use the official MySQL 8.0 image. In the docker-compose.yml file (which we will build in Step 5), we will map a local directory to /var/lib/mysql inside the container. This ensures that even if you stop the containers, your database records remain intact.
Step 4: Implementing Redis for Caching
Redis is an in-memory data structure store, used as a database, cache, and message broker. In a Node.js environment, it is frequently used to store session data or cache expensive database queries. The setup for Redis is straightforward as it requires minimal configuration compared to MySQL. We will utilize the redis:alpine image for its small footprint and high performance.
Step 5: Orchestrating with docker-compose.yml
This is where the magic happens. The docker-compose.yml file integrates all the components of our tutorial setup docker compose mysql node js redis. It defines the services, networks, and volumes needed for the application to function as a unit.
version: '3.8'
services:
app:
build: .
ports:
- "3000:3000"
environment:
- MYSQL_HOST=db
- MYSQL_USER=user
- MYSQL_PASSWORD=password
- MYSQL_DATABASE=mydatabase
- REDIS_HOST=cache
depends_on:
- db
- cache
db:
image: mysql:8.0
restart: always
environment:
MYSQL_ROOT_PASSWORD: rootpassword
MYSQL_DATABASE: mydatabase
MYSQL_USER: user
MYSQL_PASSWORD: password
volumes:
- mysql-data:/var/lib/mysql
ports:
- "3306:3306"
cache:
image: redis:alpine
restart: always
ports:
- "6379:6379"
volumes:
mysql-data:
Key components explained:
- depends_on: Ensures that the database and cache containers start before the Node.js application.
- networks: Docker Compose creates a default network where services can reach each other using their service names (e.g., the app connects to
dbinstead oflocalhost). - environment: We pass sensitive information via environment variables. In a production setup, these should be stored in a
.envfile.
Step 6: Running and Testing the Entire Stack
With all files in place, it is time to launch your containerized application. Open your terminal in the root directory and run:
docker-compose up --build
The --build flag ensures that Docker builds the Node.js image from the local Dockerfile. Once the process completes, you should see logs from all three services. Open your browser and navigate to http://localhost:3000. You should see the message: “Node.js, MySQL, and Redis are running in Docker!”
To verify the database connection, you can use a tool like TablePlus or DBeaver to connect to localhost:3306 using the credentials defined in your docker-compose.yml.
Troubleshooting Common Docker Issues
Even with a perfect tutorial setup docker compose mysql node js redis, issues can arise. Here are the most common pitfalls and their solutions:
- Port Conflicts: If you already have MySQL or Redis running locally, Docker will fail to bind the ports. Either stop the local services or change the port mapping in
docker-compose.yml(e.g.,"3307:3306"). - Database Connection Refused: MySQL takes a few seconds to initialize. Even if the container is “running,” the database might not be ready for connections. Implementing a “wait-for-it” script is a common advanced solution.
- Permission Denied: On Linux, Docker might require
sudo. Ensure your user is added to thedockergroup.
Best Practices for Production Environments
While this setup is perfect for development, moving to production requires additional considerations:
- Use Environment Variables: Never hardcode passwords in your YAML files. Use a
.envfile and add it to.gitignore. - Resource Limits: Define CPU and Memory limits in Docker Compose to prevent one container from crashing the entire host.
- Multi-stage Builds: In your Dockerfile, use multi-stage builds to keep production images small by excluding development dependencies.
- Healthchecks: Add healthcheck parameters to your services so Docker can automatically restart unhealthy containers.
Conclusion and Next Steps
Congratulations! You have successfully completed this tutorial setup docker compose mysql node js redis. You now possess a powerful development stack that is portable, scalable, and standardized. This setup is the foundation for building modern web applications that can handle high traffic and complex data requirements.
To further your knowledge, consider exploring Docker Swarm or Kubernetes for orchestration at scale, or look into CI/CD pipelines to automate the deployment of your containerized app. The world of DevOps is vast, but with Docker Compose, you have taken the most important first step.