Docs / Programming & Development / Python Virtual Environments and Deployment

Python Virtual Environments and Deployment

By Admin · Feb 25, 2026 · Updated Apr 23, 2026 · 27 views · 1 min read

Why Virtual Environments?

Virtual environments isolate project dependencies, preventing conflicts between different Python projects on the same server. Each project gets its own set of packages independent of the system Python.

Creating a Virtual Environment

# Install venv module (if not present)
sudo apt install -y python3-venv

# Create virtual environment
python3 -m venv /var/www/myapp/venv

# Activate it
source /var/www/myapp/venv/bin/activate

# Install dependencies
pip install -r requirements.txt

# Deactivate when done
deactivate

Deploying a Flask Application

# Install Gunicorn (WSGI server)
pip install gunicorn

# Test run
gunicorn --bind 127.0.0.1:8000 app:app

Systemd Service

Create /etc/systemd/system/myapp.service:

[Unit]
Description=My Flask Application
After=network.target

[Service]
User=www-data
WorkingDirectory=/var/www/myapp
ExecStart=/var/www/myapp/venv/bin/gunicorn --workers 4 --bind 127.0.0.1:8000 app:app
Restart=always
RestartSec=5
Environment="PATH=/var/www/myapp/venv/bin"

[Install]
WantedBy=multi-user.target
sudo systemctl enable --now myapp

Nginx Configuration

server {
    listen 80;
    server_name example.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;
    }

    location /static {
        alias /var/www/myapp/static;
        expires 30d;
    }
}

Was this article helpful?