I have a few sites which are all hosted on the same web hosting service under shared hosting. My web host supports Git and I have SSH access to it, and I also have Git setup on my laptop as well.
I want to make it so that when I do a “git push origin master”, it will automatically update the files on my web server, and also save a backup of the previous commit’s files so I can easily rollback if I want to. Is this possible?
2
This is summarized from Using Git to manage a web site
The key to the process is the server side hook ‘post-receive’ (more on git hooks at Customizing Git – Git Hooks and the githooks man page). This hook runs after the server has received all of the data.
Once the server receives the data, it runs git checkout -f
The -f option will force a checkout to the head even if there are local differences.
#!/bin/sh
GIT_WORK_TREE=/var/www/www.example.org git checkout -f
Put that in the hooks/
directory as post-receive
and executable. Of course, the path changes to where you have your webserver’s files (the use of GIT_WORK_TREE
sets the environment variable so that you don’t need to juggle dot files and git settings on the server).
For rolling back, one should tag each release (this can be done as part of the post-commit hook too). By tagging the release one can easily identify the spot to rollback to, though that likely involves logging into the server and checking out that tag.
4
The simplest way to update the working tree of the repository you are pushing to is setting
git config receive.denyCurrentBranch updateInstead
on the receiver side. See
https://git-scm.com/docs/git-config/#git-config-receivedenyCurrentBranch
Ryan’s answer with post commit hooks is better in that it allows checking out to some different location (you likely do not want to have the .git in your web folder). But at this level, it might be a good idea to use some existing deployment tool, like sleske said in the comments.