Deploying a Node.js Server with MySQL Database: A Dockerized Approach

Posted on May 6, 2024

Dave Herring

I’d be glad to provide a comprehensive guide on setting up a Node.js server with a MySQL database, containerizing them in Docker, and deploying them to a remote server. This guide incorporates code samples, Linux commands with explanations, and best practices to ensure a smooth and efficient process.

Prerequisites:

  • Node.js and npm: Ensure you have Node.js and npm installed on your development machine. You can download and install them from the official Node.js website (https://nodejs.org/).
  • Docker: Install Docker on your development machine. Refer to the official Docker documentation (https://docs.docker.com/get-docker/) for installation instructions specific to your operating system.

Project Setup:

  1. Create a Project Directory:
  • Open your terminal and create a new directory for your project:
mkdir nodejs-mysql-docker
cd nodejs-mysql-docker
  1. Initialize Node.js Project:
  • Initialize a new Node.js project within the directory:
npm init -y
  1. Install Dependencies:
  • Install the required dependencies for your Node.js application:
npm install express mysql2

Node.js Server Development:

  1. Create index.js File:
  • Create a file named index.js in your project directory. This file will serve as your Node.js server entry point.
  1. Implement Server Logic (Example):
  • Add the following code to index.js to create a basic Node.js server that connects to a MySQL database:
const express = require('express');
const mysql = require('mysql2/promise');

const app = express();
const port = 3000;

const connectionPool = mysql.createPool({
host: 'mysql-container', // Replace with your MySQL container name or IP
user: 'your_username',
password: 'your_password',
database: 'your_database',
connectionLimit: 10
});

app.get('/', async (req, res) => {
try {
const [rows] = await connectionPool.query('SELECT * FROM your_table');
res.json(rows);
} catch (err) {
console.error(err);
res.status(500).send('Error fetching data');
}
});

app.listen(port, () => {
console.log(`Server listening on port ${port}`);
});
  • Replace the placeholders with your actual MySQL database credentials and table name.

Dockerfile Creation:

  1. Create Dockerfile:
  • Create a file named Dockerfile in your project directory. This file specifies the instructions for building your Docker image.
  1. Define Base Image:
  • Specify the base image as node:18-alpine:
FROM node:18-alpine
  1. Set Working Directory:
  • Set the working directory within the container:
WORKDIR /app
  1. Copy Package.json and package-lock.json:
  • Copy the package.json and package-lock.json files into the container:
COPY package*.json ./
  1. Install Dependencies:
  • Install the required Node.js dependencies:
RUN npm ci
  1. Copy Application Code:
  • Copy the remaining application code (e.g., index.js) into the container:
COPY . .
  1. Expose Port:
  • Expose the port on which your Node.js server will listen:
EXPOSE 3000
  1. Define Command:
  • Specify the command to execute when the container starts:
CMD [ "npm", "start" ]

Docker Compose Setup:

  1. Create docker-compose.yml File:
  • Create a file named docker-compose.yml in your project directory. This file defines the services (Node.js and MySQL) to be included in your Docker composition.
  1. Define Services:
  • Add the following content to docker-compose.yml:
version: '3.8'

services:
node-app:
build: .
ports:
- "3000:3000"
depends_on:
- mysql

mysql:
image: mysql:8.0
environment:
MYSQL_ROOT_PASSWORD: your_root_password
MYSQL_DATABASE: your_database
MYSQL_USER: your_username
MYSQL_PASSWORD: your_password
volumes:
- mysql-data:/var/lib/mysql
volumes:
mysql-data:
  • Replace the placeholders with your actual MySQL credentials and database name.

Building and Running the Docker Containers:

  1. Build Images:
  • Build the Docker images for both services:
docker-compose build
  1. Run Services:
  • Start the containers:
docker-compose up -d

Remote Server Deployment:

  1. Push Images to Docker Hub (Optional):
  • If you want to deploy your application to a remote server, you can push your Docker images to a container registry like Docker Hub:
docker login
docker tag node-app your_username/node-app:latest
docker push your_username/node-app:latest

docker tag mysql mysql:8.0
docker push mysql:8.0
  1. Pull Images on Remote Server:
  • On your remote server, pull the Docker images:
docker pull your_username/node-app:latest
docker pull mysql:8.0
  1. Run Docker Compose:
  • Run the Docker Compose file to start the services on the remote server:
docker-compose -f docker-compose.yml up -d

Additional Considerations:

  • Environment Variables: Consider using environment variables to store sensitive information like database credentials. You can define them in the docker-compose.yml file or set them as environment variables when running docker-compose up.
  • Security: For production environments, implement security measures like SSL/TLS encryption for communication between the Node.js server and the MySQL database.
  • Persistence: If you need to persist data, you can use Docker volumes to store the MySQL database data outside the container.

By following these steps and incorporating the best practices, you’ll have a well-structured and containerized Node.js application with a MySQL database, ready for deployment to a remote server.

comments powered by Disqus