How to build a simple CD pipeline for your nodejs project

How to build a simple CD pipeline for your nodejs project

June 25, 2020

What we need?

  • VPS
  • Git

Whats is CD?

Continuous deployment is the process of automatically deploying an application, the goal of this practice is to minimize the time pushing a new line of code and using it live on production.

Setting up Pipeline

Gitlab runner:

As we gonna use Gitlab to setup our pipeline we need a runner.
  • Runner is an environment to run your jobs and run tests, deploy your code.
In this case, either you use a shared Runner or you step up one yourself we gonna use a shared one but if you wanna set up it check the documentation here : Gitlab Runner.

Gitlab-CI File :

Create .gitlab-ci.yml file on the root of your project. So what we gonna write there we gonna follow these steps :
  1. Updating Linux package manager
  1. Installing Git
  1. Setting up SSH key
  1. Connect to our server using ssh
  1. Pull our project from git
  1. Install dependencies
  1. Build it
  1. Restart server using pm2
before_script: - apt-get update -qq - apt-get install -qq git # Setup SSH deploy keys - 'which ssh-agent || ( apt-get install -qq openssh-client )' - eval $(ssh-agent -s) - ssh-add <(echo "$SSH_PRIVATE_KEY") - mkdir -p ~/.ssh - '[[ -f /.dockerenv ]] && echo -e "Host *\n\tStrictHostKeyChecking no\n\n" > ~/.ssh/config' deploy_staging: tags: - docker type: deploy environment: name: testing url: "$VPS_IP" script: - ssh root@"$VPS_IP" "cd /root/app/allomakkah && git fetch origin master && git reset --hard FETCH_HEAD && git clean -df && npm i && npm run prod-build" - ssh root@"$VPS_IP" "pm2 restart hiddy" only: - master
Now let's deploy our application it will automatically run this pipeline whenever we push to the master branch because of that ligne :
only: - master