57.12 Project 12: Jupyter Lab and a FastAPI model server (CPU, then GPU)
Friends, today we run Jupyter Lab in Docker, train a small delivery-time model, save it on a shared volume, and serve predictions with FastAPI. The same Compose file can later request a GPU. Type every command yourself.
मित्रांनो, आज आपण Docker मध्ये Jupyter Lab चालवू, छोटी delivery-time model train करू, shared volume वर save करू, आणि FastAPI ने predictions serve करू. तोच Compose file नंतर GPU मागू शकतो. प्रत्येक command स्वतः टाइप करा.
दोस्तों, आज हम Docker में Jupyter Lab चलाएंगे, छोटी delivery-time model train करेंगे, shared volume पर save करेंगे, और FastAPI से predictions serve करेंगे. वही Compose file बाद में GPU मांग सकती है. हर command खुद टाइप कीजिए.
What you will learn in this lesson
- Why notebooks and model servers share a volume.
- How Jupyter Lab runs with a token in Docker.
- How FastAPI loads a pinned scikit-learn model.
- How to retrain and restart only the server.
- How GPU passthrough looks in Compose.
1. Start from a real problem
Suppose we work in the data team at Swiggy and we must predict how many minutes a food delivery will take.
Data scientists love Jupyter. Backend engineers want a stable HTTP API. Both need the same model file.
With Docker we run Jupyter and a FastAPI server that share a named volume at /models. Flipkart and Zomato ML teams use the same split.
2. Project layout
Step 1: Folders and pinned deps
Why: Same versions train and serve.
What: Pin scikit-learn and joblib so the notebook and the server never disagree.
Example 1: Make folders
Type this:
mkdir -p ml-serve/server ml-serve/notebooks && cd ml-serve && pwd
You will see:
/home/you/ml-serve
What it means: Project root ready.
Example 2: Write requirements.txt
Type this:
printf '%s\n' 'fastapi==0.115.0' 'uvicorn[standard]==0.30.6' 'scikit-learn==1.5.2' 'joblib==1.4.2' 'numpy==2.1.1' 'pandas==2.2.2' > requirements.txt && wc -l requirements.txt
You will see:
6 requirements.txt
What it means: Pinned train and serve stack.
Example 3: Show pins
Type this:
grep scikit requirements.txt
You will see:
scikit-learn==1.5.2
What it means: Exact version for both containers.
Step 2: FastAPI model server
Why: Load once, predict many times.
What: server/main.py loads /models/model.joblib at startup. /predict accepts distance_km and prep_minutes.
Example 4: Write server/main.py
Type this:
printf '%s\n' 'import os' 'from fastapi import FastAPI' 'from pydantic import BaseModel' 'import joblib' '' 'app = FastAPI(title="Delivery time model")' 'MODEL = joblib.load(os.environ.get("MODEL_PATH", "/models/model.joblib"))' '' 'class Feat(BaseModel):' ' distance_km: float' ' prep_minutes: float' '' '@app.get("/healthz")' 'def health():' ' return {"ok": True, "model": type(MODEL).__name__}' '' '@app.post("/predict")' 'def predict(f: Feat):' ' y = MODEL.predict([[f.distance_km, f.prep_minutes]])[0]' ' return {"eta_minutes": float(y)}' > server/main.py && wc -l server/main.py
You will see:
16 server/main.py
What it means: Health and predict routes.
Example 5: Show model path
Type this:
grep MODEL_PATH server/main.py
You will see:
MODEL = joblib.load(os.environ.get("MODEL_PATH", "/models/model.joblib"))
What it means: Default path is the shared volume.
Example 6: Write server Dockerfile
Type this:
printf '%s\n' 'FROM python:3.12-slim' 'WORKDIR /app' 'COPY requirements.txt .' 'RUN pip install --no-cache-dir -r requirements.txt' 'COPY server/main.py .' 'ENV MODEL_PATH=/models/model.joblib' 'EXPOSE 8000' 'CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]' > server/Dockerfile && wc -l server/Dockerfile
You will see:
8 server/Dockerfile
What it means: Slim image; model comes from the volume.
3. Jupyter and first model
Step 3: Jupyter in Compose
Why: Token login, notebooks on a volume.
What: Use the official jupyter/scipy-notebook image. Mount notebooks/ and the shared models volume.
Example 7: Write compose.yaml
Type this:
printf '%s\n' 'name: mlserve' 'services:' ' jupyter:' ' image: quay.io/jupyter/scipy-notebook:2024-10-07' ' ports: ["127.0.0.1:8888:8888"]' ' environment:' ' JUPYTER_TOKEN: lab-token' ' volumes:' ' - ./notebooks:/home/jovyan/work' ' - models:/models' ' user: root' ' command: start-notebook.sh --ServerApp.token=lab-token' '' ' api:' ' build: ./server' ' ports: ["8000:8000"]' ' volumes: [models:/models:ro]' ' depends_on: [jupyter]' '' 'volumes: {models:}' > compose.yaml && wc -l compose.yaml
You will see:
22 compose.yaml
What it means: Jupyter and API share models.
Example 8: Start Jupyter only first
Type this:
docker compose up -d jupyter
sleep 5
curl -s -o /dev/null -w '%{http_code}\n' 'http://127.0.0.1:8888/lab?token=lab-token'
You will see:
302
What it means: Lab redirects into the UI with the token.
Example 9: Show token in compose
Type this:
grep JUPYTER_TOKEN compose.yaml
You will see:
JUPYTER_TOKEN: lab-token
What it means: Classroom token; change it on a shared VM.
Step 4: Train inside the notebook container
Why: Write model.joblib to /models.
What: A one-shot python command trains a tiny linear model so we do not need to click cells for the lesson.
Example 10: Train script via exec
Type this:
docker compose exec jupyter python - <<'PY'
import joblib, numpy as np
from sklearn.linear_model import LinearRegression
X = np.array([[1,10],[2,15],[5,20],[8,25],[3,12]], float)
y = np.array([25,35,55,75,32], float)
m = LinearRegression().fit(X,y)
joblib.dump(m, '/models/model.joblib')
print('saved', type(m).__name__, 'coef', m.coef_.tolist())
PY
You will see:
saved LinearRegression coef [5.0, 1.0]
What it means: Model written to the shared volume.
Example 11: List /models
Type this:
docker compose exec jupyter ls -l /models
You will see:
-rw-r--r-- 1 root root ... model.joblib
What it means: File visible inside Jupyter.
Example 12: Same file from a busybox mount
Type this:
docker run --rm -v mlserve_models:/models busybox ls -l /models
You will see:
-rw-r--r-- 1 root root ... model.joblib
What it means: Volume name mlserve_models holds the file.
4. Serve predictions
Step 5: Start API and predict
Why: Read-only mount of models.
What: The API mounts models as :ro so a bug cannot delete the file. Restart after retrain.
Example 13: Start API
Type this:
docker compose up -d --build api
sleep 3
curl -s http://localhost:8000/healthz
You will see:
{"ok":true,"model":"LinearRegression"}
What it means: Server loaded the joblib.
Example 14: Predict
Type this:
curl -s -X POST http://localhost:8000/predict -H 'Content-Type: application/json' -d '{"distance_km":4,"prep_minutes":18}'
You will see:
{"eta_minutes":38.0}
What it means: 45 + 181 roughly matches the toy coef.
Example 15: Bad payload
Type this:
curl -s -o /dev/null -w '%{http_code}\n' -X POST http://localhost:8000/predict -H 'Content-Type: application/json' -d '{}'
You will see:
422
What it means: Pydantic rejects missing fields.
Step 6: Retrain and reload
Why: Only restart the server.
What: Write a new model, restart api, health still works. Jupyter stays up.
Example 16: Retrain with new data
Type this:
docker compose exec jupyter python -c "import joblib,numpy as np; from sklearn.linear_model import LinearRegression; X=np.array([[1.,10],[2,15],[5,20],[8,25],[3,12],[6,22]]); y=np.array([24.,34,54,74,31,60.]); joblib.dump(LinearRegression().fit(X,y),'/models/model.joblib'); print('retrained')"
You will see:
retrained
What it means: New bytes on the volume.
Example 17: Restart only API
Type this:
docker compose restart api && sleep 2 && curl -s http://localhost:8000/healthz
You will see:
{"ok":true,"model":"LinearRegression"}
What it means: Process reloaded the file.
Example 18: Jupyter still up
Type this:
docker compose ps --format '{{.Name}} {{.Status}}' | grep jupyter
You will see:
mlserve-jupyter-1 Up
What it means: Notebook session kept.
5. GPU note, mistakes and clean up
Step 7: GPU passthrough shape
Why: Optional for CUDA hosts.
What: On a machine with the NVIDIA Container Toolkit you add a deploy reservation. The classroom CPU path stays the default.
Example 19: Show GPU snippet
Type this:
printf '%s\n' 'deploy:' ' resources:' ' reservations:' ' devices:' ' - driver: nvidia' ' count: 1' ' capabilities: [gpu]' > gpu-snippet.yaml && cat gpu-snippet.yaml
You will see:
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
What it means: Compose GPU reservation block.
Example 20: CPU works without GPU
Type this:
curl -s http://localhost:8000/healthz
You will see:
{"ok":true,"model":"LinearRegression"}
What it means: No GPU required for this linear model.
Example 21: When to use GPU
Type this:
echo 'Neural nets and large batch scoring need the NVIDIA toolkit and a CUDA image'
You will see:
Neural nets and large batch scoring need the NVIDIA toolkit and a CUDA image
What it means: Keep CPU images for small sklearn models.
Step 8: Common mistakes
Why: Version drift and writable mounts.
What: Training with sklearn 1.4 and serving with 1.5 can fail to unpickle. Mounting models as read-write in the API invites accidents.
Example 22: Pinned in one file
Type this:
wc -l requirements.txt && grep scikit requirements.txt
You will see:
6 requirements.txt
scikit-learn==1.5.2
What it means: One pin list for both images.
Example 23: API mount is read-only
Type this:
grep 'models:/models' compose.yaml
You will see:
- models:/models
volumes: [models:/models:ro]
What it means: Jupyter writes; API only reads.
Example 24: Token not on 0.0.0.0 public
Type this:
grep '127.0.0.1:8888' compose.yaml
You will see:
ports: ["127.0.0.1:8888:8888"]
What it means: Lab UI on loopback only.
Step 9: Clean up
Why: Stop the stack and remove the volume.
What: down -v deletes model.joblib with the volume. Export it first if you need it.
Example 25: Export model
Type this:
docker run --rm -v mlserve_models:/models -v "$PWD":/out busybox cp /models/model.joblib /out/model.joblib && ls -l model.joblib
You will see:
-rw-r--r-- 1 root root ... model.joblib
What it means: Copy kept on the host.
Example 26: Stop stack
Type this:
docker compose down -v
You will see:
... Removed
What it means: Containers and models volume gone.
Example 27: Remove image
Type this:
docker image rm mlserve-api 2>/dev/null; echo done
You will see:
done
What it means: Build cache image removed.
Step 10: Health before traffic
Why: Predict only after load.
What: If model.joblib is missing the API crashes on start. Train first, then start api, then curl /healthz.
Example 28: Order of operations
Type this:
echo '1 train in jupyter 2 start api 3 curl /healthz 4 curl /predict'
You will see:
1 train in jupyter 2 start api 3 curl /healthz 4 curl /predict
What it means: Missing file means restart loop.
Example 29: Depends_on is not enough
Type this:
grep depends_on compose.yaml
You will see:
depends_on: [jupyter]
What it means: depends_on waits for start, not for model.joblib.
Example 30: Fail if file missing
Type this:
docker run --rm -v mlserve_models:/models:ro busybox ls /models/model.joblib 2>&1 | head -1
You will see:
ls: /models/model.joblib: No such file or directory
What it means: After down -v the file is gone. Train again next time.
Step 11: Load test a few predictions
Why: See latency on CPU.
What: A tiny bash loop posts many /predict calls. Swiggy load tests do the same before a release.
Example 31: Fifty requests
Type this:
for i in $(seq 1 50); do curl -s -o /dev/null -w '%{http_code} ' -X POST http://localhost:8000/predict -H 'Content-Type: application/json' -d '{"distance_km":3,"prep_minutes":15}'; done; echo
You will see:
200 200 200 ... 200
What it means: All fifty returned 200.
Example 32: One timed call
Type this:
curl -s -o /dev/null -w 'time_total=%{time_total}\n' -X POST http://localhost:8000/predict -H 'Content-Type: application/json' -d '{"distance_km":3,"prep_minutes":15}'
You will see:
time_total=0.012
What it means: Milliseconds on CPU for linear models.
Example 33: Server logs show posts
Type this:
docker compose logs api 2>&1 | grep POST | tail -2
You will see:
INFO: ... "POST /predict HTTP/1.1" 200 OK
What it means: Uvicorn access log confirms traffic.
Step 12: Separate train and serve images
Why: Why two containers.
What: Jupyter images are large and include many libraries. The API image stays slim with only serving deps. Companies keep them apart so production nodes do not pull a one-gigabyte notebook image.
Example 34: Compare image names
Type this:
docker compose images
You will see:
jupyter quay.io/jupyter/scipy-notebook:...
api mlserve-api
What it means: Two different images.
Example 35: API has no Jupyter
Type this:
docker compose exec api which jupyter 2>&1 | head -1
You will see:
... not found
What it means: Serve image has no notebook server.
Example 36: Why :ro on API volume
Type this:
grep ':ro' compose.yaml
You will see:
volumes: [models:/models:ro]
What it means: Production scorers should not write training artifacts.
Ravindra Bagale's Tip
Pin the same scikit-learn in the notebook and the server. Swiggy and Zomato ML teams lose hours when pickle versions drift.
Notebook आणि server मध्ये तोच scikit-learn pin करा. Pickle versions drift झाले की Swiggy आणि Zomato ML teams तास गमावतात.
Notebook और server में वही scikit-learn pin करें. Pickle versions drift होने पर Swiggy और Zomato ML teams घंटे गंवाती हैं.
Check yourself
Q1. Why share a models volume?
So the notebook can write model.joblib and the API can read the same file.
Q2. Where should Jupyter listen in a lab?
On 127.0.0.1 with a token.
Q3. How do you reload a new model?
Write a new joblib and restart only the API container.
Q4. Why pin scikit-learn?
So train and serve unpickle with the same version.
Q5. Why mount models read-only in the API?
So a bug in the server cannot delete the model file.
Q6. When do you need the GPU block?
For CUDA neural nets on a host with the NVIDIA toolkit.
Friends, you trained a model in Jupyter, served it with FastAPI from a shared volume, retrained, and restarted only the API. Did you understand? Let us try it once more. If not, look at Pictures 1 and 2 and repeat the train then predict steps. Next project: LAMP stack with Apache, PHP and MySQL.
मित्रांनो, आज तुम्ही Jupyter मध्ये model train केली, shared volume वरून FastAPI ने serve केली, पुन्हा train करून फक्त API restart केली. नसेल तर Picture 1 आणि 2 बघा आणि train-predict पावले पुन्हा करा. पुढचा project: Apache, PHP आणि MySQL सह LAMP stack.
दोस्तों, आज आपने Jupyter में model train की, shared volume से FastAPI से serve की, फिर train कर सिर्फ API restart की. नहीं तो Picture 1 और 2 देखिए और train-predict कदम दोहराइए. अगला project: Apache, PHP और MySQL के साथ LAMP stack.
Lab: try at home
- Create ml-serve with pinned requirements.
- Write the FastAPI server and Dockerfile.
- Start Jupyter on 127.0.0.1:8888 with a token.
- Train LinearRegression into /models/model.joblib.
- Start the API and call /predict.
- Retrain and restart only the API.
- Export the model and clean up.
Recap
- Notebooks train; APIs serve.
- Share models on a named volume.
- Pin sklearn on both sides.
- Restart API after retrain.
- Bind Jupyter to loopback.
- GPU is optional for small models.
Revision card
Interview card