In modern network operations centers and remote edge sites, detecting security threats or hardware failures instantly is critical. Traditional cloud-based analysis often introduces too much latency to be effective at the edge. This guide walks you through building a self-contained, real-time anomaly detector using Python’s FastAPI framework and Docker. By containerizing your model, you ensure it runs consistently across different hardware configurations without dependency hell. This project covers the entire lifecycle: from data preprocessing in a Jupyter notebook to deploying a secure API endpoint that can monitor network traffic metrics like packet loss or CPU utilization on edge devices.
Project Architecture and Prerequisites
Before writing code, understand the architecture. You will build a microservice that accepts JSON payloads containing sensor readings or network logs, processes them against a pre-trained machine learning model, and returns an alert if an anomaly is detected. The system relies on Python 3.10+, Docker Engine, and a lightweight ML library like Scikit-learn for the classification logic.
Prerequisites Checklist:
* Python Environment: Install Python 3.10 or higher. Verify with python --version.
* Docker: Ensure Docker Desktop or Docker Engine is running on your host machine.
* Data Source: Prepare a CSV file named network_logs.csv containing columns: timestamp, cpu_load, memory_usage, and packet_rate.
* Tools: Install JupyterLab for data exploration and the fastapi, uvicorn, scikit-learn, and pandas libraries.
Step 1: Data Preprocessing and Model Training
The first phase involves cleaning raw network logs and training a classification model to distinguish between “normal” traffic patterns and “anomalous” spikes. This should ideally be done in a Jupyter Notebook before deployment.
Create a file named train_model.py. This script loads your CSV data, normalizes the features, and trains a Random Forest classifier.
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
# Load data
df = pd.read_csv('network_logs.csv')
# Select features for the model
features = ['cpu_load', 'memory_usage', 'packet_rate']
X = df[features]
y = df['label'] # Assume 0 is normal, 1 is anomaly in your dataset
# Split and scale data
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
scaler = StandardScaler()
X_train_scaled = scaler.fit_transform(X_train)
X_test_scaled = scaler.transform(X_test)
# Train model
model = RandomForestClassifier(n_estimators=100, random_state=42)
model.fit(X_train_scaled, y_train)
score = model.score(X_test_scaled, y_test)
print(f"Model Training Complete. Test Accuracy: {score:.2f}")
# Save the model and scaler for deployment
import joblib
joblib.dump(model, 'anomaly_model.pkl')
joblib.dump(scaler, 'scaler.pkl')
Expected Output: The console should print “Model Training Complete” followed by an accuracy score between 0.70 and 0.95 depending on your dataset quality. If you receive a ValueError regarding unknown columns, ensure your CSV headers match the code exactly.
Step 2: Building the FastAPI Application
With the model trained and saved, we construct the API server. This application will load the pre-trained artifacts upon startup and expose an endpoint for real-time inference. Create a file named main.py.
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import joblib
import numpy as np
app = FastAPI(title="Edge Anomaly Detector")
# Load models at startup
model = joblib.load('anomaly_model.pkl')
scaler = joblib.load('scaler.pkl')
class NetworkMetrics(BaseModel):
cpu_load: float
memory_usage: float
packet_rate: float
@app.post("/predict")
async def detect_anomaly(metrics: NetworkMetrics):
try:
# Prepare input data as a 2D array
input_data = np.array([[metrics.cpu_load, metrics.memory_usage, metrics.packet_rate]])
# Scale the input using the saved scaler
scaled_input = scaler.transform(input_data)
# Predict probability of anomaly
prediction = model.predict(scaled_input)[0]
probability = model.predict_proba(scaled_input)[0][1]
return {
"status": "alert" if prediction == 1 else "normal",
"anomaly_probability": round(probability, 4),
"message": "High anomaly detected!" if prediction == 1 else "Traffic patterns appear normal."
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
Verification Step: Run the script using python main.py. Once the server starts, open a terminal and run: curl -X POST http://localhost:8000/predict -H "Content-Type: application/json" -d '{"cpu_load": 95.0, "memory_usage": 80.0, "packet_rate": 1200}'. You should receive a JSON response indicating the status and probability.
Step 3: Containerization with Docker
To ensure this detector runs on any edge device (from a Raspberry Pi to an industrial gateway), we must containerize the application. Create a Dockerfile in the same directory as your Python files.
FROM python:3.10-slim
WORKDIR /app
# Install dependencies
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
# Copy application code
COPY train_model.py ./
COPY main.py ./
COPY network_logs.csv ./ # Include dummy data for testing if needed, or mount as volume
EXPOSE 8000
CMD ["python", "main.py"]
Create a requirements.txt file listing: fastapi, uvicorn[standard], scikit-learn, pandas, joblib, pydantic.
Build and run the container with these commands:
docker build -t edge-anomaly-detector .
docker run -p 8000:8000 --name anomaly-service edge-anomaly-detector
Common Errors: If you see “Permission denied” errors during pip install, ensure your user has write permissions to the Docker volume. If the container exits immediately, check logs with docker logs anomaly-service to see if a specific file is missing or if the model loading failed due to path issues.
Industry Application and Student Practice Task
Industry Scenario: A telecommunications provider deploys this container on edge routers at cell towers. The router sends CPU and packet loss metrics every second to this API. If the probability exceeds 0.8, the system triggers an automated ticket in their ITSM tool to investigate potential fiber cuts or hardware overheating before service degradation occurs.
Student Practice Task:
1. Modify main.py to add a new endpoint /health that returns the current system time and container uptime to verify liveness probes.
2. Simulate an attack by sending a JSON payload with cpu_load set to 100.0 repeatedly using a script or curl loop.
3. Document the latency between sending the request and receiving the response using Python’s time.time() function. Compare this local execution time against a hypothetical cloud API call to argue for edge deployment benefits.
By following these steps, you have built a robust, reproducible system capable of running in resource-constrained environments. Always verify your model’s performance on unseen data before deploying it to production networks, and remember to monitor the container logs regularly for drift or memory leaks.
Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.

