Today a quick post on how to use Git to push your code to a remote location. I found this very useful when developing sites. Welcome to post #100.

featured image

I learned this from Using Git to manage a web site and after using this technique at 2 websites, I found this needed to have a dedicated post. The article explains it very well, but this note taking helps me to remember and implement it well. And you guys might find this quite useful :)

Note that it is highly recommended to set up a key-based login to your remote server, see this useful SSH reference for more details.

Steps from local git to remote mirror

  • On the local server you begin with your project and commits, see my first Git post how to get started if you are not familiar with Git.
  • On the remote node you start by creating a new repository (assuming ~/repositories as the home of all code repos):
  • $ cd ~/repositories && mkdir repository.git
    $ cd repository.git
    $ git init --bare 
    

    You will see something like: Initialized empty Git repository in /home/user/repository.git/ and it means you have a new repository to mirror the local one to.

  • Make a destination directory where your code will be copied to:
  • $ mkdir /home/user/target_dir 
    
  • Create the following script that will take care to check out the latest copy in the source target directory (/home/user/target_dir) when you commit to the remote server (with $ git commit aliasName ; see towards the end of this post ... )
  • $ vi hooks/post-receive
    

    Enter the following:

    # #!/bin/sh
    # GIT_WORK_TREE=/home/user/target_dir git checkout -f
    
  • And give the script execution permissions with:
  • $ chmod +x hooks/post-receive
    

    You can find a quick wrapper script at Github.

  • Back on your localhost:
    • Define a name of the remote mirror (replacing aliasName, user, domain.com and repository.git with your stuff ):
    • $ git remote add aliasName ssh://[email protected]/home/user/repositories/repository.git
      
    • Push the code to remote location, creating a new "branch" master there, the hooks/post-receive script causes the source code to be copied to /home/user/target_dir you defined earlier. So here we are pushing master to aliasName:
    • $ git push aliasName +master:refs/heads/master 
      
    • Following updates are easy:
    • After local committing with: $ git add . ; $ git commit -m "message" , you push your code to your remote mirror with: $ git push aliasName


    Bob Belderbos

    Software Developer, Pythonista, Data Geek, Student of Life. About me