In this guide, we'll walk through Deploy NodeJS REST API on ECS Fargate using AWS CodePipeline.
=> Create nodejs app using express framework
- Create folder and run npm init.
=> Will be using Express framework to deploy the Node.js-based REST API.
=> Create an index.js file and paste the code into the current directory
'use strict'
const express = require('express');
const client = require('prom-client');
// Create a Registry to register the metrics
const register = new client.Registry();
client.collectDefaultMetrics({ register });
const PORT = 8080;
const HOST = '0.0.0.0';
const app = express();
// Define the route for the root path ("/")
app.get('/', (req, res) => {
const sentence = 'Welcome to the Automation world';
// Send the sentence as the response
res.json({ sentence });
});
app.get('/metrics', async(req, res) => {
res.setHeader('Content-Type', register.contentType);
res.send(await register.metrics());
});
app.get('/ping', (req, res) => {
res.status(200).json({ message: "pong" })
});
app.get('/error', (req, res) => {
// Simulating an internal server error (500)
const error = new Error('Internal Server Error');
res.status(500).json({ error: error.message });
});
app.listen(PORT, HOST);
console.log('running on http://${HOST}:${PORT}')
=> Add Dockerfile to build the nodejs app
FROM node:16.18
WORKDIR /usr/src/app
COPY . .
RUN npm ci --only=production
EXPOSE 8080
USER node
CMD ["node", "index.js"]
=> Run the 'docker build' command to create the Docker image.
docker build -t nodeapp:v1 .
========================================================
AWS CodeBuild Setup
- Create Repository in AWS ECR
- Setup Source Provider
- Create service role
Configure the Source Provider and authenticate using the GitHub provider.(Authenticate by generating a personal access token in GitHub. Navigate to GitHub's Developer Settings to create the token)
- Grant ECR permissions to the CodeDeploy service role.
- CodeBuild has successfully pushed the image to ECR
========================================================
AWS Code deploy Setup
- Create ECS Cluster
- Create Task definition in AWS ECS
- Create Service in AWS ECS
- Retrieve the IP address from the task definition and access it via the browser by pasting the IP
http://13.235.73.88:8080/
http://13.235.73.88:8080/ping
========================================================
AWS Code Pipeline Setup
- Enter the pipeline name in step 1 and in other steps fill up the source,build and deploy stage.
- AWS Code pipeline status
If you prefer a video tutorial to help guide you through the process to setup AWS CodePipeline with ECS
Happy by Deploying NodeJS Rest API in AWS ECS !
Top comments (0)