benclmnt / til

Today I Learned: mainly configs, gotchas, setups, workflows
1 stars 0 forks source link

Django Deployment using Caddy and Systemd #12

Open benclmnt opened 1 year ago

benclmnt commented 1 year ago

Steps for deploying Django to a VPS, such as digital ocean. These steps assume you have a caddy service running, and will deploy django using gunicorn running on localhost:8000 and served by caddy for https://mywebsite.com.

Caddyfile

Default location: /etc/caddy/Caddyfile

https://mywebsite.com {

    handle_path /static/* {
        root * <path to your project>/static
        file_server
    }

    handle {
        reverse_proxy localhost:8000
    }
}

After editing, don't forget to reload caddy sudo systemctl reload caddy

Django checklists

Run through python3 manage.py check --deploy. Settings to change

For ease of development, you might want to add

# myproject/settings.py

if os.getenv('DJANGO_DEVELOPMENT') == 'true':
    from .settings_dev import (
        ALLOWED_HOSTS,
        CSRF_COOKIE_SECURE,
        DATABASES,
        DEBUG,
        SECRET_KEY,
        SECURE_SSL_REDIRECT,
        SESSION_COOKIE_SECURE,
    )

Systemd

First create a systemd file for your Django project.

# sudo vim /etc/systemd/system/<your project name>.service

[Unit]
Description=gunicorn daemon
After=network.target

[Service]
User=<your linux username>
Group=<your linux username>
Restart=on-failure
WorkingDirectory=<path to your working directory>
ExecStart=<path to gunicorn> <your project name>.wsgi -b 127.0.0.1:8000

[Install]
WantedBy=multi-user.target

Next, generate and copy a secret key. To generate a secret key, you can run head /dev/urandom | openssl sha256

Then run sudo EDITOR=vim systemctl edit <your project name> which will open an override file. Here you can insert your environment variables, e.g. the secret key that you generated previously.

[Service]
Environment="SECRET_KEY=<SECRET_KEY>"

Optionally, run sudo systemctl enable <your project name> to run it on the next boot.

Running

benclmnt commented 1 year ago

Journalctl

systemctl logs can become large over time.

  1. check its current size by running journalctl --disk-usage.
  2. prune the journals by running sudo journalctl --vacuum-size=500M or sudo journalctl --vacuum-time=7d

References:

benclmnt commented 1 year ago

If you are using Nginx, the following should work

server {
    server_name YOUR_HOST;

    location ^~/static/ {
        alias /HOME_FOLDER/SOME_PREFIX/static/;
    }

    location / {
        include proxy_params;
        proxy_pass http://127.0.0.1:9001;
    }
}
server {
    listen 80;
    server_name YOUR_HOST;
}