Deploying Django apps
First, we will prepare the project, then web server and other services that we might need to use.
Clone the project
git clone name@server:git/project.git
Here is my structure for Django apps. You may see different structure but it will be similar to this:
project/
├── apps -> The project folder
├── etc -> Sample configurations
├── fabfile.py -> Fabric script for automate deployment
├── README
├── requirement.txt -> dependent apps for the project
└── www -> static files, ex. css, js ...
Create virtualenv
mkvirtualenv project_name
Install requirements
pip install requirement.txt
Set environment variables
Not all projects need this. I usually don’t save secret keys in settings.py. So, I get them from my environment variables. Advantage of using this:
- No secret keys on the git repository.
- No changes in the files or the codes between local repository and production repository.
There are 5 environment variables I need to set to deal with the project:
- SECRET_KEY
- DATABASE_NAME
- DATABASE_USER
- DATABASE_PASSWORD
- DEBUG
Set it on your .profile:
vi ~/.profile
export SECRET_KEY=''
export DATABASE_NAME=''
export DATABASE_USER=''
export DATABASE_PASSWORD=''
export DEBUG=True
Database
./manage.py syncdb
./manage.py migrate --all
if there is fixture and you did not put them in your settings, then add them:
./manage.py loaddata app_name
Configure Web server
You may use Nginx or Apache2. Checkout this to see sample configurations and more details.
Gunicorn
Install:
pip install gunicorn
To run it on special port type:
gunicorn apps.wsgi:application -b 127.0.0.1:8001
Supervisor
Install:
sudo aptitude install supervisor
Create new configration:
sudo vi /etc/supervisor/conf.d/site_name.conf
Sample configuration:
- “command” notice that we have specify the path for python that are on our envirunmet with our django apps installed on.
- “user” specify the user that you want the app to run by.
- “port” specify the listening address and port the site is listening on
Don’t forget to restart it.
sudo service supervisor restart
// or reload
sudo supervisorctl site_name reload
Extra commands:
sudo supervisorctl ?
sudo supervisorctl update site_name.conf
Fabric:
Fabric is used to automate deployment to the server. This is a scenario maybe later I will provide with some codes.
Prepare for deployment:
- If there is changes and not yet committed it will abort the deployment process.
- Push changes to server repository.
Deploy changes:
- Pull changes from server repository to production repository.
- Synchronize the database (syncdb and migrate).
- Restart the production to let the changes take effect (restart Gunicorn).
Scenario for develop new feature and deploy it:
- Develop the new feature on the local repository.
- Handle Git add and Git commit.
- Then run Fabric to automate the deployment process.
References: