Python28 min read
Python Deployment
Deploy Python apps the right way: lock dependencies, run with a production server, use environment variables, add health checks, and keep releases stable.
David Miller
August 26, 2025
9.1k229
Deployment means running your Python app reliably on a server so real users can use it.
This lesson focuses on practical deployment habits:
- stable installs
- production servers
- environment-based configuration
- monitoring basics
## Step 1: Requirements file
```bash
pip freeze > requirements.txt
pip install -r requirements.txt
```
Purpose:
- repeatable installs
- same versions on dev and production
## Step 2: Production server (Gunicorn for Flask)
```bash
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 app:app
```
Why:
- Flask dev server is not designed for production traffic
## Step 3: Docker (portable deployment)
```dockerfile
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
CMD ["gunicorn", "-b", "0.0.0.0:8000", "app:app"]
```
```bash
docker build -t myapp .
docker run -p 8000:8000 myapp
```
Benefit:
- same behavior on every machine
## Step 4: Configuration by environment
```python
import os
class Config:
DEBUG = False
DATABASE_URI = os.getenv("DATABASE_URI")
```
Never hardcode secrets, use env vars.
## Step 5: Systemd service (Linux server)
```ini
[Unit]
Description=My Python App
After=network.target
[Service]
User=www-data
WorkingDirectory=/var/www/myapp
Environment="PATH=/var/www/myapp/venv/bin"
ExecStart=/var/www/myapp/venv/bin/gunicorn -w 4 app:app
[Install]
WantedBy=multi-user.target
```
This keeps your app running after reboot.
## Step 6: Health check endpoint
```python
from flask import Flask
app = Flask(__name__)
@app.route("/health")
def health():
return {"status": "healthy"}, 200
```
This helps monitoring tools verify the app is alive.
## Graph: deployment pipeline
```mermaid
flowchart LR
A[Code] --> B[requirements.txt]
B --> C[Build Docker / Setup server]
C --> D[Run gunicorn]
D --> E[Health check + logs]
E --> F[Stable production app]
```
## Remember
- Use a real server (gunicorn/uvicorn) for production
- Keep secrets in environment variables
- Add health checks and logs
- Docker makes deployment consistent
> Congratulations! You've completed all Python tutorials from beginner to advanced!
#Python#Advanced#Deployment