Building a modern application that includes a web server, a backend application, and a database requires coordinating several software components effectively. Docker Compose is a tool that simplifies the process of defining and managing Docker multi-container applications. In this article, we will explore how to set up an application that uses Nginx as a reverse proxy for a Node.js application, with MySQL as the backend database.
Architecture Overview
Our application will consist of three main services:
- MySQL: the database that stores the application data.
- Node.js: the backend application that interacts with the database.
- Nginx: the web server that acts as a reverse proxy for the Node.js application, improving security and performance.
Step 1: Project Setup
Create a new directory for the project and create the following subdirectories and files inside it:
db
: a directory for any MySQL initialization scripts.app
: a directory for the application source code Node.js.nginx
: a directory for configuring Nginx.docker-compose.yml
: the file of Docker Compose configuration.
Step 2: Configuring Docker Compose
The docker-compose.yml
file defines the services, networks, and volumes that make up the application. Here is an example of how it could be configured:
version: '3.8'
services:
db:
image: mysql:5.7
volumes:
- db-data:/var/lib/mysql
environment:
MYSQL_ROOT_PASSWORD: example
MYSQL_DATABASE: mydatabase
networks:
- app-network
apps:
build: ./app
depends_on:
- db
environment:
DB_HOST: db
DB_USER: root
DB_PASSWORD: example
DB_NAME: mydatabase
networks:
- app-network
nginx:
image: nginx:latest
ports:
- "80:80"
volumes:
- ./nginx:/etc/nginx/conf.d
depends_on:
- app
networks:
- app-network
volumes:
db-data:
networks:
app-network:
drivers: bridge
Step 3: Configuring the Node.js App
In the app
directory, create a simple Node.js server that connects to MySQL and responds to HTTP requests. Use the express
module for the server and mysql
to connect to MySQL.
Step 4: Configuring Nginx
In the nginx
directory, create an Nginx configuration file, default.conf
, that configures Nginx as a reverse proxy for your Node.js application. The file must direct requests to the app
service.
Step 5: Building and Launching the Application
After configuring all the components, you can build and launch the application with Docker Compose by running:
docker-compose up --build
This command will build the Node.js application image, download the MySQL and Nginx images if they are not already present, and start the containers. The services will now be accessible: Nginx will listen on port 80 of your host, acting as a reverse proxy to the Node.js application, which in turn interacts with the MySQL database.
Conclusion
You have successfully created a multi-container application with Docker Compose, which includes a Node.js server, a MySQL database, and Nginx as a reverse proxy. This configuration offers a solid starting point for developing robust and scalable applications.