Web Deployment With Git

This is my solution to do the following
1) deploy a website from my local machine to my server in one step
2) keep a git repository on the server (mainly to have it as backup)

I use a combination of git push and rsync to achieve this.

Create git repositories on your local machine and the server.


1) create a bare git repository on the server (this is the repository that will be pushed to)

$ mkdir /home/cogan/git_projects/myproject.git
$ cd myproject
$ git init --bare


2) create a git repository on the development machine (where you will do the deployment from)

$ mkdir /home/cogan/projects/myproject
$ cd myproject
$ git init


add a test file to the git repository and commit

$ echo "<h1>[G]It Works!</h1>" > test.html
$ git add test.html
$ git commit -m "initial commit"


Set up remote repository


3) On your local machine add the repository on the server as a remote repository called 'web'

$ git remote add web ssh://myserver/home/cogan/git_projects/myproject.git


you can type git remote to check that it was added

$ git remote


At this point you can type 'git push web' to push changes to your server.

Set up web deployment


The actual deployment will be done with rsync, which is a command to sync up a remote directory with a local one. Instead of doing a copy of every file, rsync will only copy files that are different between the remote directory and the local directory, which is exactly what we want.

4) write the rsync command

$ rsync -e 'ssh -x' -av --exclude=.git/ --exclude --.*\swp --delete /home/cogan/projects/myproject cogan@myserver:/var/www


You can tailor this command to exclude whatever type of backup files your text editor might leave lying around your directory. If you run this command you should see the files being transferred, and a directory called myproject will exist in /var/www/ on your server

Putting it all together with git alias


5) To deploy the project and update the remote repository, we can use a git alias to do it all. A git alias is just like a regular alias, except you access it by typing 'git aliasname' instead of just 'aliasname'

$ git config alias.deploy '!git push web master && rsync -e \'ssh -x\' -av --exclude=.git/ --exclude --.*\swp --delete /home/cogan/projects/myproject cogan@myserver:/var/www'

This will place the alias in .git/config (it may be easier to add it there directly than to type it from the command line. Also, don't use double quotes if you do decide to type it from the command line, bash may process the '!' character and do strange things).

Now all you have to do is type 'git deploy' and you'll update your remote repository and deploy to your webserver.

Comments

Popular posts from this blog

Terminate Scripted Minicom Session

What Twitter Tells Us

CodinGame: Building an AI to play (and win) at "Penguins"