DEV Community

Anna lilith
Anna lilith

Posted on

Deploy Python Web Apps for Free: Complete Guide

Deploy Python Web Apps for Free: Complete Guide

Deploying Python web apps used to require expensive servers and complex configurations. Today, platforms like Railway, Render, and Fly.io offer generous free tiers. This guide walks you through deploying on every major platform.

What You'll Build

Working deployments of a Python web application on Railway, Render, Fly.io, and Cloudflare Tunnel. You'll understand the tradeoffs of each platform and choose the best option for your needs.

Why Deploy for Free?

Free deployment tiers let you:

  • Launch MVPs without upfront costs
  • Learn DevOps without financial risk
  • Host side projects professionally
  • Scale to paid when revenue justifies it

Full Tutorial

Step 1: Prepare Your Application

# app.py
from flask import Flask, jsonify
import os

app = Flask(__name__)

@app.route("/")
def home():
    return jsonify({
        "app": "Python Deploy Demo",
        "version": "1.0.0",
        "status": "running"
    })

@app.route("/health")
def health():
    return jsonify({"status": "healthy"}), 200

if __name__ == "__main__":
    port = int(os.environ.get("PORT", 8000))
    app.run(host="0.0.0.0", port=port)
Enter fullscreen mode Exit fullscreen mode
# requirements.txt
flask==3.0.0
gunicorn==21.2.0
Enter fullscreen mode Exit fullscreen mode
# .gitignore
__pycache__/
*.pyc
.env
.venv/
*.egg-info/
dist/
build/
Enter fullscreen mode Exit fullscreen mode

Step 2: Deploy to Railway

Railway offers a frictionless deployment experience with automatic HTTPS.

# railway.json
{
  "build": {
    "builder": "nixpacks"
  },
  "deploy": {
    "startCommand": "gunicorn app:app",
    "healthcheckPath": "/health",
    "restartPolicyType": "on_failure",
    "restartPolicyMaxRetries": 3
  }
}
Enter fullscreen mode Exit fullscreen mode
# Deploy with Railway CLI
npm install -g @railway/cli
railway login
railway init
railway up

# Set environment variables
railway variables set SECRET_KEY=your-secret-key
railway variables set DATABASE_URL=your-db-url

# Check deployment
railway logs
railway status
Enter fullscreen mode Exit fullscreen mode

Step 3: Deploy to Render

Render provides free static sites and web services with auto-deploy from GitHub.

# render.yaml
services:
  - type: web
    name: python-app
    runtime: python
    buildCommand: pip install -r requirements.txt
    startCommand: gunicorn app:app
    envVars:
      - key: PYTHON_VERSION
        value: "3.12.0"
      - key: SECRET_KEY
        generateValue: true
    healthCheckPath: /health
    autoDeploy: true
Enter fullscreen mode Exit fullscreen mode

Steps:

  1. Push code to GitHub
  2. Go to render.com → New → Web Service
  3. Connect your GitHub repo
  4. Render auto-detects Python and deploys
  5. Free tier includes 750 hours/month

Step 4: Deploy to Fly.io

Fly.io offers container-based deployment with global edge distribution.

# Install flyctl
curl -L https://fly.io/install.sh | sh
fly auth signup
fly auth login

# Initialize and deploy
fly launch
fly deploy

# Set secrets
fly secrets set SECRET_KEY=your-secret-key
fly secrets set DATABASE_URL=your-db-url

# Check status
fly status
fly logs
Enter fullscreen mode Exit fullscreen mode

Step 5: Docker Configuration

# Dockerfile
FROM python:3.12-slim

WORKDIR /app

# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application
COPY . .

# Create non-root user
RUN useradd --create-home appuser
USER appuser

EXPOSE 8000

CMD ["gunicorn", "--bind", "0.0.0.0:8000", "--workers", "4", "app:app"]
Enter fullscreen mode Exit fullscreen mode
# docker-compose.yml
version: '3.8'
services:
  web:
    build: .
    ports:
      - "8000:8000"
    environment:
      - SECRET_KEY=${SECRET_KEY}
      - DATABASE_URL=${DATABASE_URL}
    restart: unless-stopped
    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8000/health"]
      interval: 30s
      timeout: 10s
      retries: 3
Enter fullscreen mode Exit fullscreen mode
# Run locally with Docker
docker build -t python-app .
docker run -p 8000:8000 --env-file .env python-app

# Or with docker-compose
docker-compose up -d
docker-compose logs -f
Enter fullscreen mode Exit fullscreen mode

Step 6: Cloudflare Tunnel (Free HTTPS)

Cloudflare Tunnel exposes your local or server app to the internet with free HTTPS.

# Install cloudflared
# macOS
brew install cloudflared

# Linux
wget https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-amd64
chmod +x cloudflared-linux-amd64
sudo mv cloudflared-linux-amd64 /usr/local/bin/cloudflared

# Quick tunnel (no account needed)
cloudflared tunnel --url http://localhost:8000

# Named tunnel (persistent URL)
cloudflared tunnel create my-app
cloudflared tunnel route dns my-app myapp.example.com
cloudflared tunnel run --url http://localhost:8000 my-app
Enter fullscreen mode Exit fullscreen mode

Step 7: Deployment Comparison

Feature Railway Render Fly.io Cloudflare
Free tier $5/month credit 750 hrs/month 3 shared VMs Unlimited tunnels
HTTPS Auto Auto Auto Auto
Custom domain Yes Yes Yes Yes
Database Yes (paid) Yes (paid) Yes (paid) No
Ease of use ⭐⭐⭐⭐⭐ ⭐⭐⭐⭐ ⭐⭐⭐ ⭐⭐
Best for Full-stack apps Simple web apps Global edge Local dev sharing

Step 8: Production Best Practices

# config.py
import os
from datetime import timedelta

class Config:
    SECRET_KEY = os.environ.get("SECRET_KEY", "dev-key-change-in-production")
    SESSION_COOKIE_SECURE = True
    SESSION_COOKIE_HTTPONLY = True
    SESSION_COOKIE_SAMESITE = "Lax"
    PERMANENT_SESSION_LIFETIME = timedelta(hours=24)

    # Database
    SQLALCHEMY_DATABASE_URI = os.environ.get("DATABASE_URL")
    SQLALCHEMY_TRACK_MODIFICATIONS = False

    # Rate limiting
    RATELIMIT_DEFAULT = "100/hour"
    RATELIMIT_STORAGE_URI = "memory://"

class ProductionConfig(Config):
    DEBUG = False
    TESTING = False

class DevelopmentConfig(Config):
    DEBUG = True
Enter fullscreen mode Exit fullscreen mode
# wsgi.py
from app import create_app

app = create_app()

if __name__ == "__main__":
    app.run()
Enter fullscreen mode Exit fullscreen mode

Deployment Checklist

  • ✅ Set environment variables (never commit secrets)
  • ✅ Configure health check endpoint
  • ✅ Enable automatic deployments from git
  • ✅ Set up error logging (Sentry, LogDNA)
  • ✅ Configure custom domain with SSL
  • ✅ Set up database backups
  • ✅ Monitor resource usage
  • ✅ Configure auto-scaling rules

Get the Code

Ready to use these tools? Browse our collection of tested, production-ready Python scripts:

🔗 Browse Products: Anna's Digital Products

All products include:

  • ✅ Tested and verified code
  • ✅ Instant delivery via crypto or card
  • ✅ Free updates forever
  • ✅ Telegram bot support (@AnnaLilithBot)

Get the Production-Ready Version

Don't want to build it yourself? We have production-ready versions at https://petroleum-board-hawaii-lol.trycloudflare.com.

What you get:

  • Complete, tested Python code
  • Documentation and setup guides
  • Instant delivery after crypto payment
  • Free updates

Browse the collection →

Top comments (0)