惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Application and Cybersecurity Blog
Application and Cybersecurity Blog
A
About on SuperTechFans
S
SegmentFault 最新的问题
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Help Net Security
Help Net Security
有赞技术团队
有赞技术团队
博客园 - 【当耐特】
O
OpenAI News
美团技术团队
月光博客
月光博客
Apple Machine Learning Research
Apple Machine Learning Research
Schneier on Security
Schneier on Security
Webroot Blog
Webroot Blog
Cyberwarzone
Cyberwarzone
Hacker News - Newest:
Hacker News - Newest: "LLM"
Google Online Security Blog
Google Online Security Blog
T
Tenable Blog
S
Security Affairs
博客园_首页
S
Schneier on Security
Security Latest
Security Latest
T
Threat Research - Cisco Blogs
T
Tailwind CSS Blog
大猫的无限游戏
大猫的无限游戏
Spread Privacy
Spread Privacy
量子位
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
K
Kaspersky official blog
Hugging Face - Blog
Hugging Face - Blog
TaoSecurity Blog
TaoSecurity Blog
博客园 - 聂微东
Vercel News
Vercel News
M
MIT News - Artificial intelligence
T
Troy Hunt's Blog
B
Blog
MongoDB | Blog
MongoDB | Blog
Martin Fowler
Martin Fowler
Attack and Defense Labs
Attack and Defense Labs
L
LINUX DO - 最新话题
D
DataBreaches.Net
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Stack Overflow Blog
Stack Overflow Blog
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
博客园 - Franky
W
WeLiveSecurity
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
F
Fortinet All Blogs
www.infosecurity-magazine.com
www.infosecurity-magazine.com
C
Check Point Blog
H
Hacker News: Front Page

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
From Chaos to Consistency: Docker for Modern AI Workflows
Sachin Singh · 2026-06-19 · via DEV Community

You trained the model. The notebook runs. The demo works. You push it to a teammate, and forty minutes later you get the message every engineer dreads:

"Hey, I'm getting a CUDA error. And torch won't import. And what version of Python is this?"

And you say the six words that have haunted software since the dawn of time:

"But it works on my machine."

Here's the uncomfortable truth: "it works on my machine" isn't a defense. It's a confession. It means your code depends on something living on your laptop that you never wrote down a Python version, a system library, a CUDA toolkit, a stray environment variable, a model file sitting in ~/Downloads.

Docker is how you stop making that confession. Let's fix this.

The real problem: AI projects are dependency monsters

A typical web app has a handful of dependencies. An AI project has layers of them, and each layer can betray you:

  • Python packages : torch, transformers, numpy, and the version conflicts between them.
  • System libraries : things like libgl1 or ffmpeg that pip won't install for you.
  • The CUDA / driver stack : the single most common reason "it works on my machine" and nowhere else.
  • The model weights themselves : multi-gigabyte files that aren't in your repo.
  • Python itself : 3.10 on your laptop, 3.12 on the server, subtle breakage everywhere.

requirements.txt captures one of those five layers. Docker captures all of them. That's the whole pitch.

What Docker actually is?

Forget the whale logo and the buzzwords for a second.

A Docker image is a frozen snapshot of a complete computer: the operating system, Python, your packages, your code, and your config, all baked into one file. A container is a running copy of that snapshot.

The mental model that makes it click: a virtual machine simulates an entire computer including its own operating system kernel, which is heavy and slow. A container shares your machine's kernel and only packages everything above it. So it boots in seconds, not minutes, and a single image runs identically on your laptop, your teammate's laptop, and a cloud GPU server.

You write the recipe once. Everyone gets the exact same kitchen.

Your first Dockerfile for a PyTorch project

A Dockerfile is just that recipe, a plain text file of instructions. Here's a real one for a PyTorch project, with every line explained:

# Start from an official Python image. The "-slim" variant is smaller.
FROM python:3.11-slim

# Install system libraries that pip can't. Many vision/audio
# libraries need these, and forgetting them is a classic
# "works on my machine" trap.
RUN apt-get update && apt-get install -y --no-install-recommends \
    build-essential \
    libgl1 \
    && rm -rf /var/lib/apt/lists/*

# Set the working directory inside the container.
WORKDIR /app

# Copy ONLY requirements first, then install.
# This is a caching trick, see the note below.
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Now copy the rest of your code.
COPY . .

# The command that runs when the container starts.
CMD ["python", "predict.py"]

Two beginner mistakes this avoids:

1. Pin your versions. Your requirements.txt should look like this, not just bare package names:

torch==2.3.1
transformers==4.41.2
fastapi==0.111.0
uvicorn==0.30.1
numpy==1.26.4

torch without a version is a future outage waiting to happen. The whole point of Docker is reproducibility, don't undermine it by letting versions float.

2. Copy requirements.txt before your code. Docker builds in layers and caches each one. If you copy everything at once, changing a single line of code forces it to reinstall torch (a multi-minute download) every single build. By copying requirements first, Docker reuses the cached install layer and only re-runs steps that actually changed. Your build goes from minutes to seconds.

To build and run it:

docker build -t my-model .
docker run my-model

That -t my-model just names the image. The . tells Docker to look for the Dockerfile in the current folder. That's it, you now have a portable, reproducible model.

Don't bake your model weights into the image

Beginners often COPY model.bin straight into the image. Don't. A 5GB image is painful to build, push, and pull, and you'll rebuild it every time the weights change.

Instead, keep large files outside the image and mount them at runtime with a volume, a shared folder between your machine and the container:

docker run -v $(pwd)/models:/app/models my-model

This maps your local models/ folder to /app/models inside the container. The weights live on disk, the image stays lean, and you can swap models without rebuilding anything.

Serving a model as an API

Most of the time you don't just want to run a script, you want a model behind an endpoint your app can call. Here's a minimal FastAPI server, app.py:

from fastapi import FastAPI
from pydantic import BaseModel
import torch

app = FastAPI()

# Load the model ONCE at startup, not on every request.
# This is the single biggest performance mistake beginners make.
model = torch.load("/app/models/model.pt", map_location="cpu")
model.eval()

class Request(BaseModel):
    text: str

@app.post("/predict")
def predict(req: Request):
    with torch.no_grad():
        result = model(req.text)
    return {"prediction": result}

@app.get("/health")
def health():
    return {"status": "ok"}

Notice the model loads once when the server boots, not inside predict(). Loading weights on every request will make your API crawl, a mistake that's easy to miss until production traffic hits.

Now adjust the Dockerfile's last line to launch the server instead of a script:

CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]

That --host 0.0.0.0 matters. Inside a container, the default 127.0.0.1 means "only reachable from inside this container", your requests from outside would bounce. Binding to 0.0.0.0 makes it reachable. Then map the port when you run it:

docker run -p 8000:8000 -v $(pwd)/models:/app/models my-model

-p 8000:8000 connects port 8000 on your machine to 8000 in the container. Hit http://localhost:8000/predict and you're serving a model from a container.

When one container isn't enough: docker-compose

Real AI apps rarely run alone. You've got your model API, plus maybe a Redis cache for results and a vector database for embeddings. Starting three containers by hand, with the right flags and in the right order, gets old fast.

docker-compose lets you define your whole stack in one docker-compose.yml file:

services:
  model-api:
    build: .
    ports:
      - "8000:8000"
    volumes:
      - ./models:/app/models
    depends_on:
      - redis

  redis:
    image: redis:7-alpine
    ports:
      - "6379:6379"

  vector-db:
    image: qdrant/qdrant:latest
    ports:
      - "6333:6333"
    volumes:
      - ./qdrant_data:/qdrant/storage

Then the entire stack starts with one command:

docker compose up

One command, three services, wired together and talking to each other. And because services can reach each other by name, your API connects to Redis at the host redis:6379, no IP addresses to chase down. Shut it all down with docker compose down. This is the moment most people fall in love with Docker.

A few habits that separate pros from beginners

A short list of things worth doing from day one:

  • Add a .dockerignore file. Just like .gitignore, it keeps junk out of your image. At minimum: __pycache__, .git, venv, *.pt, and data/. Without it, you'll accidentally copy gigabytes of cache and datasets into your build.
  • Use -slim or official ML base images. python:3.11-slim over the full image saves hundreds of megabytes. For GPU work, start from an official CUDA-enabled base like pytorch/pytorch so the driver stack is handled for you.
  • One process per container. Resist the urge to cram your API, database, and worker into one container. Split them, that's exactly what compose is for.
  • Never bake secrets into images. API keys and tokens go in environment variables (-e MY_KEY=... or an .env file), never hardcoded into the Dockerfile. Anyone with the image can read what's baked in.

The payoff

Go back to that teammate who couldn't run your model. With Docker, the entire conversation becomes:

git clone your-repo
docker compose up

Two commands. Same Python, same CUDA, same packages, same everything on their laptop, on the cloud GPU, on the production server. No "what version are you on?" No "did you install ffmpeg?" No 40-minute debugging session.

You don't need to master Kubernetes or become a DevOps engineer to get this. You just need a Dockerfile, a pinned requirements.txt, and maybe a docker-compose.yml. Start with the PyTorch example above, get one model running in a container today, and build from there.

The next time someone asks if your project works on their machine, you'll already know the answer.

It works on every machine.


Found this useful? Drop a comment with the trickiest "works on my machine" bug you've hit