Skip to main content
Flask Basics Tutorial
CHAPTER 19 Beginner

Deploying Flask Applications

Updated: May 14, 2026
35 min read

# CHAPTER 19

Deploying Flask Applications

1. Introduction

Building a web application on http://127.0.0.1:5000 is only half the journey. To allow users worldwide to access your platform, you must Deploy your Flask application to a live web server on the internet. Deploying a Python framework requires significantly more configuration than uploading a simple HTML/CSS website. In this chapter, we will secure your environment variables, configure the Gunicorn WSGI server, and explore Platform-as-a-Service (PaaS) hosting solutions.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Secure sensitive keys using python-dotenv.
  • Prepare app.py for a production environment (disabling debug).
  • Understand the critical role of Gunicorn (WSGI Server).
  • Generate a requirements.txt file for the cloud server.
  • Understand the deployment pipeline to platforms like Render or Heroku.

3. Beginner-Friendly Explanation

Imagine you built a magnificent robot (your Flask App) in your garage (your laptop). You want the whole town to use the robot. You can't just leave it in your garage; you have to rent a storefront (a Server). Furthermore, your robot currently runs on a tiny battery (the app.run() command), which is fine for testing but will explode if 100 people try to use the robot at once. You must hook the robot up to a heavy-duty industrial generator (Gunicorn) to handle massive web traffic. Finally, the robot holds the key to the vault (Database Passwords). You must hide that key in a secure lockbox (Environment Variables) so no one peeking through the window (GitHub) can steal it.

4. Step 1: Environment Variables (.env)

The biggest mistake beginners make is uploading their app.py file to GitHub with their SECRET_KEY and database passwords typed directly into the code. Bots scrape GitHub 24/7 and will hijack your server in seconds.

Install: pip install python-dotenv

Create a .env file in the root of your project:

env
1234
# Do not use quotes!
FLASK_DEBUG=False
SECRET_KEY=my_ultra_secure_random_string_123!
DATABASE_URL=postgres://user:password@cloud-database-url.com/db

CRITICAL: Add .env to your .gitignore file. It must never go to GitHub.

Update app.py:

python
123456789101112
import os
from flask import Flask
from dotenv import load_dotenv

# Load the variables from the hidden file!
load_dotenv()

app = Flask(__name__)

# Pull the secrets securely using os.environ
app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')

5. Step 2: The Production Server (Gunicorn)

The command python app.py starts the Werkzeug development server. It is single-threaded and will crash under heavy traffic. In production, we use a robust Web Server Gateway Interface (WSGI) called Gunicorn.

Install: pip install gunicorn

Instead of running Python, the live cloud server will start your app using this terminal command:

bash
12
# syntax: gunicorn [filename]:[flask_app_object_name]
gunicorn app:app

*(Note: Gunicorn only works on Mac/Linux servers. If you develop on Windows, you can test it using a tool called Waitress, but production servers are almost always Linux).*

6. Step 3: The Requirements File

When you upload your code to a cloud server, the server doesn't know what packages to install (Flask, SQLAlchemy, Gunicorn, Dotenv). You must provide a list.

Run this in your terminal:

bash
1
pip freeze > requirements.txt

*The cloud server will read this text file and automatically run pip install -r requirements.txt for you during the build process.*

7. Hosting Options: Where to Deploy?

  • PaaS (Render, Heroku, Railway): The modern standard for beginners. You link your GitHub repository. Every time you push code, the platform automatically downloads it, reads requirements.txt, installs dependencies, and turns on Gunicorn. It is fully automated and highly recommended.
  • VPS (DigitalOcean, AWS EC2): You rent a blank Linux computer. You must manually install Python, configure an Nginx reverse-proxy to route port 80 to port 5000, and set up Gunicorn as a background system service. Powerful and cheap, but extremely difficult for beginners.

8. Best Practices

  • Cloud Databases (PostgreSQL): SQLite is fantastic for local development, but it fails in production when multiple users try to write to the database simultaneously. You should transition your production app to PostgreSQL. Services like Render or Supabase provide managed Postgres databases with a connection string you simply paste into your cloud platform's Environment Variables dashboard.

9. Common Mistakes

  • Forgetting app:app Configuration: If you used the Application Factory pattern (Chapter 12) and your code is in run.py, the gunicorn command is gunicorn run:app. The first word is the name of the Python file (without .py), and the second word is the name of the Flask object inside that file.

10. Exercises

  1. 1. Explain why the built-in Flask development server (triggered by app.run()) must never be used in a live production environment. What package replaces it?

11. Coding Challenges

  • Challenge: Audit your local Flask project. Install python-dotenv, create a .env file, and successfully move your SECRET_KEY out of your Python code and into the hidden environment file. Ensure the local server still runs.

12. MCQs with Answers

Question 1

Which Python package is considered the industry standard for serving Flask applications in a production Linux environment, acting as a robust WSGI interface capable of handling multiple concurrent requests?

Question 2

Why is the python-dotenv package critical for deploying secure web applications?

13. Interview Questions

  • Q: Walk me through the necessary configuration changes to transition a Flask project from a local development environment (app.run(debug=True)) to a secure production environment.
  • Q: Explain the role of the requirements.txt file in the deployment pipeline. How does a Platform-as-a-Service (PaaS) utilize this file during the automated build process?

14. FAQs

Q: How do I get HTTPS (the padlock) for my website? A: If you use a PaaS (Render/Heroku/Vercel), they provide an SSL certificate automatically. If you deploy manually to a Linux VPS, you must install an Nginx server and generate a free SSL certificate using a command-line tool called Certbot (Let's Encrypt).

15. Summary

In Chapter 19, our Flask application graduated from the local laptop to the live internet. We learned the critical security protocol of isolating sensitive data using .env files and os.environ. We prepared our architecture for heavy traffic by replacing the fragile development server with industrial-grade Gunicorn. Finally, we generated our dependency lists (requirements.txt) and explored automated PaaS deployment workflows to share our creation with the world.

16. Next Chapter Recommendation

You possess the knowledge of a professional backend Python engineer. Now it's time to prove it. Proceed to Chapter 20: Flask Interview Questions and Practice Challenges.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·