Build Nodejs API with Redis, MongoDB in Docker
Tags: cloud, docker, node, javascript
Published: 2024-04-01 19:23:56

The benefits of docker can not be understated as it facilitates software development regardless of whatever platform a developer is using.

I built an API using Nodejs, Redis and MongoDB and I wanted to containerise the API using Docker. 

Here are the processes or steps, I followed to be able to containerise the API. Here is a [Github link](https://github.com/MasterIfeanyi/ifeanyi-production-API) to the API.


### Redis

**Change the API code**

We need to change our nodejs API code to configure the redis client to be able to connect to a redis server running in the docker container.

```javascript

// src/index.js

export const client = createClient({
    socket: {
        port: 6379,
        host: "redis"
    }
});

```


**Download a redis image:**

```
docker pull redis
```



**Create a container:** We are going to create a redis container from the image we just downloaded. 

*Port-forwarding*, when you want to create a container remember to implement port-forwarding because when you have a container running, the ports you declare in your code while running in the container will only refer to the port of the container and not the host (local) machine where docker is running on.

```
docker run -d -p 6379:6379 --name redisCont redis
```





![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fplf4ygogbaso7gns9qp.gif)


### MongoDB
 
We will repeat the same process for mongoDB.

**Change the API code:**

```javascript

export const connectDB = async () => {
    try {
        await mongoose.connect('mongodb://mongo/instaCartDB', { // ->this line
            useUnifiedTopology: true,
            useNewUrlParser: true
        }) 
    } catch (error) {
        console.error(error)
    }
}

```
**note**

We change the initial hostname (localhost or `127.0.0.1`) to mongo in the connection URI, this is to allow the DNS resolve to the appropriate container on docker.

**Download a mongoDB image:** for some reason, mongoDB version 5.0 docker image was throwing an error of `WARNING: MongoDB 5.0+ requires a CPU with AVX support, and your current system does not appear to have that!`. 

Hence, I had to downgrade to mongoDB version `4.4.6` docker image.

```
docker pull mongo:4.4.6
```

**Create a Container:** We are going to create a mongoDB container from the image we just downloaded. Also, remember to implement port-forwarding here as well.

```
docker run -d -p 27017:27017 --name mongodbCont mongo:4.4.6
```


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/11xfpunjplp351ex9esc.gif)



### Dockerfile

So, after building the API I created a `dockerfile` and then I built a `docker` image using the following syntax.

```

FROM node:20-alpine

LABEL maintainer="chima@gmail.com"

WORKDIR /app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3500

CMD ["node", "index.js"]


```

```docker
docker build -t prod-API-image .
```



### Finally, running containers

You have to link your redis container and mongoDB to your Nodejs API using docker.

```
docker run -d --link redisCont:redis --link mongodbCont:mongo -p 4000:4000 --name my-nodejs-api prod-API-image

```

### References

[How to dockerize a nodejs api](https://dev.to/liza_____/step-by-step-tutorial-on-how-to-dockerize-a-nodejs-api-with-a-mongodb-database-27f0)

[Getting started with docker](https://github.com/championshuttler/docker-basicLearning?tab=readme-ov-file#writing-your-first-dockerfile)

[Dockerize a Node.js app connected to MongoDb](https://itnext.io/dockerize-a-node-js-app-connected-to-mongodb-64fdeca94797)


<a href="https://www.buymeacoffee.com/ifeanyichima" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Me A Coffee" height="41" width="174"></a>

**Thank you, Please follow me**

[![HTML](https://img.shields.io/badge/LinkedIn-0077B5?style=for-the-badge&logo=linkedin&logoColor=white)](https://linkedin.com/in/ifeanyi-thankgod-chima)&nbsp;[![GitHub](https://img.shields.io/badge/GitHub-100000?style=for-the-badge&logo=github&logoColor=white)](https://github.com/masterifeanyi)