Deploying a Node.js Application to AWS ECR and EC2 Instance

Posted by

Deploy Node Js App into AWS ECR and EC2 instance

Deploy Node Js App into AWS ECR and EC2 instance

Node.js is a popular runtime environment for building server-side applications. In this tutorial, we will go through the process of deploying a Node.js app into AWS ECR (Elastic Container Registry) and then onto an EC2 instance.

Step 1: Prepare your Node.js app

Before deploying your Node.js app, make sure that it’s ready for deployment. This includes ensuring that all necessary dependencies are installed and that the app is running smoothly on your local machine.

Step 2: Create a Docker image for your app

Once your app is ready, the next step is to create a Docker image for it. This can be done by creating a Dockerfile in the root of your project and then building the image using the following commands:

    
FROM node:12

WORKDIR /usr/src/app

COPY package*.json ./

RUN npm install

COPY . .

EXPOSE 3000

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

Step 3: Push the Docker image to AWS ECR

Once the Docker image is ready, you can push it to AWS ECR using the following commands:

    
aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin .dkr.ecr.us-west-2.amazonaws.com

docker build -t  .

docker tag :latest .dkr.ecr.us-west-2.amazonaws.com/:latest

docker push .dkr.ecr.us-west-2.amazonaws.com/:latest
    
  

Step 4: Launch an EC2 instance

After your Docker image is in ECR, the next step is to launch an EC2 instance on AWS to run your app. You can follow the AWS documentation for launching an EC2 instance and then SSH into the instance to continue.

Step 5: Pull the Docker image onto the EC2 instance and run the app

Once logged into the EC2 instance, use the following commands to pull the Docker image from ECR and run your app:

    
aws ecr get-login-password --region us-west-2 | docker login --username AWS --password-stdin .dkr.ecr.us-west-2.amazonaws.com

docker pull .dkr.ecr.us-west-2.amazonaws.com/:latest

docker run -d -p 3000:3000 .dkr.ecr.us-west-2.amazonaws.com/:latest
    
  

Conclusion

Congratulations! Your Node.js app is now deployed into AWS ECR and running on an EC2 instance. You can now access your app by navigating to the public IP address of your EC2 instance on port 3000 in a web browser.