Basic CICD on EC2
Author : JaNakh Pon , December 27, 2021
Tags
Intro
In this article, we are going to set up a basic CICD pipeline on AWS EC2 using gitlab-ci.
EC2 Setup
For EC2 setup, use Ubuntu 18.04 LTS or 20.04LTS and generate a new pem key and save it to your local computer. Update the security group's rules to your preference and associate the instance with Elastic IP Address to be sure the instance is accessible.
Firstly, ssh in to your EC2 instance and install nvm and nodejs LTS version accordingly to your perference:
>> ssh -i "yourkey.pem" ubuntu@ec2-109-18-24-207.compute-1.amazonaws.com
>> curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.34.0/install.sh | bash
>> . ~/.nvm/nvm.sh
>> nvm install v14.17.2 //pick your fav version
>> npm i -g pm2
After installing nodejs, make sure to link node
path since we used nvm
in nodejs installation:
>> sudo ln -s "$(which node)" /usr/local/bin/node
Basic CICD Flow with Gitlab
To demonstrate basic CICD flow in this article, we'll just use an example next.js repo with gitlab-ci configuration. We will use develop
branch to trigger ci service provided by Gitlab.
There will be two stages: build stage and deployment stage. In build
stage, we will use gitlab ci service to build & export build
folder for production and in deploy
stage, we will copy everything including build
folder to our ec2 instance.
And we'll use pm2
to start, stop and restart our nodejs app programatically in EC2.
Pipeline setup
Before the pipeline is ready, we need to go into our EC2 instance and create a specific folder as a destination folder path for our pipeline codbase:
>> mkdir -p develop/web
>> git clone your_repo_url .
And run build script and serve it using pm2
with the same namespace that we were using in our ci configuration.
>> npm i && npm run build
>> pm2 serve build 3000 --name develop_web // serve the `build` folder, use port `3000` and set its name to `develop_web`
Try to access it from your browser and check the status of the app!
Now, we need to provide the required environment variables for our pipeline: key value from our .pem
file and EC2 instance's address:
INSTANCE_ADDR = ubuntu@ec2-109-18-24-207.compute-1.amazonaws.com
SSH_PRIVATE_KEY = ${value from .pem file}
Finally, we need to push our codebase to gitlab with gitlab-ci
configuration and don't forget to set default branch to our targeted branch name and in our case it's develop
.
So whenever we push code to targeted branch, it will trigger the pipeline and the CI service
will run the script to build
the updated codebase and will copy it to the EC2
instance.
Once the copying process is finished, pm2
will stop the app with previous codbase and will use the newly builded folder to serve on the same port.
Ref => Symlink Tutorial in Linux – How to Create and Remove a Symbolic Link
Go Back.