Automatically mirror a git repository

Viewed 16377

One of the side-effects of using an external Subversion repository was getting automatic offsite backups on every commit.

I'd like to achieve the same using Git.

i.e. every commit to my local repository automatically commits to an external one so the two repositories are always in sync.

I imagine that a post-commit hook would be the way to go. Does anyone have any specific examples of this?

3 Answers

I just wanted to add that I had a similar issue, but in my case I needed every push to a remote repository to automatically mirror to another remote as a backup. My local machine also couldn't directly connect to the mirrored repo, so it had to be pushed from the server-side.

For that, I had to create a post-receive hook on the remote repo (under the hooks/ directory). And then, as Manoj's answer suggested, I simply added the following command to the post-receive file:

git push --mirror my_remote

Hopefully that will help others who, like me, stumbled upon this question from Google.

GitBitLabHub allows you automatically mirror repositories between Bitbucket / Gitlab / Github using simple webhooks. Under the hood it does the following:

git config remote.origin.fetch "+refs/heads/*:refs/remotes/origin/*"
git fetch --prune
git remote set-head origin -d
git branch -a || 'true'
git push --prune dest +refs/remotes/origin/*:refs/heads/* +refs/tags/*:refs/tags/*

All you need is to set up deploy keys and webhooks:

  1. Generate an ssh key for source and destination repositories:
ssh-keygen -t rsa -f ~/.ssh/project_id_rsa
  • It will generate 2 keys, the PRIVATE key to ~/.ssh/project_id_rsa and the PUBLIC key to ~/.ssh/project_id_rsa.pub.
  • The PUBLIC key is used as Deploy Key while the PRIVATE key should be used in SRC_DEPLOY_KEY and DEST_DEPLOY_KEY env variables.
  1. Add this PUBLIC key as a Deploy Key for the source and destination repositories. Depending on the platform it's called Deploy Key or Access key. See how to add Deploy/Access Key to bitbucket, bitbucket access keys, gitlab, github.
  • Add the PUBLIC key to the source repo with read-only access.
  • Add the PUBLIC key to the destination repo with write access.
  1. Create the webhook in the source repository. Using default settings should be enough. See how to create a webhook in bitbucket, gitlab, github.
Related