Python Virtual Environments auf VPS: venv richtig nutzen
Python Virtual Environments (venv) isolieren Dependencies.
Python Virtual Environments (venv) isolieren Dependencies. Projekt A nutzt Django 4, Projekt B Django 3 – kein Problem mit venv.
Warum venv?
Ohne venv: Alle Packages global installiert. Verschiedene Projekte können sich in die Quere kommen.
Mit venv: Jedes Projekt hat eigenen Ordner für Dependencies. Sauber getrennt.
Python & venv installieren
sudo apt update
sudo apt install python3 python3-venv python3-pip
# Version checken:
python3 --version
Virtual Environment erstellen
# Im Projekt-Ordner:
cd /var/www/myproject
python3 -m venv venv
# Erstellt Ordner 'venv' mit Python-Kopie
venv aktivieren
# Aktivieren:
source venv/bin/activate
# Prompt ändert sich:
(venv) user@vps:~/myproject$
# Deaktivieren:
deactivate
Packages installieren
# venv aktiviert:
pip install django flask requests
# Dependencies exportieren:
pip freeze > requirements.txt
# Auf anderem Server installieren:
pip install -r requirements.txt
Python-App als Service (systemd)
Damit deine App nach Reboot automatisch startet:
sudo nano /etc/systemd/system/myapp.service
# Inhalt:
[Unit]
Description=My Python App
After=network.target
[Service]
User=www-data
WorkingDirectory=/var/www/myproject
Environment="PATH=/var/www/myproject/venv/bin"
ExecStart=/var/www/myproject/venv/bin/python app.py
Restart=always
[Install]
WantedBy=multi-user.target
# Aktivieren:
sudo systemctl enable myapp
sudo systemctl start myapp
sudo systemctl status myapp
Fazit
venv ist essentiell für sauberes Python-Deployment. Jedes Projekt isoliert, keine Konflikte.
Falls du noch keinen VPS hast: aktuelle Codes für Netcup VPS und Rootserver gibt es bei HostDealHero.