Learn Flask · 15/15

Deployment: Going Live!

7 min read

Deployment: Going Live! 🚀

Congratulations on building your Flask application! You've crafted the routes, perfected the templates, and now it's time to share your creation with the world. This guide will walk you through the process of taking your app from your local machine to a live production server.

1. Preparing for Production: Environment Variables and Secrets 🤫

The Problem: When developing your Flask app, you might have hardcoded sensitive information like database passwords, API keys, or your secret key directly into your code. This is fine for development, but it's a major security risk in a production environment. Imagine accidentally pushing your secret key to a public GitHub repository! 😱

The Solution: Environment Variables

Environment variables are variables that are set in the operating system where your application is running, rather than within the application code itself. This allows you to keep your sensitive information separate from your codebase.

How to Use Them:

  1. Install python-dotenv: This helpful library allows you to load environment variables from a .env file during development, mimicking how they would be set in a production environment.

    bash
    pip install python-dotenv
  2. Create a .env file: In the root directory of your project, create a file named .env. Important: Add .env to your .gitignore file to prevent it from being committed to version control.

    ini
    SECRET_KEY='a-super-secret-and-long-random-string'
    DATABASE_URL='postgresql://user:password@host:port/dbname'
    API_KEY='your-super-secret-api-key'
  3. Load the variables in your app:

    python
    from flask import Flask
    from dotenv import load_dotenv
    import os
    
    load_dotenv() # take environment variables from .env.
    
    app = Flask(__name__)
    app.config['SECRET_KEY'] = os.environ.get('SECRET_KEY')
    app.config['SQLALCHEMY_DATABASE_URI'] = os.environ.get('DATABASE_URL')

    This setup ensures that when you run your app locally, it will pick up the secrets from your .env file, and when you deploy it, it will get them from the production server's environment.

Interesting Fact: The concept of separating configuration from code is one of the "Twelve-Factor App" principles, a set of best practices for building modern, scalable web applications.

2. Replacing the Development Server: Introduction to Gunicorn (WSGI) 🦄

The Problem: The server you've been using to run your Flask app with flask run is fantastic for development. It has helpful features like automatic reloading when you make changes. However, it's not built to handle the demands of a live application with multiple users. It's like using a bicycle to deliver pizzas for an entire city – it works for a few, but it won't scale.

The Solution: A Production-Ready WSGI Server like Gunicorn

WSGI (Web Server Gateway Interface) is a standard interface between web servers and Python web applications. Gunicorn ('Green Unicorn') is a popular and robust WSGI server that is designed for production use. It can handle multiple requests simultaneously and is much more stable and efficient than the development server.

Getting Started with Gunicorn:

  1. Installation:

    bash
    pip install gunicorn
  2. Running your app with Gunicorn: Let's say your main Flask application file is named app.py and the Flask instance is called app. You would run it like this:

    bash
    gunicorn --workers 3 app:app
    • --workers 3: This tells Gunicorn to create 3 worker processes. A good starting point is 2-4 workers per CPU core.
    • app:app: The first app is the name of your Python file (app.py), and the second app is the name of the Flask application instance within that file.

Under the Hood: Gunicorn acts as a manager, spawning multiple "worker" processes. Each worker is a copy of your Flask application. When a request comes in, Gunicorn hands it off to one of the available workers to process. This allows your application to handle multiple requests at the same time.

3. Using Nginx as a Reverse Proxy 🔄

The Problem: While Gunicorn is great at running your Python code, it's not the best at handling direct traffic from the internet. Things like serving static files (CSS, JavaScript, images) or protecting against certain types of attacks are better handled by a dedicated web server.

The Solution: Nginx as a Reverse Proxy

Nginx (pronounced "engine-x") is a high-performance web server. When used as a reverse proxy, it sits in front of your Gunicorn server and acts as an intermediary. It receives incoming requests from users and forwards them to Gunicorn.

A Real-World Analogy: Imagine a busy restaurant. Nginx is the friendly host at the front door. They greet the customers (incoming requests), take their coats (handle static files), and then guide them to an available table where a waiter (Gunicorn worker) will take their order (process the dynamic request). This is much more efficient than having the chefs (your Flask app) also manage the front door.

Key Benefits of using Nginx:

  • Serving Static Files: Nginx is incredibly efficient at serving static files directly, freeing up Gunicorn to focus on running your Python code.
  • Load Balancing: If you have multiple servers running your app, Nginx can distribute the traffic between them.
  • Security: Nginx can help protect your application from common web vulnerabilities.
  • SSL Termination: Nginx can handle HTTPS, encrypting traffic between the user and the server.

Example Nginx Configuration:

Here's a basic Nginx configuration file that proxies requests to a Gunicorn server running on localhost:8000:

nginx
server {
    listen 80;
    server_name your_domain.com www.your_domain.com;

    location / {
        proxy_pass http://127.0.0.1:8000;
        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;
    }

    location /static {
        alias /path/to/your/project/static;
    }
}

This configuration tells Nginx to listen for requests on port 80 for your_domain.com. Any request to the root URL (/) will be passed to Gunicorn. Requests for /static will be served directly from your project's static folder.

4. Deploying Your App to a Cloud Provider (e.g., Render, Heroku) ☁️

The Problem: Setting up and managing your own server can be a complex and time-consuming task. You need to worry about the operating system, security updates, and a host of other administrative tasks.

The Solution: Platform as a Service (PaaS)

Cloud providers like Render and Heroku offer a "Platform as a Service" (PaaS) that simplifies the deployment process. You provide your code, and they handle the underlying infrastructure, servers, and networking for you.

Deploying to Render

Render is a popular choice for its simplicity and developer-friendly experience.

Steps for a typical Render deployment:

  1. Push your code to a Git repository (like GitHub).
  2. Create a requirements.txt file: This file lists all the Python packages your application needs.
    bash
    pip freeze > requirements.txt
  3. Create a render.yaml file (optional, but recommended): This file defines your services and how they should be built and run.
  4. Connect your Git repository to Render: In the Render dashboard, you'll create a new web service and connect it to your repository.
  5. Configure your build and start commands:
    • Build Command: pip install -r requirements.txt
    • Start Command: gunicorn app:app
  6. Set Environment Variables: In the Render dashboard, you'll add your secret keys and other environment variables.

Render will then automatically build and deploy your application. Any future pushes to your connected Git branch will trigger a new deployment.

Deploying to Heroku

Heroku is another well-established PaaS provider. The process is very similar to Render.

Key Heroku Files:

  • requirements.txt: Same as with Render, this lists your Python dependencies.
  • Procfile: This file tells Heroku how to run your application.
    stata
    web: gunicorn app:app
  • runtime.txt (optional): You can use this to specify the Python version Heroku should use.

General Heroku Workflow:

  1. Create a Heroku account and install the Heroku CLI.
  2. Initialize a Git repository for your project.
  3. Create a Heroku application: heroku create your-app-name
  4. Provision any necessary add-ons (like a database).
  5. Set your environment variables: heroku config:set SECRET_KEY='your-secret-key'
  6. Deploy your code: git push heroku main

Heroku will then build your application and deploy it to a public URL.


Additional Resources for Further Reading:

Challenge

You are finalizing the deployment configuration for a new Flask application. The application instance is named main_app and is located in a Python file named wsgi.py.

Your task is to provide the necessary commands and configuration snippets for three different parts of the deployment pipeline. Fill in the code in the editor to complete the configuration.

Part 1: Gunicorn Command

Write the shell command to start the application server using Gunicorn. The server must:

  • Run with 4 worker processes.
  • Bind to a Unix socket located at /sockets/gunicorn.sock.

Part 2: Nginx Reverse Proxy

Complete the Nginx server block to act as a reverse proxy for the Gunicorn server from Part 1. The configuration must:

  • Listen on the standard HTTP port (80).
  • Handle requests for the domain yourdomain.com.
  • Serve static files directly. Requests for URLs starting with /static/ should map to files in the /home/user/myproject/static/ directory on the server. You can use the root directive for this.
  • Proxy all other requests to the Gunicorn Unix socket using the proxy_pass directive.

Part 3: Heroku Procfile

Write the content for a Heroku Procfile. This file should define a web process that:

  • Starts the application using Gunicorn.
  • Binds to the host and port provided by Heroku's environment variables ($HOST and $PORT). For maximum compatibility, bind to 0.0.0.0:$PORT.
  • Uses 3 worker processes.

Expected result

Your final submission should contain the completed code block with the three parts filled out according to the instructions.

Part 1: Gunicorn Command
The command should correctly specify the number of workers, bind to the Unix socket, and reference the application instance wsgi:main_app.

sh
gunicorn --workers 4 --bind unix:/sockets/gunicorn.sock wsgi:main_app

Part 2: Nginx Server Block
The Nginx configuration should include a root directive for the static location and a proxy_pass directive pointing to the Gunicorn socket for the main location.

nginx
server {
    listen 80;
    server_name yourdomain.com;

    location /static/ {
        root /home/user/myproject;
    }

    location / {
        proxy_pass http://unix:/sockets/gunicorn.sock;
    }
}

Part 3: Heroku Procfile
The Procfile line must define the web process type and use Gunicorn to run the wsgi:main_app application, binding to the dynamic host and port variables provided by Heroku.

stylus
web: gunicorn --workers 3 --bind 0.0.0.0:$PORT wsgi:main_app
plaintext

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.