Friday, July 12, 2024

How to Set Up Blue Green Deployment on an EC2 Instance for an Angular Application Using AWS CodeDeploy Pipeline with GitHub [Part - I ]

Description: In this blog, we'll walk through setting up a Blue Green deployment.Deployment strategy for an Angular application hosted on Amazon EC2 instances.

Blue-Green Deployment allows for zero-downtime updates, ensuring that users experience seamless transitions during application updates. This setup will leverage AWS services, including EC2, Auto-Scaling, Load Balancing, and Code Deploy.





Application Deployment: Traditional vs Blue-Green pipeline

When delivering an application traditionally, a failed deployment is usually fixed by redeploying an older, stable version of the application.

Due to the expense and time involved in provisioning additional resources, redeployment in traditional data centers often uses the same set of resources

This strategy works, but it has a lot of drawbacks. Rollbacks are difficult to implement since they necessitate starting from scratch with a previous version. 

Since this process takes time, the application can be inaccessible for extended periods of time. Even though the application is simply compromised, a rollback is necessary to replace the flawed version. 

As a result, you are unable to troubleshoot the existing problematic program.

Blue-Green Deployment is an application release methodology in which you create two separate but identical environments. The traffic from the current version (blue environment) of an application or micro-service is transferred to a newer version(green environment), both of which are already in production.

After the green environment has undergone testing, the blue environment is deprecated, and actual application traffic is switched to the green environment.

The blue-green deployment methodology increases application availability and lowers deployment risk by simplifying the rollback process if a deployment fails.


Advantages of Blue-Green Deployment

It is challenging to validate your new application version in a production deployment while also continuing to use the older version of the program when using a traditional deployment with in-place upgrades. 

Your blue and green application environments will be somewhat isolated thanks to blue/green deployments. 

This makes sure that creating a parallel green environment won’t have an impact on the resources supporting your blue environment. The danger of deployment is decreased by this separation.


Steps to set up Blue-Green Deployment with an Angular Application with EC2

Step1: In-Placed Deployment, First we are going to setup In-placed deployment using AWS Code-deploy with Angular


Setup EC2 instance with Nginx and setup custom directory for angular with below configuration

OS: Ubuntu 22
Instance Type: t2.micro
Role: Nginx
Tag:  Name = Angular-Instance


Install and start nginx, start the service
# apt update
# apt install -y  nginx
# systemctl start nginx
# systemctl enable nginx


Create project directory
# cd /var/www
# mkdir my-angular

Change it in default document root
File: /etc/nginx/sites-available/default

Change root directory  from
/var/www/html
TO
root /var/www/my-angular;

Restart nginx
# service nginx restart 

Browse the URL with public IP of machine shows 403

Install AWS code deploy agent in EC2 instance 

[In this example I used Ubuntu image]

Below are the command to setup agent and service for code deploy

# apt update
# apt install -y ruby-full
# apt install wget
# cd ~
# wget https://bucket-name.s3.region-identifier.amazonaws.com/latest/install

For us-west-1 region url is as follow
# wget https://aws-codedeploy-us-west-1.s3.us-west-1.amazonaws.com/latest/install

Reference URL:
https://docs.aws.amazon.com/codedeploy/latest/userguide/resource-kit.html#resource-kit-bucket-names
https://docs.aws.amazon.com/codedeploy/latest/userguide/codedeploy-agent-operations-install-ubuntu.html


# chmod +x ./install
# sudo ./install auto
# systemctl start codedeploy-agent
# systemctl enable codedeploy-agent



Step2 -Setup Github Angular repo with appsepc.yml and buildspec.yml 

Below is the Github project URL with  appsepc.yml and buildspec.yml

Github Project URL : https://github.com/harpal1990/angular-ec2-project


appsepc.yml: The appspec.yaml file is used to specify the deployment actions to be taken by CodeDeploy, It  is a crucial configuration file used in AWS CodeDeploy for defining the deployment actions and specifying how AWS CodeDeploy should manage the deployment process for your application. This file includes details about the files to be transferred, the destination of those files, and the lifecycle event hooks that allow you to run custom scripts at various stages of the deployment.

version: 0.0 os: linux files: - source: dist/my-angular-project destination: /var/www/my-angular permissions: - object: /var/www/my-angular pattern: '**' mode: '0755' owner: root group: root type: - file - directory hooks: ApplicationStart: - location: deploy-scripts/application-start-hook.sh timeout: 300

 

buildspec.yml:  It is is a configuration file used by AWS Code Build to define the build process for your application. This file specifies the commands to run during the build, including installing dependencies, running tests, and packaging the application. It also defines the artifacts to be produced and can include environment variables and other settings.

version: 0.2 phases: install: runtime-versions: nodejs: 12 commands: - npm install -g @angular/cli@9.0.6 pre_build: commands: - npm install build: commands: - ng build --prod finally: - echo This is the finally block execution! artifacts: files: - 'dist/my-angular-project/**/*' - appspec.yml - 'deploy-scripts/**/*'


Step3: Setup Code Build Project for prepare build project and upload it to S3 bucket 

To create the build project navigate to AWS Devleoper Tools --> Build --> Build Projects --> Create Project 




After click on create project, fill all the require details, click on connect to Github to connect


After connect the Github, Click on webhook trigger "Rebuild everytime a code change pushed to the repository"


Set Environment for Build

 

 

Define buildspec configuration: we have already upload buildspec.yml in root path with repository, so here we only define the buildspec.yml file with same name

Artifacts: We are going to save artifacts into s3, So I have created one bucket to store the artifacts



Logs: We can stored build logs in cloudwatch and S3 bucket as well and click on create project



Once project created, test build by click on start build



Once build completed, you will get message as follow, also you will get build in s3 bucket as well



 S3 Bucket


Step4: Create Application and Deployment Group  in Code-deploy to deploy the application in EC2 instance 

To create the application, navigate to CodeDeploy --> Create application




Fill name and Compute platform --> EC2/on-premise

After create application, Create deployment group and fill all the details

Service Role: CodeDeployEC2Role

Deployment type: In place 


Environment Type: Amazon EC2 Instance, Also define Tag which we have setup while setting up the machine

[Note: Here we are applying in placed deployment on standalone machine without auto-scaling]

Define Deployment Setting: Deployment All at once, click on Create Deployment Group



Step5: Setup IAM role for EC2 Instance and attach it to EC2 instance

Create Role with below permission policies

  • AmazonEC2FullAccess
  • AmazonS3FullAccess
  • AmazonEC2RoleforAWSCodeDeploy
  • AWSCodeDeployRole

 


After create the IAM role attach to EC2 instance  



Step6: Create Pipeline for automatic deployment on EC2 Instance
 
To create pipeline navigate to pipeline --> create pipeline fill all the details
 
Create new role for pipeline and click on Next 

 




Source: Filled all the source details like repository and branch name, change the detection option for trigger


Build: Filled all details regarding the build project 


Deploy: Fill all the details for deploy Application Name and Deployment Group


Review: Review the settings and click on create pipeline, Once you click on create it will create to run pipeline 


Once the code pipeline executed, you can see the source code extracted to webroot path


Also we can validate by browse the public IP of EC2 instance

So this is how you can setup standalone EC2 instance with angular using code deploy pipeline. 

In the next topics: we will setup code deploy In-placed and Blue Green deployment with auto-scaling and load balancer


Wednesday, January 24, 2024

How to Deploy a Dockerized React App Using Azure DevOps Pipelines

Description:  In this topic I am going to explain, How to setup React Application to Docker Image and upload image to Azure ACR [Azure Container Registry] to deploy the Dockerized React APP to Azure App service 


Prepare the React Application

First I am setting up the React Application using command line 

# mkdir reactapp

# cd reactapp

# npx create-react-app react-app   [react-app is the application folder name]

Above command will create the folder with react-app, after created enter into folder and start the deployment server

# npm start

Dockerizing the Reactapp

Create the Dockerfile in webroot folder as follow

FROM node:18 AS build WORKDIR /app COPY package.json package-lock.json ./ RUN npm install COPY . ./ RUN npm run build # Step 2: Serve the application using Nginx FROM nginx:alpine COPY --from=build /app/build /usr/share/nginx/html EXPOSE 80 CMD ["nginx", "-g", "daemon off;"]

Create .dockerignore file as follow to remove unwanted content upload into docker file as follow


node_modules build .dockerignore Dockerfile .git .gitignore
Create the Docker Image 

After creating both the files now create the image from the Dockerfile

# cd react-app 
# docker build -t my-react-app .

Validate the image by create the container from the above image and run the application using port 80

# docker run -p 80:80 my-react-app



Upload Changes to GitHub Repository: After verifying the URL upload changes to Github with new repo.
Git Repo : https://github.com/harpal1990/node18new

Deploying React App To Azure: To deploy create the ACR [Azure Container Registry] and Azure App service with Docker Container Running on Linux 


Setup Azure Container Registry

To Setup ACR -- Search for the service called Container Registries -- click on Create Container Registry




Filled all the require details and click on Create


After ACR created navigate to ACR --> Access Key and ticked the Admin User that will generated username and Password for the ACR




After ACR created upload the local machine container image to ACR using command line Install azuer cli using below command # apt install aws-cli Login into azure and upload the local image

# az login --use-device-code Above command will generate the device code like as follow To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code IKDD9SFVS to authenticate.

After login into Azure now login into ACR using below command # az acr login --name reactapptechserverglobal 


Tag the existing image with azure ACR #docker tag my-react-app reactapptechserverglobal.azurecr.io/my-react-app:v1 Push the image to ACR


# docker push reactapptechserverglobal.azurecr.io/my-react-app:v1







Create the Azure App with container: To create the Azure App with container navigate to Azure app service

Click on Create the Webapp and fill all the details as follow Select Docker Container and location same as ACR [i.e. East US 2]


Select the Registry, image and tag for the Web APP


After filled all the details click on Review + Create. Once the process completed check the URL of the Web App you will get the out put of the react







To validate the configuration open the Azure App -- > Setting you will get all the details regarding the ACR details



Setup AzureDevops Project: Create the Project in Azure DevOps and setup pipeline





Select the source code location as Git and I am selecting my Repository which I have prepared at beginning On configure Tab I am going to select Build and Push image to Docker registry








Once you validate it will generate the yaml file validate the following things from the yaml file








# Docker # Build and push an image to Azure Container Registry # https://docs.microsoft.com/azure/devops/pipelines/languages/docker trigger: - main resources: - repo: self variables: # Container registry service connection established during pipeline creation dockerRegistryServiceConnection: 'acf4f71d-f988-4c52-a365-24525e269fb0' imageRepository: 'harpalnodenew' containerRegistry: 'reactapptechserverglobal.azurecr.io' dockerfilePath: '$(Build.SourcesDirectory)/Dockerfile' tag: '$(Build.BuildId)' # Agent VM image name vmImageName: 'ubuntu-latest' stages: - stage: Build displayName: Build and push stage jobs: - job: Build displayName: Build pool: vmImage: $(vmImageName) steps: - task: Docker@2 displayName: Build and push an image to container registry inputs: command: buildAndPush repository: $(imageRepository) dockerfile: $(dockerfilePath) containerRegistry: $(dockerRegistryServiceConnection) tags: | $(tag)

Click on Save and Run. Once the build piepline run successfully, it shows the output






You will get changes on The Azure APP

Friday, December 1, 2023

Pblishing Docker Images to Amazon ECR with AWS CodeBuild on CodeCommit Changes

 

Description:  In this discussion, I will guide you through the process of automatically publishing Docker images to Amazon Elastic Container Registry (ECR) using AWS Code Build. Learn how to trigger this process each time changes are pushed to AWS Code Commit. Dive into the step-by-step setup, enabling seamless integration between Code Commit, Code Build, and ECR for efficient image management in your AWS environment.






Setup Repository in CodeCommit:

The first setup to prepare code commit repository with source code, Dockerfile for build the image and buildspec.yml file for managing the build workflow


Kindly check the GitHub repository for reference URL

buildspec.yml 

phases: pre_build: commands: - echo Logging in to Amazon ECR... - ECR_LOGIN=$(aws ecr get-login-password --region $AWS_DEFAULT_REGION) - echo $ECR_LOGIN | docker login -u AWS --password-stdin XXXXXXXX.dkr.ecr.ap-south-1.amazonaws.com - REPOSITORY_URI=XXXXXXXX.dkr.ecr.ap-south-1.amazonaws.com/reactrepository - COMMIT_HASH=$(echo $CODEBUILD_RESOLVED_SOURCE_VERSION | cut -c 1-7) - IMAGE_TAG=build-$(echo $CODEBUILD_BUILD_ID | awk -F":" '{print $2}') build: commands: - echo Build started on `date` - echo Building the Docker image... - docker build -t $REPOSITORY_URI:latest . - docker tag $REPOSITORY_URI:latest $REPOSITORY_URI:$IMAGE_TAG post_build: commands: - echo Pushing the Docker image to Amazon ECR... - docker push $REPOSITORY_URI

Setup ECR [Elastic Container Registry]

After setup repository Create the ECR private repository 




Setup CodeBuild for React:  We have code commit repository with source code so our first step is to setup Code Build and IAM role for Build.

To create code build navigate to CodeBuild stage and click on create buildstage







Once you create the Build you will get the project under list and also the custom role which created with the build project. Now need to allocate ECR permission to IAM role.

Allocate Permission to login ECR and upload the image:After build project created navigate to IAM role created with the project and assign permission to login with ECR and upload the image

Permission: AmazonEC2ContainerRegistryFullAccess



 

Build the Project: Once all the above changes applied click on Build the project 





Once the build completed you will get the success result and container also uploaded to ECR