Heroku Deployment
Basic set up
- Create a Heroku account
- Create new app and choose the location (server location)
- Go to Resources and add Heroku Postgres (for PostgreSQL database) and Heroku Redis (for cache) and Deploy Hook- Http Post (for deployment notification in Slack for e.g.)
- Download and install Heroku CLI
Django Set Up
- Create a Django app
- Create requirements.txt file in the project folder
- Install following libraries
pip install dj-database-url # for accessing databasepip install gunicorn # for running Python HTTP server - Add dj-database-url==XX & gunicorn==XX to requirements.txt file.
- Add the following environment variables:
- DATABASE_URL
- REDIS_URL
- Go to settings.py file and add the following:
-
For Database settings:
config = {
key: value for key, value in os.environ.items()
}
heroku_database_url = config.get('DATABASE_URL', None)
if heroku_database_url:
# heroku production setting
import dj_database_url
DATABASES = {
'default': dj_database_url.parse(heroku_database_url),
}
else:
# development/test setting
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'postgres',
}
} - For Cache setting:
open_redis_url = config.get('REDIS_URL')
if not open_redis_url:
CACHES = {'default': {'BACKEND': 'django.core.cache.backends.dummy.DummyCache',}}else:CACHES = {"default": {"BACKEND": "django_redis.cache.RedisCache","LOCATION": open_redis_url,"OPTIONS": {"CLIENT_CLASS": "django_redis.client.DefaultClient","IGNORE_EXCEPTIONS": True,},'KEY_PREFIX': DEP_NAME,'VERSION': VERSION,'TIMEOUT': 86400, # 1 day},}
-
- Create gunicorn_cofig.py in project folder and add
import osimport multiprocessingsize = int(os.getenv("SIZE", 1))# Maximum 5 worker per 128MBworkers = min(multiprocessing.cpu_count() * 2 + 1, size * 1)timeout = int(os.getenv("GUNICORN_TIMEOUT", 120)) - Create Procfile in project folder and add
web: gunicorn <django-project-name>.wsgi:application --config gunicorn_config.py - Create runtime.txt in project folder and add
python-3.5.2
- Commit your changes in git
- Deploy using terminal:
$ heroku login$ heroku git:remote -a <heroku app name>$ git push heroku <local git branch name>:master Tip:
-
$ heroku run 'bash' --app <heroku_app_name> # to run bash on heroku terminal$ python manage.py createsuperuser # to create superuser in heroku
-
Enjoy !