PortGate

Blueprints · Systemd & Agents

Production 25 min · Gunicorn / Nginx

Python FastAPI or Django production stack

A virtualenv, a non-root systemd service, Gunicorn bound to localhost, and Nginx forwarding the original client address.

Live config

Baked-in protections

Step 1 · ini

systemd service

/etc/systemd/system/api.service

For Django, change APP_MODULE to project.wsgi:application. Uvicorn workers are used for FastAPI.

[Unit]
Description=api
After=network.target

[Service]
User=api
Group=api
WorkingDirectory=/var/www/api
ExecStart=/var/www/api/.venv/bin/gunicorn app.main:app --bind 127.0.0.1:8000 --workers 2 --worker-class uvicorn.workers.UvicornWorker
Restart=always
NoNewPrivileges=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Step 2 · nginx

Nginx proxy

/etc/nginx/sites-available/app.example.com.conf

FastAPI should use ProxyHeadersMiddleware with trusted_hosts set to the Nginx address. Django should use SECURE_PROXY_SSL_HEADER.

server {
    listen 80;
    server_name app.example.com;
    server_tokens off;
    location / {
        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }
}

Step 3 · bash

Create the virtualenv user

/root/portgate-blueprints/python-enable.sh

Does not install your dependencies. Run pip install inside the venv after this.

#!/bin/sh
set -eu
apt-get update
apt-get install -y python3-venv
id "api" >/dev/null 2>&1 || useradd --system --create-home --shell /usr/sbin/nologin "api"
install -d -m 755 -o "api" -g "api" "/var/www/api"
sudo -u "api" python3 -m venv "/var/www/api/.venv"
systemctl daemon-reload
ln -sfn "/etc/nginx/sites-available/app.example.com.conf" /etc/nginx/sites-enabled/app.example.com.conf
nginx -t
systemctl reload nginx