Back to home
• 18 min read
github-actions nginx django oracle-cloud deployment cloudflare-r2

Deploying Django on a 1 GB Oracle Cloud Free-Tier VPS: Gunicorn, Nginx, PostgreSQL, Cloudflare R2 and GitHub Actions

How I run a production Django site on a 1 GB Oracle Cloud free-tier VM, with Gunicorn and Nginx, a memory-tuned local PostgreSQL, static and media files on Cloudflare R2, Certbot TLS, and SSH deploys from GitHub Actions.

Deploying Django on a 1 GB Oracle Cloud Free-Tier VPS: Gunicorn, Nginx, PostgreSQL, Cloudflare R2 and GitHub Actions

My portfolio and blog run on a single Oracle Cloud free-tier VM with 1 GB of RAM. Django, Gunicorn, Nginx and PostgreSQL all live on that one box. Static files and uploads go to Cloudflare R2, Certbot handles TLS, and GitHub Actions deploys every push to main.

That is not a lot of memory. A careless setup will push the kernel's OOM killer into picking off Postgres or a Gunicorn worker at the worst moment, usually during a deploy. With a few deliberate choices, though, 1 GB is plenty for a low-traffic Django site, and it costs nothing.

This guide walks through how I set it up, with the actual config files. It is also honest about what is missing. There is no caching layer yet, and the security hardening is still on my to-do list. I cover both at the end.

By the end you will have:

  • Django 5.x served by Gunicorn over a Unix socket, behind Nginx
  • PostgreSQL on the same VM, tuned to stay small
  • Static and media files in Cloudflare R2, served from a custom subdomain
  • Let's Encrypt certificates that renew themselves
  • A GitHub Actions workflow that deploys over SSH on every push

Why a 1 GB box at all?

Oracle's Always Free tier gives you two AMD VM.Standard.E2.1.Micro instances, each with 1 GB of RAM and a fraction of a CPU. I use one for this site and the other for a separate API. A portfolio with a blog gets a few hundred visits a day at most, and most of those requests are cheap page renders. Paying for a 4 GB droplet to serve that felt wasteful.

The constraint is also useful. On a box this small you have to know where every megabyte goes, and that habit carries over to bigger systems.

Architecture

            Browser
               |
     +---------+------------------------------+
     |                                        |
 firojacharya.com.np                media.firojacharya.com.np
     |                                        |
  Oracle VM (1 GB)                      Cloudflare R2 bucket
  +-------------------------------+     (static/ and media/)
  | Nginx :80/:443 (Certbot TLS)  |            ^
  |   -> Gunicorn (unix socket)   |            |
  |        -> Django 5.x  --------+--- boto3 --+  (collectstatic, uploads)
  |        -> PostgreSQL (local)  |
  +-------------------------------+
               ^
               |  SSH deploy
         GitHub Actions

The key decision is that Nginx never serves static or media files. Django writes them to R2 through django-storages, and the browser fetches them from media.firojacharya.com.np, which is an R2 custom domain on Cloudflare. That keeps disk I/O and bandwidth off the VM, and it means uploads from the admin (CKEditor 5 images, mostly) survive if I ever rebuild the server.

1. Server prep: swap first

The image is Ubuntu. Before installing anything, add swap. pip install for a project with a few compiled dependencies can spike past the free RAM, and without swap that ends in an OOM kill instead of a slow install.

sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# Prefer RAM, use swap as a safety net
echo 'vm.swappiness=10' | sudo tee /etc/sysctl.d/99-swappiness.conf
sudo sysctl --system

Swap is not a replacement for memory. If the box is swapping constantly, response times will show it. But as a buffer for short spikes, it is the single most useful thing you can do on a 1 GB machine.

Then the base packages:

sudo apt update && sudo apt upgrade -y
sudo apt install -y python3-venv python3-dev build-essential libpq-dev \
    nginx postgresql git

The Oracle firewall gotcha

Oracle has two layers of firewall, and you need both open for ports 80 and 443:

  1. The security list (or network security group) on the VCN subnet, set in the Oracle console. Add ingress rules for TCP 80 and 443 from 0.0.0.0/0.
  2. iptables on the instance itself. Oracle's Ubuntu images ship with rules in /etc/iptables/rules.v4 that reject everything except SSH.

The second one catches almost everyone. Nginx is running, the security list is open, and the site still times out. Insert the rules above the default REJECT line and save them:

sudo iptables -I INPUT 6 -m state --state NEW -p tcp --dport 80 -j ACCEPT
sudo iptables -I INPUT 6 -m state --state NEW -p tcp --dport 443 -j ACCEPT
sudo netfilter-persistent save

Position 6 works on the stock image, but check with sudo iptables -L INPUT --line-numbers first so the rules land before the REJECT.

2. PostgreSQL, kept small

Running Postgres on the same box avoids paying for a managed database and keeps queries on a local socket. The default config is already fairly modest, but it assumes more connections than a two-worker Django app will ever open.

Create the database and role:

sudo -u postgres psql <<'SQL'
CREATE ROLE portfolio WITH LOGIN PASSWORD 'change-me';
CREATE DATABASE portfolio OWNER portfolio;
SQL

Ubuntu's postgresql.conf includes everything in conf.d/, so I keep my overrides in a separate file. The version in the path is 14 on Ubuntu 22.04 and 16 on 24.04.

# /etc/postgresql/16/main/conf.d/lowmem.conf
max_connections = 20
shared_buffers = 128MB
effective_cache_size = 384MB
work_mem = 4MB
maintenance_work_mem = 32MB
wal_buffers = 4MB

max_connections is the setting that matters most here. Every connection is a separate backend process with its own memory, and two Gunicorn workers plus the odd manage.py shell need maybe five. Twenty leaves room without inviting trouble. effective_cache_size allocates nothing. It only tells the planner how much of the OS page cache it can expect.

sudo systemctl restart postgresql
sudo -u postgres psql -c "SHOW shared_buffers;"

Postgres listens only on localhost by default. Leave it that way.

3. Django production settings

Everything that differs between my laptop and the server comes from environment variables. On the server they live in /etc/portfolio/env, owned by root:deploy with mode 640. Systemd loads them into Gunicorn, and the deploy user can read them when it runs manage.py, but nobody else can.

# /etc/portfolio/env
DJANGO_SECRET_KEY=generate-a-long-random-string
DJANGO_DEBUG=False
DJANGO_ALLOWED_HOSTS=firojacharya.com.np,www.firojacharya.com.np
DATABASE_NAME=portfolio
DATABASE_USER=portfolio
DATABASE_PASSWORD=change-me
R2_ACCOUNT_ID=your-cloudflare-account-id
R2_ACCESS_KEY_ID=...
R2_SECRET_ACCESS_KEY=...
R2_BUCKET_NAME=portfolio-assets

The relevant parts of settings.py:

import os

SECRET_KEY = os.environ["DJANGO_SECRET_KEY"]
DEBUG = os.environ.get("DJANGO_DEBUG", "False") == "True"

ALLOWED_HOSTS = os.environ.get("DJANGO_ALLOWED_HOSTS", "").split(",")
# Django 4.0+ requires the scheme here
CSRF_TRUSTED_ORIGINS = [f"https://{host}" for host in ALLOWED_HOSTS if host]

# Nginx terminates TLS, so trust its X-Forwarded-Proto header
SECURE_PROXY_SSL_HEADER = ("HTTP_X_FORWARDED_PROTO", "https")

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.postgresql",
        "NAME": os.environ["DATABASE_NAME"],
        "USER": os.environ["DATABASE_USER"],
        "PASSWORD": os.environ["DATABASE_PASSWORD"],
        "HOST": "localhost",
        "PORT": "5432",
        "CONN_MAX_AGE": 60,
        "CONN_HEALTH_CHECKS": True,
    }
}

CONN_MAX_AGE keeps each worker's connection open between requests instead of reconnecting every time. With only two workers, that means two long-lived Postgres backends, which is cheap. CONN_HEALTH_CHECKS (Django 4.1+) makes Django check a reused connection before using it, so a Postgres restart does not cause a burst of errors.

SECURE_PROXY_SSL_HEADER is only safe because Nginx always sets that header itself and Gunicorn is not reachable from outside. If Gunicorn were exposed directly, a client could forge it.

4. Static and media files on Cloudflare R2

R2 speaks the S3 API, so django-storages with boto3 works as is. R2 also has no egress fees, which is the reason I picked it over S3.

pip install "django-storages[s3]"

In the Cloudflare dashboard I created a bucket, generated an R2 API token with read and write access to that bucket only, and connected media.firojacharya.com.np as a custom domain under the bucket's settings. Cloudflare creates the DNS record for you when the domain is on the same account. The custom domain matters: the default r2.dev URL is rate-limited and meant for development.

Django 4.2 replaced DEFAULT_FILE_STORAGE and STATICFILES_STORAGE with a single STORAGES dict, and Django 5.1 removed the old settings completely. One bucket holds both static and media, split by prefix:

R2_ACCOUNT_ID = os.environ["R2_ACCOUNT_ID"]
MEDIA_DOMAIN = "media.firojacharya.com.np"

_r2_options = {
    "bucket_name": os.environ["R2_BUCKET_NAME"],
    "endpoint_url": f"https://{R2_ACCOUNT_ID}.r2.cloudflarestorage.com",
    "access_key": os.environ["R2_ACCESS_KEY_ID"],
    "secret_key": os.environ["R2_SECRET_ACCESS_KEY"],
    "region_name": "auto",
    "signature_version": "s3v4",
    "custom_domain": MEDIA_DOMAIN,
    "querystring_auth": False,  # public URLs, no signed query strings
    "default_acl": None,        # R2 does not support object ACLs
}

STORAGES = {
    "default": {
        "BACKEND": "storages.backends.s3.S3Storage",
        "OPTIONS": {**_r2_options, "location": "media", "file_overwrite": False},
    },
    "staticfiles": {
        "BACKEND": "storages.backends.s3.S3Storage",
        "OPTIONS": {**_r2_options, "location": "static"},
    },
}

STATIC_URL = f"https://{MEDIA_DOMAIN}/static/"
MEDIA_URL = f"https://{MEDIA_DOMAIN}/media/"

A few things that took me a while to get right:

  • custom_domain is what makes the generated URLs point at media.firojacharya.com.np instead of the private R2 endpoint. Without it, every image URL is a signed r2.cloudflarestorage.com link that expires.
  • file_overwrite: False on media means two uploads called screenshot.png do not silently replace each other. Django adds a random suffix instead.
  • collectstatic now uploads to R2. It compares timestamps and skips unchanged files, but the first run uploads the whole Django admin and CKEditor 5 bundle, which takes a minute or two.
  • CORS for fonts. Scripts and stylesheets load cross-origin without any setup, but browsers refuse web fonts from another origin unless the bucket sends CORS headers. If admin icons show up as empty boxes, add a CORS policy on the bucket allowing GET from https://firojacharya.com.np.
  • Recent boto3 checksum headers. boto3 1.36 started sending new integrity checksums by default. If uploads fail with checksum errors, set AWS_REQUEST_CHECKSUM_CALCULATION=when_required and AWS_RESPONSE_CHECKSUM_VALIDATION=when_required in the env file.

CKEditor 5 image uploads go through the default storage, so they land in media/ in the bucket with no extra code.

5. Gunicorn under systemd

How many workers?

The usual advice is 2 × cores + 1 workers. On this shape, that formula is the wrong question. The limit is memory, not CPU. Each sync worker loads the whole Django project and settles at roughly 60 to 90 MB for a small app like mine. Two workers is the sweet spot. A third adds little throughput on a fractional CPU and eats into the headroom Postgres needs.

# /etc/systemd/system/gunicorn.service
[Unit]
Description=Gunicorn for firojacharya.com.np
After=network.target postgresql.service

[Service]
User=deploy
Group=www-data
WorkingDirectory=/home/deploy/portfolio
EnvironmentFile=/etc/portfolio/env
RuntimeDirectory=gunicorn
ExecStart=/home/deploy/portfolio/.venv/bin/gunicorn \
    --workers 2 \
    --bind unix:/run/gunicorn/gunicorn.sock \
    --umask 007 \
    --timeout 30 \
    --max-requests 1000 \
    --max-requests-jitter 100 \
    --access-logfile - \
    config.wsgi:application
ExecReload=/bin/kill -s HUP $MAINPID
Restart=on-failure

[Install]
WantedBy=multi-user.target

The user deploy, the path /home/deploy/portfolio and the module config.wsgi are what I use here. Adjust them to your project. One systemd quirk to remember: it does not support comments at the end of a line, so keep notes on their own lines.

Notes on the flags:

  • Unix socket instead of 127.0.0.1:8000. It skips the TCP stack and cannot be reached from the network by accident. RuntimeDirectory=gunicorn makes systemd create /run/gunicorn with the right owner on every start.
  • --umask 007 with Group=www-data gives the socket group read and write access, which Nginx (running as www-data) needs.
  • --max-requests with jitter recycles each worker after about a thousand requests. That caps slow memory growth from leaks in any dependency, and the jitter stops both workers restarting at the same moment.
sudo systemctl daemon-reload
sudo systemctl enable --now gunicorn
sudo systemctl status gunicorn

6. Nginx

Since R2 serves all assets, the Nginx config is short. Its job is TLS termination, buffering slow clients so they do not tie up one of my two workers, and passing requests to the socket.

# /etc/nginx/sites-available/portfolio
server {
    listen 80;
    server_name firojacharya.com.np www.firojacharya.com.np;

    client_max_body_size 10M;   # CKEditor image uploads

    location / {
        proxy_pass http://unix:/run/gunicorn/gunicorn.sock;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_read_timeout 30s;
    }
}
sudo ln -s /etc/nginx/sites-available/portfolio /etc/nginx/sites-enabled/
sudo rm /etc/nginx/sites-enabled/default
sudo nginx -t && sudo systemctl reload nginx

The buffering point is easy to overlook. A sync Gunicorn worker is blocked for as long as its client is connected. Nginx reads the full request first and takes the response off the worker quickly, so a visitor on a slow mobile connection costs an Nginx connection (a few KB) rather than a whole Python process.

I keep this block HTTP-only on purpose. Certbot adds the TLS parts in the next step.

7. TLS with Certbot, and renewing it properly

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d firojacharya.com.np -d www.firojacharya.com.np

Certbot gets the certificate, adds a listen 443 ssl block to the server config, and sets up the HTTP to HTTPS redirect.

Let's Encrypt certificates last 90 days, and I originally read that as "renew every three months". That is the wrong mental model. certbot renew only renews certificates that are within 30 days of expiring, and does nothing otherwise. So the job should run often, daily or twice a day, and let Certbot decide. A cron that literally fires every three months could miss the window and let the certificate lapse.

Also, check whether you already have a scheduler before adding one. The apt and snap packages of Certbot both install a systemd timer:

systemctl list-timers | grep certbot

If a timer shows up, renewal is already handled. I prefer an explicit cron entry I can see in one place, so I disabled the timer and use this:

sudo systemctl disable --now certbot.timer    # or snap.certbot.renew.timer for the snap

# /etc/cron.d/certbot-renew
0 3,15 * * * root certbot renew --quiet --deploy-hook "systemctl reload nginx"

--deploy-hook runs only when a certificate was actually renewed, so Nginx reloads at most once every couple of months. Before trusting any of it, do a dry run:

sudo certbot renew --dry-run

8. Deploys with GitHub Actions

Every push to main SSHes into the VM, pulls, installs dependencies, migrates, collects static files, and restarts Gunicorn. There is no container registry and no build artifact. For one small app on one server, that is enough.

On the server, the deploy user has a dedicated SSH key whose public half is in ~/.ssh/authorized_keys, and the repo is cloned with a read-only deploy key. The private key, host and user are stored as repository secrets.

Restarting Gunicorn needs root, so instead of giving the deploy user full sudo, I allow exactly one command:

# /etc/sudoers.d/deploy  (edit with: sudo visudo -f /etc/sudoers.d/deploy)
deploy ALL=(root) NOPASSWD: /usr/bin/systemctl restart gunicorn

The workflow:

# .github/workflows/deploy.yml
name: Deploy

on:
  push:
    branches: [main]
  workflow_dispatch:

concurrency:
  group: production-deploy
  cancel-in-progress: false

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - name: Deploy over SSH
        uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.VPS_HOST }}
          username: ${{ secrets.VPS_USER }}
          key: ${{ secrets.VPS_SSH_KEY }}
          script: |
            set -euo pipefail
            cd ~/portfolio
            git fetch origin main
            git reset --hard origin/main
            .venv/bin/pip install --quiet -r requirements.txt
            set -a; source /etc/portfolio/env; set +a
            .venv/bin/python manage.py check --deploy --fail-level ERROR
            .venv/bin/python manage.py migrate --noinput
            .venv/bin/python manage.py collectstatic --noinput
            sudo /usr/bin/systemctl restart gunicorn

Some details worth explaining:

  • set -euo pipefail makes the script stop at the first failed command, so a broken migration never gets followed by a restart.
  • concurrency stops two quick pushes from running two deploys at once on the same checkout.
  • git reset --hard origin/main instead of git pull means a stray edit on the server can never block a deploy with a merge conflict. The server is not a place to edit code.
  • Loading /etc/portfolio/env matters because manage.py needs the same variables as Gunicorn. Without it, migrate fails on the missing secret key. This is why the env file is group-owned by deploy instead of world-readable.
  • check --deploy runs Django's production checklist. With --fail-level ERROR, warnings are printed but do not block the deploy, which is useful while the security work below is unfinished.
  • restart vs reload. A HUP reload is gentler, but a full restart is the predictable option after dependency changes. On a site this size the gap is a second or two.

One memory note. pip install is the heaviest thing this box ever does. If a deploy hangs or gets killed, look at dmesg for OOM messages first. Swap is usually what saves it.

A rough memory budget

These numbers are typical figures for this kind of stack, not measurements from my server. Check your own with free -m and ps aux --sort=-rss | head.

ComponentApprox. RAM (resident)
Ubuntu base (systemd, sshd, journald, snapd, Oracle agent)150–250 MB
PostgreSQL (128 MB shared buffers + a few backends)100–180 MB
Gunicorn master25–40 MB
Gunicorn workers (2 × 60–90 MB)120–180 MB
Nginx (master + 1 worker)5–15 MB
Total~400–665 MB
Left for page cache and spikes~300–550 MB, plus 2 GB swap

Two caveats. Postgres shared memory gets counted in every backend's RSS, so adding up ps output overstates its real use. And the free page cache is not wasted. Postgres depends on it for reads, which is why effective_cache_size is set higher than shared_buffers.

What I'd add next

This setup works and has been stable, but I would not call it finished. These are the gaps I know about, roughly in the order I plan to close them.

Security hardening

  • SSH keys only. Set PasswordAuthentication no and PermitRootLogin no in /etc/ssh/sshd_config (or a file in sshd_config.d/), then restart ssh. Test from a second terminal before closing the first one.
  • Firewall: security lists first. Oracle's own docs warn against enabling UFW on its Ubuntu images, because it can conflict with the preloaded iptables rules the instance needs. So I will keep using the VCN security list as the main firewall, limit SSH ingress where practical, and leave the instance iptables rules alone apart from 80 and 443.
  • fail2ban with the sshd jail, to ban IPs that brute-force SSH. It costs a few tens of MB of RAM, which is worth it.
  • Django security settings. Once HTTPS has been stable for a while:
SECURE_SSL_REDIRECT = True
SESSION_COOKIE_SECURE = True
CSRF_COOKIE_SECURE = True
SECURE_HSTS_SECONDS = 3600  # raise to 31536000 once you're sure
SECURE_HSTS_INCLUDE_SUBDOMAINS = True
SECURE_CONTENT_TYPE_NOSNIFF = True
X_FRAME_OPTIONS = "DENY"

Start HSTS with a short value. A year-long HSTS header with a broken certificate locks visitors out, and you cannot take it back.

  • Nginx rate limiting on the admin login, since that is the one endpoint worth brute-forcing:
# in the http {} context, e.g. /etc/nginx/conf.d/ratelimit.conf
limit_req_zone $binary_remote_addr zone=login:10m rate=5r/m;

# inside the server {} block
location /admin/login/ {
    limit_req zone=login burst=5 nodelay;
    proxy_pass http://unix:/run/gunicorn/gunicorn.sock;
    proxy_set_header Host $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Proto $scheme;
}

Moving the admin off /admin/ to a less obvious path also cuts down the noise from bots.

Caching

Right now every page view renders templates and hits Postgres. For a blog where content changes a few times a month, that is wasted work.

  • Per-view caching with Django's cache framework. Even the local-memory backend, LocMemCache, would help, though each worker keeps its own copy. Redis would share a cache between workers but adds another process to the memory budget, so I would measure before adding it.
  • Nginx proxy_cache for anonymous visitors. It is stored on disk, uses almost no RAM, and would let Nginx serve most blog traffic without touching Python at all.
  • Hashed static file names with storages.backends.s3.S3ManifestStaticStorage. Plain filenames make it risky to set long cache headers on R2, because a changed CSS file keeps its old URL. Hashed names make it safe to cache static files for a year.

Operations

Backups are the other honest gap. A nightly pg_dump copied to a separate R2 bucket would cover the database, and media already lives off the server. I would also like basic uptime and log monitoring, so I hear about problems before visitors do.

Wrapping up

A 1 GB free-tier VM is a perfectly reasonable home for a Django portfolio, as long as you treat memory as the budget it is. The choices that make it work:

  • Add swap before anything else
  • Shrink Postgres connections and buffers to match a two-worker app
  • Size Gunicorn by RAM, not CPU, and recycle workers
  • Get static and media files off the box entirely, with R2 on a custom domain
  • Let Certbot decide when to renew, and run its check often
  • Keep the deploy pipeline boring: SSH, pull, migrate, collectstatic, restart

None of this is exotic, and that is the point. Every part is something you can debug at 2 a.m. with journalctl and free -m. Next I will add caching and finish the hardening list, and I will write up how that changes the memory numbers once I have real measurements.

FA

Firoj Acharya

Software developer.