Deploy Node.js on ubuntu with GIT

Install Git on your server

Arnav Zek
2 min readDec 6, 2020

ssh into your VM, then install Git:

apt-get update
apt-get install git

Clone your private/public repo

#For public repogit clone https://github.com/strafe/project.git# For private repogit clone https://strafe:mygithubpassword@github.com/strafe/project.gitor you can use ssh. here is a free guide: https://www.freecodecamp.org/news/git-ssh-how-to/
then git clone the ssh link
if you get a permission denial execute the follow
ssh-add ~/.ssh/youRSAname

Remove old node and add new node

#Uninstall
sudo apt-get purge --auto-remove nodejs npm
#install node through nvm it is easier to upgrade and downgrade nodesudo apt-get update
sudo apt-get install build-essential
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.5/install.sh | bash#install the latest versionnvm install node//upon installatin the new version is set as defaultgo here for more info on nvm, like hwo to switch version: https://www.keycdn.com/blog/node-version-manager

Install pm2

npm -g install pm2

Kill other PM2 Process

pm2 killor find the running PM2 process with:ps aux | grep PM2then kill with:kill -9 [pid]//see pm2 logs
pm2 logs

Create an environment variable file

//cd to the git repo
nano .env
//paste all variables by right clicking

Update the local repo

git pull origin master

If you get permission denied error which might happen if the repo is private follow the following steps

# Make sure ssh agent is working
eval "$(ssh-agent -s)"
# Find the ssh that as given to the repo
ls -al ~/.ssh
# Make that ssh default
ssh-add ~/.ssh/youRSAname

Run PM2

pm2 start index.js --name "GingerCream"#orpm2 stop GingerCream#or pm2 restart GingerCream

For automatic deployment, u can follow the following methods

  • Github actions (CI & CD)
  • post-receive Git hook

--

--