Skip to content

Instantly share code, notes, and snippets.

@rahman541
Last active October 14, 2021 21:50
Show Gist options
  • Save rahman541/63926b0bb456efbbf6c17fa0e6e68c52 to your computer and use it in GitHub Desktop.
Save rahman541/63926b0bb456efbbf6c17fa0e6e68c52 to your computer and use it in GitHub Desktop.

Automate Deploy Node App in Amazon EC2 Linux

PREREQUISITES

To Login

ssh -i <private-key-file/pem> ec2-user@[ec2-hostname].amazonaws.com
  1. Install Node JS & pm2 Ref:
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.32.0/install.sh | bash
. ~/.nvm/nvm.sh
nvm install 10.9
node -e "console.log('Running Node.js ' + process.version)"
npm install pm2 -g

In local git project

git init nodeapp && cd nodeapp
git remote add ec2 ec2-user@ec2-18-136-199-135.ap-southeast-1.compute.amazonaws.com:/home/ec2-user/nodeapp.git

In EC2

Login to EC2 instance.

sudo yum install git
pm2 stop nodeapp && pm2 delete all
rm -rf nodeapp.git nodeapp tmp && ll
git init --bare nodeapp.git && git clone nodeapp.git nodeapp && ll
# Copy code below
nano nodeapp.git/hooks/post-receive && sudo chmod +x nodeapp.git/hooks/post-receive && ls nodeapp.git/hooks/

nodeapp.git/hooks/post-receive file content:

#!/bin/sh
echo 'post-receive: Triggered.'
# The production directory
TARGET="/home/ec2-user/nodeapp"
# A temporary directory for deployment
TEMP="/home/ec2-user/tmp/nodeapp"
# The Git repo
REPO="/home/ec2-user/nodeapp.git"
# Deploy the content to the temporary directory
echo 'post-receive: git check out…'
git --work-tree=$TARGET --git-dir=$REPO checkout -f

cd $TARGET
echo 'post-receive: npm install…' \
&& npm install \
&& echo 'post-receive: → done.' \
&& (pm2 delete 'nodeapp' || true) \
&& pm2 start index.js --name 'nodeapp' \
&& echo 'post-receive: app started successfully with pm2.'

Back to local

git push ec2
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment