The following solution updates a live server code base with code from a bare repo on another server. This solution does not use scp or copy files to overwrite on the live server, because we want to avoid overwriting a whole directory (with git we can choose what we want to update).
Assumptions:
- You are pushing your code to a bare-repository on a testing/staging server (or it might only be a server to host your "centralized" repo)
- You want to update your live server with the code in this bare repo
- Your live server is on a different server than you bare repo
On the live server:
- Set up a non-bare git repo that hosts the live files:
cd /var/www/www.yoursite.com && git init
- From this live server, make sure you have ssh-access to the server where your bare repository is, using ssh-keys (not covered here)
- Add the "centralized" repo:
git remote add origin git@testserverip:/path/to/repo.git
- Now, every time you want to update the live server code base, you can run
git fetch origin
followed by git merge
Since this is a live server, you typically do not want any merge-conflicts to cause trouble. If you don't care about loosing changes on the live server (because you probably never change anything important on the live server), you can use git merge -m 'Overwriting live server' -s recursive -X theirs origin/active-branch-on-live-server
A typical scenario is that you have other files (temp files, user-changed files etc) on the live server that you do not want to overwrite). Make sure to add all these files/directories to your .gitignore-file and make sure they are not added by git add. That way, they will not be affected when code is pulled from you centralized repo.
If you want this setup to me more automatic, make a bash script on the live server:
git fetch origin
git merge -m 'Overwriting live server' -s recursive -X theirs origin/active-branch-on-live-server
Make this script as an executable bash script (not covered here). Now, you can call this script from a hook-script on the "centralized" server, so that the live server gets updated every time you push your code.
On the "centralized" repo/test/staging server:
(You should already have a bare repo set up here, if not create it).
In your bare-repo.git/hooks/ create/edit the post-receive
file, so that the live server runs the script created above when code is pushed to the bare repo:
#!/bin/bash
while read oldrev newrev refname
do
branch=$(git rev-parse --symbolic --abbrev-ref $refname)
# Use this if-sentence to only update live server if branch is the wanted branch, e.g. master or stable
if [[ "stable" == "$branch" ]]; then
# Fetch this branch from live-server
ssh root@ip-to-live-server '/path/to/script-created-above'
fi
done
Make sure that the git user on you the server that hosts your bare repo has access to your live server via ssh-keys, so that the ssh in the script above works.
This is a schematic overview. Details can be found other places: