DEV Community

Cover image for Node.js REST API with Docker, Redis and MongoDB
Renato
Renato

Posted on

Node.js REST API with Docker, Redis and MongoDB

Hi guys, this is my first post and I want to share a simple Node.js REST API (Express) that includes Docker, Redis and MongoDB.

You can run this project with docker-compose, we won't explain anything about it but you refer these links Docker and Docker Compose. Check the repo link at the end to be able to run the GitHub project.

In the file api.js, we use mongoose to connect to MongoDB server:

mongoose.connect(`mongodb://${process.env.MONGO_INITDB_ROOT_USERNAME}:${process.env.MONGO_INITDB_ROOT_PASSWORD}@${process.env.MONGO_CONTAINER_NAME}/${process.env.MONGO_INITDB_DATABASE}?authMechanism=SCRAM-SHA-1&authSource=admin`,
    { useNewUrlParser: true, useCreateIndex: true, useFindAndModify: false, useUnifiedTopology: true }
, (err) => {
    if (err) {
        console.log('could\'t connect to Mongo DB ', err);
    }
});
Enter fullscreen mode Exit fullscreen mode

Inside libs/redis-client.js you can see the Redis connection:

const redis = require('redis');
const { promisify } = require('util');
const client = redis.createClient(process.env.REDIS_URL);

client.on("error", (error) => {
    console.error(`Error to connect Redis: ${error}`);
});
Enter fullscreen mode Exit fullscreen mode

Then let's use it:
mongoose -> api/routes/users.js. (Check User schema inside models/user)

// retrieve users
let users = await User.find({}).lean().exec();
Enter fullscreen mode Exit fullscreen mode

redis -> api/routes/users.js.

// retrieve user
const rawData = await redisClient.getAsync(req.params.email);
// save user
await redisClient.setAsync(req.params.email, JSON.stringify(user));
Enter fullscreen mode Exit fullscreen mode

The repo is available at: https://github.com/renacargnelutti/express-mongo-redis

I hope you enjoy the post!
Let me know any question.

Top comments (2)

Collapse
 
tsdmrfth profile image
Fatih Taşdemir

Where is Docker integration!

Collapse
 
renacargnelutti profile image
Renato

Hi dude! Sorry for being late.
This post is only a summary, you can check it out the complete code on GitHub. There check the 'docker' folder and the README.md.