Deploying Django Micro-Services on Render at ZERO Cost

in DevTalk2 years ago


kobu-agency-7okkFhxrxNw-unsplash.jpg
Photo by KOBU Agency on Unsplash

Have you been badly hit by the recent economic turmoil?

No, I mean the recent pricing changes of all major XaaS companies starting at the last quarter of this year, you might have gone scrambling for alternatives.

Yep, there are a handful, but we're talking Python here, so that further limits us to less than ten, maybe.

I've tried Deta, Fly.io, Back4App... but Deta is like a high-school kid project. Fly.io wants you to pay upfront. And Back4App isn't too optimize yet for Python.

So I'm trying Render.

Render supported Python 3, but only for Django. So, if you're using other frameworks such as Flask, you might need to do some changes. As a simple walkthrough, follow on and let's build a Django project and deploy it on Render!

Initial Requirements

Before anything else, make sure you have an account on Render and also a valid GitHub/ or GitLab account to load your repository from.

Let's Build the App First

Please take note that these are run on Windows 10 and in Command Prompt, or unless stated explicitly.

1. Open the command line (Windows), then go to your desired root directory, but not on your repository since we will still create that. Install python-poetry and Django:

pip install poetry

2. Create your project directory, you can change site based on your actual webapp:

poetry new site
cd site

3. Back to the project repository, do a little cleanup and delete the auto-generated folders:

rmdir -rf site tests /s /q

4. Open the pyproject.toml file and edit the Python version to 3.7 as supported by Render.

[tool.poetry.dependencies]
python = "^3.9"

5. Back to the command line, add Django to the dependencies and create the project application:

poetry add django
poetry run django-admin startproject site .

6. The generic Django application is now complete, verify by running the command:

python manage.py migrate
poetry run py manage.py runserver

To fully configure and modify your Django application, go to the latest Django Documentation and scroll over the links for the perfect tutorial for you.

Post-Production Changes

Before deploying to Render, do some necessary changes first. For the complete deployment guide, go to the Render Python Django Documentation.

1. Open the site/settings.py file and add the following lines:

import os
SECRET_KEY = os.environ.get("SECRET_KEY", default="<your-secret-key>")

2. On the same site/settings.py file, edit the value of the DEBUG variable:

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = 'RENDER' not in os.environ

3. On the same site/settings.py file, under the ALLOWED_HOSTS declaration, add the following lines:

RENDER_EXTERNAL_HOSTNAME = os.environ.get("RENDER_EXTERNAL_HOSTNAME")
if RENDER_EXTERNAL_HOSTNAME:
    ALLOWED_HOSTS.append(RENDER_EXTERNAL_HOSTNAME)

4. Add a way to host your static files, run on the command line:

poetry add whitenoise

5. On the same site/settings.py file, find the MIDDLEWARE list variable and append the value:

"whitenoise.middleware.WhiteNoiseMiddleware"

6. On the same site/settings.py file, find the STATIC_URL declaration and replace with the following lines:

STATIC_URL = "/static/"
if not DEBUG:
    STATIC_ROOT = os.path.join(BASE_DIR, "staticfiles")
    STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage"

7. Create a build.sh file on the root project directory, add the following lines:

#!/usr/bin/env bash
set -o errexit
poetry install
python manage.py collectstatic --no-input
python manage.py migrate

8. Make sure that the script is executable, run the command on MINGW64 or Git for Windows shell:

chmod a+x build.sh

9. Back to the command line, add Gunicorn to the dependencies:

poetry add gunicorn

Deploying to Render

Note that the generic Django Application is ready, we will have your project deployed to Render.

1. Create a render.yaml file on the root project directory, add the following lines:

databases:
  - name: mysite
    databaseName: mysite
    user: mysite

services:
  - type: web
    name: site
    env: python
    buildCommand: "./build.sh"
    startCommand: "gunicorn site.wsgi:application"
    envVars:
      - key: SECRET_KEY
        generateValue: true
      - key: WEB_CONCURRENCY
        value: 4

2. Make sure you already have a GitHub or GitLab project repository, run the following commands:

git init
git add .
git commit -m "<commit-message>"
git remote add origin <https/ssh-repo-url>
git push --force origin main

3. Go to the Render Dashboard and click the NEW > Web Service. Connect to your remote GitHub or GitLab account, select the repository to connect as a web service.

4. After setting up, depending on the chosen deployment, the application should be running on site.onrender.com website. When encountering build error, just fix the bug and commit to remote repository then manually deploy again.

Create DJango SuperUser Account

Once the Django application is live, create a superuser account using the Render shell:

python manage.py createsuperuser

And that's it, you have just deployed a Django Application on Render for FREE! Do you think it's better than Heroku? If you have questions, sentiments for Render, or just want to connect, feel free to comment below or DM me in my social media :)





 
Rydeon ⟠
 
Sup frens, Rydeon here!

I do nerd-stuff to feed the wallet, relatable? I live in Cebu City, but most of the time inside the computer. Frequently doing Python, Analytics, ML, and always coffee. I've been to blockchains and cryptocurrencies for some time already, but it would be dumb and risky to share unreliable financial advice. So, don't ask me.

Thinking of following? I'll gonna resume writing about time-waster games, awesome technology, and the cafés I went to connect to their Wi-Fi. g2g...



Sort:  

Hey there @avid.serosik!

I just read your blog about deploying Django micro-services on Render at zero cost, and I think it's a fantastic idea. As a software developer, I can really appreciate the effort you've gone to in order to create this cost-effective solution. This will be incredibly helpful to a lot of developers who are looking to save money, and they'll be able to get the most out of their applications with this setup. Thanks for sharing your knowledge!