How to Install Flask on Hosting: A Complete Step-by-Step Guide
Flask is a lightweight, flexible web framework for Python that empowers developers to build and deploy web applications quickly and efficiently. Whether you're launching a personal project, a REST API, or a full-scale web service, knowing how to correctly install and configure Flask on a hosting environment is an essential skill. This comprehensive guide walks you through every step — from server setup to production deployment with Gunicorn and Nginx.
1. Prerequisites
Before diving into the installation process, make sure you have the following in place:
Hosting Environment That Supports Python
You need a hosting service that gives you full control over your server environment. Shared hosting plans often restrict Python execution, so for Flask deployments, a VPS Hosting plan or a Dedicated Server is strongly recommended. These options give you root access, full package management capabilities, and the flexibility to configure your stack exactly as needed.
SSH Access
You'll need SSH access to connect to your remote server and execute commands. Most Linux-based VPS and dedicated server environments support this out of the box.
Python Installed
Python 3.8 or higher is recommended. Most modern hosting environments come with Python pre-installed, but we'll verify this during setup.
Optional: A Domain Name
If you plan to make your Flask app publicly accessible via a domain rather than a raw IP address, consider registering one through Domain Registration before you begin.
2. Connecting to Your Server via SSH
Open your terminal (Linux/macOS) or an SSH client such as PuTTY (Windows) and connect to your server:
ssh username@your_server_ipReplace username with your actual server username and your_server_ip with your server's public IP address.
Once connected, verify that Python 3 is available:
python3 --versionYou should see output similar to Python 3.10.x. If Python is not installed, proceed to install it:
sudo apt install python33. Updating Your Server
Before installing any packages, it's best practice to update your system's package list and upgrade existing packages to their latest versions:
sudo apt update
sudo apt upgrade -yThis ensures you're working with the most stable and secure versions of all dependencies.
4. Installing Flask
Step 1: Install pip
pip is Python's package manager and is required to install Flask and other Python libraries. Install it if it's not already present:
sudo apt install python3-pip -yVerify the installation:
pip3 --versionStep 2: Create a Project Directory
Organize your application by creating a dedicated directory:
mkdir my_flaskapp
cd my_flaskappStep 3: Set Up a Virtual Environment
Using a virtual environment isolates your project's dependencies from the global Python installation, preventing version conflicts and keeping your server clean:
sudo apt install python3-venv -y
python3 -m venv venvActivate the virtual environment:
source venv/bin/activateYour terminal prompt will change to indicate that the virtual environment is active, typically showing (venv) at the beginning of the line.
Step 4: Install Flask
With the virtual environment activated, install Flask using pip:
pip install FlaskConfirm the installation:
flask --versionYou should see the Flask version along with the Python and Werkzeug versions.
5. Creating a Simple Flask Application
Step 1: Create the Application File
Create a new file called app.py inside your project directory:
nano app.pyStep 2: Write Your Flask Application
Add the following minimal Flask application code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return "Hello, World! Flask is running successfully."
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)Code breakdown:
Flask(__name__)— Creates a new Flask application instance.@app.route('/')— Defines a URL route for the homepage.app.run(host='0.0.0.0', port=5000)— Starts the development server, making it accessible on all network interfaces at port 5000.
Step 3: Save and Exit
Press CTRL + X, then Y, and hit Enter to save the file and exit the nano editor.
6. Running Your Flask Application in Development Mode
Start the Flask development server to test your application:
python app.pyYour application will now be accessible in a web browser at:
http://your_server_ip:5000> Important: The built-in Flask development server is not suitable for production use. It is single-threaded, not optimized for performance, and lacks critical security features. Always use a production-grade WSGI server for live deployments.
7. Deploying Flask in a Production Environment with Gunicorn
For production deployments, Gunicorn (Green Unicorn) is the most widely used Python WSGI HTTP server. It handles multiple concurrent requests efficiently and integrates seamlessly with Nginx.
Step 1: Install Gunicorn
With your virtual environment still active, install Gunicorn:
pip install gunicornStep 2: Run Your Application with Gunicorn
Launch your Flask app using Gunicorn, binding it to localhost on port 8000:
gunicorn app:app -b 127.0.0.1:8000 --workers 3Parameter explanation:
app:app— Refers to theappobject inside theapp.pyfile.-b 127.0.0.1:8000— Binds Gunicorn to localhost on port 8000 (Nginx will handle external traffic).--workers 3— Spawns 3 worker processes to handle concurrent requests. A common formula is(2 × CPU cores) + 1.
Step 3: Run Gunicorn as a Systemd Service (Recommended)
To ensure Gunicorn starts automatically on server reboot, create a systemd service file:
sudo nano /etc/systemd/system/my_flaskapp.serviceAdd the following configuration:
[Unit]
Description=Gunicorn instance to serve my_flaskapp
After=network.target
[Service]
User=your_username
Group=www-data
WorkingDirectory=/home/your_username/my_flaskapp
Environment="PATH=/home/your_username/my_flaskapp/venv/bin"
ExecStart=/home/your_username/my_flaskapp/venv/bin/gunicorn app:app -b 127.0.0.1:8000 --workers 3
[Install]
WantedBy=multi-user.targetReplace your_username with your actual server username. Then enable and start the service:
sudo systemctl daemon-reload
sudo systemctl start my_flaskapp
sudo systemctl enable my_flaskappCheck the service status:
sudo systemctl status my_flaskapp8. Configuring Nginx as a Reverse Proxy
Nginx acts as a reverse proxy, sitting in front of Gunicorn and handling all incoming HTTP/HTTPS traffic. This setup improves performance, enables SSL termination, and allows you to serve static files efficiently.
Step 1: Install Nginx
sudo apt install nginx -yStep 2: Create an Nginx Configuration File
Create a new server block configuration for your Flask application:
sudo nano /etc/nginx/sites-available/my_flaskappAdd the following configuration:
server {
listen 80;
server_name your_domain_or_ip; # Replace with your domain or server IP
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 /home/your_username/my_flaskapp/static;
expires 30d;
}
}Step 3: Enable the Configuration
Create a symbolic link to enable the site and test the Nginx configuration:
sudo ln -s /etc/nginx/sites-available/my_flaskapp /etc/nginx/sites-enabled
sudo nginx -tIf the test returns syntax is ok and test is successful, restart Nginx:
sudo systemctl restart nginxYour Flask application is now accessible at http://your_domain_or_ip on port 80.
9. Securing Your Flask Application with SSL/HTTPS
Running your application over HTTPS is no longer optional — it's a fundamental requirement for security, user trust, and SEO rankings. You can obtain and install a free SSL certificate using Certbot with Let's Encrypt, or purchase a premium certificate through SSL Certificates for enhanced validation and warranty coverage.
Install Certbot and Obtain a Free SSL Certificate
sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d your_domain.com -d www.your_domain.comCertbot will automatically modify your Nginx configuration to enable HTTPS and set up automatic certificate renewal.
Verify auto-renewal is configured:
sudo certbot renew --dry-run10. Firewall Configuration
Ensure your server's firewall allows traffic on the necessary ports:
sudo ufw allow OpenSSH
sudo ufw allow 'Nginx Full'
sudo ufw enable
sudo ufw statusNginx Full opens both port 80 (HTTP) and port 443 (HTTPS).
11. Troubleshooting Common Issues
| Issue | Likely Cause | Solution |
|---|---|---|
502 Bad Gateway | Gunicorn is not running | Check sudo systemctl status my_flaskapp |
Permission denied on socket | Incorrect file permissions | Ensure the Nginx user has access to the app directory |
| Flask app not found | Wrong working directory in service file | Double-check WorkingDirectory path in systemd config |
| Port 5000 not accessible | Firewall blocking the port | Open the port with sudo ufw allow 5000 (dev only) |
ModuleNotFoundError | Virtual environment not activated | Ensure ExecStart points to the venv's Python/Gunicorn binary |
12. Summary and Next Steps
Deploying a Flask application on a hosting server involves several interconnected steps: setting up a clean server environment, installing Python and Flask within a virtual environment, configuring Gunicorn as a production WSGI server, and placing Nginx in front as a reverse proxy. Adding SSL encryption finalizes a secure, production-ready deployment.
Here's a quick recap of the full deployment stack:
- Flask — Python web framework
- Gunicorn — Production WSGI server
- Nginx — Reverse proxy and static file server
- SSL/TLS — HTTPS encryption
- Systemd — Process management and auto-restart
For the best Flask hosting experience, you need a server environment that gives you full root access and reliable performance. AlexHost's VPS Hosting plans are an excellent choice, offering SSD storage, dedicated resources, and full SSH access. If you need even more power for high-traffic applications, explore our Dedicated Servers for maximum performance and isolation.
If you're managing multiple web projects and prefer a control panel interface, consider our VPS with cPanel option, which simplifies server management while still giving you the flexibility to run Python applications.
By following this guide, your Flask application is now properly configured, secured, and ready to serve real users in a production environment. Keep your dependencies updated regularly, monitor your application logs, and implement proper backup strategies to maintain a healthy, long-running deployment.
