Running redis using docker-compose and nodejs

Placeholder image

Aug 4, 2023

Redis Logo

In this tutorial, we’ll learn how to run Redis using Docker Compose and build a simple Node.js application that utilizes Redis capabilities for caching. Redis and Docker Compose make it easy to set up and manage containers for development and testing environments.

Running Redis with Docker Compose and Building a Simple Node.js App

In this tutorial, we’ll learn how to run Redis using Docker Compose and build a simple Node.js application that utilizes Redis capabilities for caching. Redis and Docker Compose make it easy to set up and manage containers for development and testing environments.

Prerequisites

Before you begin, ensure you have the following installed on your system:

  1. Docker: Install Docker
  2. Docker Compose: Install Docker Compose
  3. Node.js: Install Node.js

Step 1: Setting Up Docker Compose File

First, let’s create a docker-compose.yml file in a directory of your choice. This file will define the Redis service and our Node.js app service.

version: '3'
services:
  redis:
    image: redis:latest
    container_name: my-redis-container
    ports:
      - "6379:6379"
    networks:
      - my-network

  node-app:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: my-node-app-container
    ports:
      - "3000:3000"
    environment:
      - REDIS_HOST=redis
    depends_on:
      - redis
    networks:
      - my-network

networks:
  my-network:

In the above docker-compose.yml, we define two services: redis and node-app. The redis service will use the official Redis Docker image, and the node-app service will be built using the current directory (where our Node.js app will reside).

We expose port 6379 for Redis, and port 3000 for our Node.js app. We also set the REDIS_HOST environment variable for the Node.js app to connect to the Redis service.

Step 2: Create a Simple Node.js App

Now, let’s create a simple Node.js application that uses Redis for caching. Create a new file named app.js in the same directory as your docker-compose.yml file. Here’s a basic example:

npm init
npm install express redis
const express = require('express');
const redis = require('redis');

const app = express();
console.log(process.env.REDIS_HOST);
const client = redis.createClient({url: `redis://${process.env.REDIS_HOST}:${process.env.REDIS_PORT}`});

(async () => {
    client.on('error', err => console.log('Redis Client Error', err));
    await client.connect()
})();

// Route to fetch data with caching
app.get('/data', async (req, res) => {
    const key = 'cached_data';
    console.log('got request')

    const cachedData = await client.get(key);
    
    if (cachedData) {
        // Data found in cache, return it
        res.json({source: 'cache', data: JSON.parse(cachedData)});
    } else {
        const data = {message: 'Hello, Redis!'};

        // Store data in cache for next request
        await client.set(key, 60, JSON.stringify(data));

        res.json({source: 'database', data});
    }
});

const port = 3000;
app.listen(port, () => {
    console.log(`Server is running on http://localhost:${port}`);
});

In this simple app, we use the Express.js framework and the redis npm package to interact with Redis. When a client makes a GET request to /data, the app will first check if the data exists in the Redis cache. If the data is cached, it will be returned. Otherwise, the app will simulate fetching data from a database, store it in the Redis cache, and then return it to the client.

Step 3: Create a Dockerfile for the Node.js App

Next, let’s create a Dockerfile in the same directory as your docker-compose.yml and app.js. The Dockerfile defines the environment and configuration for building the Node.js app container.

Create a file named Dockerfile with the following content:

# Use the official Node.js image as base
FROM node:18

# Set the working directory in the container
WORKDIR /app

# Copy package.json and package-lock.json to the container
COPY package*.json ./

# Install app dependencies
RUN npm install

# Copy the rest of the application code to the container
COPY app.js .

# Expose the port on which the Node.js app will run
EXPOSE 3000

# Command to start the Node.js app
CMD ["node", "app.js"]

In the Dockerfile, we use the official Node.js image as the base, set the working directory to /app, and copy the necessary files to the container. We install the Node.js dependencies and expose port 3000, which is the port the Node.js app will listen on.

Step 4: Build and Run the Application

Now that we have our Docker Compose file and Node.js app set up, let’s build and run the application.

  1. Build the Node.js app image and start the containers:
docker-compose up -d --build

Step 5: Test the Application

Open your web browser or use a tool like curl or Postman to test the application. Visit http://localhost:3000/data in your browser or use the following command in your terminal:

curl http://localhost:3000/data

On the first request, you should see the message “Hello, Redis!” returned with a source of “database.” On subsequent requests made within 60 seconds, the response will be “Hello, Redis!” with a source of “cache,” indicating that the data was retrieved from the Redis cache.

Step 6: Stop the application

Now let’s stop the application and remove the containers. Run the following command:

docker-compose down

Conclusion

In this tutorial, we learned how to run Redis using Docker Compose, which simplifies the process of setting up and managing multiple containers. We also built a basic Node.js app that utilizes Redis for caching, providing a simple example of how Redis can improve the performance of applications by storing frequently accessed data in memory. Remember that this is just a starting point, and you can explore many more possibilities with Redis and Docker. Happy coding!

Tags