Wednesday, January 25, 2017

setting up automatic deployment via git

If you wish to have automatic deployment with rails and thin, here is an example:

1st, clone your repository on server to a path.
Next, vi .git/hooks/post-merge
add in your bash script to run after git is pull
example:
bash -lc /pathtoroot/deploy.sh

chmod a+x .git/hooks/post-merge

in your git repository, add a file called: deploy.sh, you may code any deployment command after git pull, example:
RAILS_ENV=production
cd /pathtoroot
echo "deploy.sh: bundle install"
bundle install
echo "deploy.sh: rake db:migrate"
bundle exec rake db:migrate
echo "deploy.sh: rake assets:precompile"
bundle exec rake assets:precompile
echo "deploy.sh: restarting"
bundle exec thin -C config/thin.yml restart
bundle exec sidekiqctl stop tmp/sidekiq.pid 0
bundle exec sidekiq -d -P tmp/sidekiq.pid -L log/sidekiq.log
echo "deploy.sh: Done!"

makesure you have chmod a+x deploy.sh and commit this file via git on your local machine.

on server, add a cron job to automatically pull on a period basis:
crontab -e
---
* * * * * bash -lc "cd /pathtoroot/ && git pull"
* * * * * sleep 30 && bash -lc "cd /pathtoroot/ && git pull"
---

2nd command allows you to run git pull within 30seconds.

Once git pull is successful, it will auto trigger post-merge and run your deploy.sh

hope it helps :)