This guide deploys a Django project with gunicorn as the server and a managed PostgreSQL database, both on Hangar, talking over the private network. A hangar.yaml file in the repository describes both, so one link creates the database, wires it to the app and deploys.
Prepare the project#
Four changes make a Django project ready for production anywhere. If yours already has them, skip ahead.
Dependencies#
Add the production packages to requirements.txt:
gunicorn
psycopg[binary]
dj-database-url
whitenoise
Settings from the environment#
# settings.py
import os
import dj_database_url
SECRET_KEY = os.environ["SECRET_KEY"]
DEBUG = os.environ.get("DEBUG") == "1"
ALLOWED_HOSTS = os.environ.get("ALLOWED_HOSTS", "").split(",")
CSRF_TRUSTED_ORIGINS = [f"https://{host}" for host in ALLOWED_HOSTS if host]
DATABASES = {"default": dj_database_url.config(conn_max_age=600)}
dj_database_url.config() reads DATABASE_URL.
Static files#
# settings.py
MIDDLEWARE = [
"django.middleware.security.SecurityMiddleware",
"whitenoise.middleware.WhiteNoiseMiddleware",
# ...
]
STATIC_ROOT = BASE_DIR / "staticfiles"
HTTPS behind the proxy#
Hangar terminates TLS and forwards the request to your app, so tell Django to trust the forwarded protocol:
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")
1Add hangar.yaml#
Create hangar.yaml at the root of the repository, next to manage.py:
# yaml-language-server: $schema=https://tryhangar.io/schema/hangar.v1.json
version: 1
name: My Django app
services:
web:
preDeploy: python manage.py migrate
start: python manage.py collectstatic --noinput && gunicorn mysite.wsgi --bind 0.0.0.0:$PORT
env:
DATABASE_URL: ${{ db.url }}
SECRET_KEY:
generate: secret
ALLOWED_HOSTS: ${{ web.host }}
databases:
db:
kind: postgres
Replace mysite with the name of your project package. What each part does:
databases.dbcreates a managed PostgreSQL database in the same region as the app.DATABASE_URL: ${{ db.url }}fills in the database's internal connection URL.SECRET_KEYgets a long random value, made once when the project is created.ALLOWED_HOSTS: ${{ web.host }}allows the address Hangar gives the service, and the settings above deriveCSRF_TRUSTED_ORIGINSfrom it.preDeploymigrates the database on every deploy, before the new version takes traffic. A failed migration stops the deploy and the running version stays up.startcollects static files and starts gunicorn on the port Hangar sets inPORT, on0.0.0.0so the proxy can reach it.
The builder needs no setting: the automatic builder detects Python from requirements.txt (or pyproject.toml) and installs the dependencies. Every key is explained in the hangar.yaml reference.
2Deploy from the link#
Push the file and open the deploy link for your repository:
https://tryhangar.io/deploy?repo=https://github.com/owner/name
The page lists what the manifest creates, a service and a PostgreSQL database. Pick a region and deploy. Put the same link in your README as a Deploy on Hangar button and anyone can do the same.
The manifest is read once, when the project is created. From then on the service is configured in the dashboard, and every push to the branch deploys it again.
3Add a domain#
In the service's Settings → Networking, add your hostname with HTTPS on. Then, in the Variables tab, append it to ALLOWED_HOSTS after the generated address, separated by a comma, and redeploy.
Without a manifest#
Deploy links need a public repository. For a private one, connect your Git provider and set up the same thing from the dashboard:
- In a new project, add a PostgreSQL service and pick a region. When it is running, open it and copy the internal connection URL.
- Add a service from your repository, in the same region as the database. Leave the builder on Automatic.
- In the service's Variables tab, set
SECRET_KEYto a long random string,ALLOWED_HOSTSto your hostname andDATABASE_URLto the internal connection URL. Generate the key locally withpython -c "import secrets; print(secrets.token_urlsafe(50))". - In Settings → Runtime, set the pre-deploy command to
python manage.py migrate. The start command chains two commands, so it runs through a shell: set it toshwith two arguments,-candpython manage.py collectstatic --noinput && gunicorn mysite.wsgi --bind 0.0.0.0:$PORT. - Deploy, then add your hostname in Settings → Networking with HTTPS on.
Background workers#
Celery or another worker runs as a second service from the same repository. In hangar.yaml, add it next to web without a public address, with a Redis database as the broker:
services:
web:
# preDeploy, start and env as above, plus:
env:
REDIS_URL: ${{ broker.url }}
worker:
public: false
start: celery -A mysite worker --loglevel=info
env:
DATABASE_URL: ${{ db.url }}
REDIS_URL: ${{ broker.url }}
databases:
db:
kind: postgres
broker:
kind: redis
Troubleshooting#
DisallowedHost: the domain is missing fromALLOWED_HOSTS.- CSRF verification failed on forms: the
https://origin is missing fromCSRF_TRUSTED_ORIGINS. connection refusedto the database: the app and the database are in different regions, orDATABASE_URLholds an external address instead of the internal one.