Installing Python packages system-wide leads to version conflicts between projects. Virtual environments give each project its own isolated set of dependencies.

Create and activate a venv

sudo apt install python3-venv -y
cd /var/www/myapp
python3 -m venv venv
source venv/bin/activate

Your prompt now shows (venv). Anything you pip install stays inside this folder.

Install dependencies

pip install -r requirements.txt
pip freeze > requirements.txt   # record exact versions

Using it with systemd

You don't need to "activate" the venv in a service file — just point ExecStart at the venv's interpreter:

ExecStart=/var/www/myapp/venv/bin/gunicorn myapp:app

Tips

  • Keep the venv/ folder out of version control (add it to .gitignore).
  • Recreate it on the server from requirements.txt rather than copying it.
  • One venv per project keeps everything clean and reproducible.