Dockerized Node.js Application with MongoDB Integration: Deployment to AWS ECR
Published: 2023-05-29 10:59:44

Docker has revolutionized the way developers build, deploy, and manage applications. With its containerization technology, Docker provides a consistent and reliable environment for running applications across different platforms. 

This project focuses on leveraging Docker to develop and deploy a Node.js application that interacts seamlessly with MongoDB. The goal is to create a local development environment by pulling a Docker image of MongoDB from DockerHub and connecting it to a Node.js application. The successful connection will be verified, ensuring that the application can interact with the MongoDB database effectively.

Next, the project aims to containerize the Node.js application using Docker and create a custom Docker image. This image will include the necessary dependencies and configurations to ensure the application runs smoothly. The Docker image will then be pushed to an AWS ECR (Elastic Container Registry) private repository, allowing for secure storage and management of the image. 

Let's get started!

### Prerequisites:
Before you get started, please ensure you have the following:

- Set up your AWS account.

- Complete the Amazon ECR setup steps. You can find information on how to [setting up for Amazon ECR](https://docs.aws.amazon.com/AmazonECR/latest/userguide/get-set-up-for-amazon-ecr.html).

- The user that you are using should have IAM permissions to access and use Amazon ECR. To find more information, [see](https://docs.aws.amazon.com/AmazonECR/latest/userguide/security-iam-awsmanpol.html)

- Have Docker installed on your machine.

- Set up AWS CLI installed and configured. 

- Set up MongoDB Atlas [account](https://www.mongodb.com/cloud/atlas/register) and create a [database](https://www.mongodb.com/docs/atlas/atlas-ui/databases/).

- Download or clone [the starter project on this repository](https://github.com/OloruntobiOlurombi/Biggy-Finesse) and init the application. 

### Connecting the Node.Js Application with MongoDB

Now that we have sorted out our prerequisites, we can proceed to connect the Node.Js application to the MongoDB Atlas database. Using the appropriate MongoDB driver for Node.Js such as Mongoose with our connection string from the MongoDB database that was create, we can establish a seamless connection to the database. By configuring the connection parameters within our Node.JS application, we ensure that the application can communicate with the MongoDB container.

To do this access the database that was created and click on ***Connect***:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/6pwwt9qrtzpzhqrxinb9.png)

On the Connect to Cluster page select the ***Drivers*** option:

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

This will take you to the Connecting with MongoDB Driver page, navigate to the third step "***Add your connection string into your application code***" and copy the connection string:

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

```
mongodb+srv://<username>:<password>@cluster0.ujj4x8j.mongodb.net/?retryWrites=true&w=majority
```
It is now time to paste MongoDB connection string to the Node.JS that was clone to our local system. Let us locate the directory called "***db***" and open "***connection.js***" file:

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

Find the variable MONGO_URL and update the value to your connection string: 

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9zwzj3bdittxfyhztdbi.png)

```
import mongoose from "mongoose";

const MONGO_URL = "mongodb+srv://username:password@cluster0.ujj4x8j.mongodb.net/?retryWrites=true&w=majority";

const connect = async () => {
    try {
        await mongoose.connect(MONGO_URL , {
            useNewUrlParser : true,
            useUnifiedTopology : true
        });
        console.log("Connected to db");
    } catch (error) {
        throw error
    }
}

mongoose.connection.on("disconnected" , () => {
    console.log("db disconnected");
})

export default connect;
```
It is time to test our connection by starting our applications using docker-compose:

```
docker compose up --build
```
If you see the following outcome, then you are good to go:


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


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


The next thing would be to access the Node.JS application on a web browser using localhost:8000, create a new user and confirm from the backend:

```
localhost:8000
```

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/4wlg9r0mu2xma4idj0jx.png)


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

We have got our application up and running for the next step, we need to stop the containers running our application. This will be done using:

```
docker compose down
```

### Pushing the Docker Image to AWS ECR

To deploy our containerized application on a cloud platform, we will utilize Amazon Elastic Container Registry (ECR), which is a fully-managed Docker container registry provided by AWS. Before pushing the Docker image to ECR, we need to create a private repository within ECR to store our image.

Go to the AWS Console and search for the keyword ECR:

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

Click on the ***Get started*** Button:


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

Fill the Create Repository form and ***create repository***:

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


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


Please confirm that the Private Repository is created successfully: 

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

Once the repository is set up, we can authenticate our Docker CLI to interact with the ECR service. By executing a few commands:

- First we have to build the Node.JS application locally using docker:

```
docker build -t my-app-biggy-finesse:1.0 .
```

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

- Retrieve an authentication token and authenticate your Docker client to your registry. Use the AWS CLI:

```
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 611512058***.dkr.ecr.us-east-1.amazonaws.com
```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9f3n9f0nls3heq37mgc8.png)

- After the build and authentication stage are completed, tag your image, so you can push the image to this repository:

```
docker tag my-app-biggy-finesse:latest 611512058022.dkr.ecr.us-east-1.amazonaws.com/my-app-biggy-finesse:latest
```

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

- Confirm the tag was completed:

```
docker images
```

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


- Run the following command to push this image to your newly created AWS repository:

```
docker push 6115120580**.dkr.ecr.us-east-1.amazonaws.com/my-app-biggy-finesse:latest

```

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8dgyxfc3g4v1s0tybo62.png)

- Confirm on the AWS console that the push was done successfully:


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

### With these we have come to the end of this article and I hope it will be of great help to someone out there.

Feel free to connect with me on [Linkedin](https://www.linkedin.com/in/olurombi-oloruntobi/).

Stay Healthy Folks!!!