DEV Community

Arvind Kumar
Arvind Kumar

Posted on

Automate your git push to remote server

Step by step deployment of my github repo to my server.

I have a ReactJS app setup as a git repo. Every-time I update and push to my currently working dev branch I have to ssh/login to my server and pull it to reflect changes to server.

In addition I have to restart my app by running PM2 restart "myapp". Sometimes I have to run yarn install as well, when I have added or removed a package in my app.

I wish I could automate all this process of pushing, pulling, yarn install and finally restart my app. Is there a way? It seems like. Let's try to set it up.

1. Create the Bare Repo

Login to your server

ssh arvind@devarticles.in

Setup a bare repository

git init --bare /path/to/My_React_App.git

create a post-receive hook

nano /path/to/My_React_App.git/hooks/post-receive

And enter into it, this:

#!/bin/sh

# Check out the files
git --work-tree=/path/to/My_React_App --git-dir=/path/to/My_React_App.git/hooks/post-receive checkout -f dev
Enter fullscreen mode Exit fullscreen mode

Note: In my example I am pushing my local dev branch to remote dev branch. You may omit passing branch name if you are working on your default branch, i.e. main or master, whatever is set in your config.

Important Step:

Make this file executable by setting:

chmod +x /path/to/My_React_App.git/hooks/post-receive

Run this within your own local repo:

git remote add Development 'ubuntu@<IP-ADDRESS>:My_React_App.git'

Note: if you use ssh key to login to server use the following to set up your key in Git configuration

GIT_SSH_COMMAND='ssh -i /Users/arvind/mykey.pem' git submodule update --init

And then make the push:

git push --set-upstream Development dev

If everything works fine you should be able see your local app changes on your server.

Running Tasks After Git Hook Push

As I mentioned earlier I was working on a reactapp for which I wanted to setup this post-receive hook. Hence after every successful push I wanted to run some specific commands inside my app folder, the following ones to be specific:

yarn install
pm2 restart "myapp"

Thankfully this is as easy to automate running these commands as adding these two or rather three lines of code into our /path/to/ICOV3_React_Admin.git/hooks/post-receive file. That is edit post-receive file to add:

cd /path/to/My_React_App
yarn install
pm2 restart "myapp"

Note: I assume that I had run pm2 command with same name to run this app first time, from my app folder. That is:

pm2 start yarn --name "myapp" -- start

Top comments (1)

Collapse
 
jwhenry3 profile image
Justin Henry

Nowadays CICD is a bit more robust and you will probably use something like Github Actions, Gitlab Pipelines, etc to handle this.

Also, when using a NextJS application, if you use Vercel as the host, all pushes to a given branch will automatically be deployed to to the remote host.