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 aGithub link 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.
// src/index.jsexportconstclient=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
MongoDB
We will repeat the same process for mongoDB.
Change the API code:
exportconstconnectDB=async()=>{try{awaitmongoose.connect('mongodb://mongo/instaCartDB',{// ->this lineuseUnifiedTopology:true,useNewUrlParser:true})}catch(error){console.error(error)}}
note
We change the initial hostname (localhost or127.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 ofWARNING: 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 version4.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
Dockerfile
So, after building the API I created adockerfile
and then I built adocker
image using the following syntax.
FROM node:20-alpineLABEL maintainer="chima@gmail.com"WORKDIR /appCOPY package*.json ./RUN npm installCOPY . .EXPOSE 3500CMD ["node", "index.js"]
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
Dockerize a Node.js app connected to MongoDb
Thank you, Please follow me
Top comments(0)
For further actions, you may consider blocking this person and/orreporting abuse