POSTS
Deploying Django with Git
This post explains how I set up a linux server such that I can deploy changes to a django application just using a git push. This is just what works for me, at the moment. In addition, the entire content is based on the article “Using Git for Deployment” from Dan Barber, so it is required reading as well.
Like Dan Barber, I set up two repositories on the server:
- A working copy which is used to run the application
- A “bare” repository, which is the repository that I push to
$ cd /srv/django/myproject
$ git init
$ git add .
$ git commit
$ mkdir -p /srv/git
$ git clone --bare /srv/django/myproject /srv/git/myproject.git
Having the bare repository allows us to push to it cleanly, then have a post-update hook that visits the working copy and pull changes from there.
Next, I edit the git configuration in /srv/django/myproject/.git/config
to add the remote reference:
[remote "origin"]
url = /srv/git/myproject.git
fetch = +refs/heads/*:refs/remotes/origin/*
“origin” is used as the remote name in case I need to reclone the working copy later, since cloning will automatically create an “origin” remote pointing back to the bare repository.
Now I have to actually write the post-update hook by creating a file at /srv/git/myproject.git/hooks/post-update
:
#!/bin/sh
echo
echo "**** Pulling changes into Live"
echo
cd /srv/django/myproject || exit
unset GIT_DIR
git pull origin master
sudo /etc/init.d/apache2 restart
exec git-update-server-info
And make it executable:
chmod +x /var/git/myproject.git/hooks/post-update
I got lazy and didn’t add the second hook described in Dan’s article, because I might need to reclone the working copy again.
In order to make the sudo /etc/init.d/apache2 restart
line work, I used instructions from this page to modify the sudoers file (using visudo
), otherwise git push would fail:
# User alias specification
User_Alias WEBMASTERS = myuser
# Cmnd alias specification
Cmnd_Alias WEB_CMDS = /etc/init.d/apache2
# User privilege specification
WEBMASTERS ALL= (ALL) NOPASSWD: WEB_CMDS
Another gotcha I ran into was file permissions. Suffice to say, I found it a lot easier just to create a specific user for pushing to the git repository. Allowing multiple users to push changes means that the file permissions in /var/django/myproject
will be based on whichever user is pushing, so the application may run into permission issues.
-
django
git
deployment