Using Redis with Docker and NodeJS/Express

Akhilesh Sharma
Geek Culture
Published in
4 min readApr 15, 2021
https://unsplash.com/photos/EaB4Ml7C7fE?utm_source=unsplash&utm_medium=referral&utm_content=creditShareLink

In this article, I will walk through the steps to install REDIS using DOCKER on your local machine and access the docker container services within the locally running node/expressJS application.

Pre-Reqs

I am assuming that you have the basic setup on your local machine such as Node Package Manager, Docker and do have a fair understanding of Javascript, NodeJS, Express, REDIS, and Docker.

Let’s Begin

I will begin with the construct to install REDIS using docker and then move towards the usage in the local dev environment.

Install REDIS using DOCKER

To accomplish this step, fire up your terminal and execute the following command.

docker run -d --name <CONTAINER_NAME> -p 127.0.0.1:6379:6379 redis
  • run — create and start the container
  • d — runs the container in the detached mode
  • — name <CONATINER_NAME> — Assigns the name to the container.
  • p — maps the port as well the IP to the local machine. This is the catch here to enable the services locally. If you create the image without the local mapping, then you will not be able to access this information. 6379 is the default port for REDIS.
  • Redis — Name of the image to be downloaded.
docker ps -a

This command will show you the list of all the containers that are associated with docker on your machine.

docker exec -it <CONTAINER_NAME|ID> sh

If you have provided the name to your container then use the name or utilize the ID associated with the container.

To test your installation, proceed as follows and run some basic REDIS commands

# redis-cli
127.0.0.1:6379> ping
PONG
127.0.0.1:6379> set customer_name "John Doe"
OK
127.0.0.1:6379> get customer_name
"John Doe"
127.0.0.1:6379> del customer_name
(integer) 1
127.0.0.1:6379> exit
# exit

Basic ExpressJS App Setup

As we are all set with the REDIS installation, let proceed forward to create a small ExpressJS application.

Go to your terminal and execute the following commands

npm init

The init command will run you through a terminal-based wizard to provide the defaults for the package.json file.

npm i -P express
npm i -D nodemon

The commands above will install the dependencies required for development.

Open up the package.json file in an editor of your choice and add the following command under the script section.

"dev": "nodemon server"

Next, open up your index.js/server.js(main) and add the following snippets to create a basic ExpressJS application.

const express = require('express');const PORT = 5001;const app = express();
const router = express.Router();
app.use(express.json());router.get('/', (req,res) => {
res.status(200).json({
message : "Sample Docker Redis Application"
});
});
app.listen(PORT, () => {
console.log(`Server running on PORT ${PORT}`);
});

Our basic ExpressJs App is ready.

Next, start the server.

npm run dev

Open up a new terminal instance and check if the application is working correctly or not by using the “cURL” command. The output will look like something similar to this.

HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: application/json; charset=utf-8
Content-Length: 45
ETag: W/"2d-bO6czhAp6+qsrxSQWqx38pGjRvo"
Date: Thu, 15 Apr 2021 18:14:24 GMT
Connection: keep-alive
Keep-Alive: timeout=5
{"message":"Sample Docker Redis Application"}

Accessing REDIS via Application

To access REDIS, we need access to the REDIS client within our application.

Go to your terminal -> App Root Folder

npm i -P redis

This installs REDIS support to your application.

Open up server.js/index.js (main) file in the editor and make changes to the enable access.

const redis = require('redis');const redisClient = redis.createClient(6379,'127.0.0.1');redisClient.on('error', (err) => {
console.log('Error occured while connecting or accessing redis server');
});
if(!redisClient.get('customer_name',redis.print)) {
//create a new record
redisClient.set('customer_name','John Doe', redis.print);
console.log('Writing Property : customer_name');
} else {
let val = redisClient.get('customer_name',redis.print);
console.log(`Reading property : customer_name - ${val}`);
}

When you save the file, as we have nodemon watching our asset changes, the server will restart.

[nodemon] starting `node server.js`
Writing Property : customer_name
Server running on PORT 5001
Reply: null
Reply: OK

Restart the server either by killing the thread or saving the file again. Now it will read the property from REDIS and display it on the console.

[nodemon] restarting due to changes...
[nodemon] starting `node server.js`
Writing Property : customer_name
Server running on PORT 5001
Reply: John Doe
Reply: OK

To further check if the information is stored successfully in the instance or not. “SSH” into the container as explained earlier in the tutorial and read the property.

Alrighty, that’s it. We are all set to access the REDIS within our local application. This concludes this article for now.

If you like the article, feel free to share it.

Access to the sample code @ https://github.com/cmgabriel/docker_redis_express

Thanks for your time reading and Happy Coding!

--

--

Akhilesh Sharma
Geek Culture

Simple | Goal Oriented | Self-Driven | Ever-Learning | Tech Enthusiast | Cloud Architect