The Problem: Why Local ComfyUI Falls Short in Production
Six months ago, our engineering team needed a reliable pipeline to generate custom marketing visuals and short product clips on demand. Like most developers, I started by running ComfyUI on a local workstation. It worked well for manual testing. The moment we wired it to a production backend, though, things fell apart.
Bare-metal Python virtual environments are fragile. One custom node update can silently break PyTorch or CUDA compatibility and take your entire pipeline offline. Clicking through a browser node graph also hits a wall when you need 200 localized ad banners before 9 a.m.
We needed isolated, reproducible containers and a clean programmatic interface. Moving ComfyUI into Docker with GPU passthrough solved the environment drift. Driving it through its REST API gave us automation. Six months later, here is what held up in production—and what caught us off guard.
Core Concepts: Docker GPU Passthrough and Headless ComfyUI
Before writing a single config file, you need to understand two things: how Docker accesses your GPU and how ComfyUI actually talks to its UI.
Docker containers cannot see your host graphics card out of the box. You might be tempted to install full NVIDIA drivers inside the container image, but that bloats the build and locks it to a specific host kernel. Instead, use the NVIDIA Container Toolkit. It mounts the host driver and CUDA libraries into the container at runtime. Your image only needs the CUDA runtime that PyTorch expects, while the host manages the hardware.
ComfyUI’s web interface is also simpler than it looks—it is just a thin client. Every time you click “Queue Prompt,” the browser serializes your node graph into JSON and posts it to a local HTTP server on port 8188. That same server exposes REST endpoints for submitting jobs, checking queue status, reading history, and downloading finished images or MP4s. Once you treat ComfyUI as a headless HTTP service, integrating it into any backend stack becomes straightforward.
After six months of production logs, three habits saved us the most headaches:
- Mount your models externally: Never bake a 6.5 GB SDXL checkpoint, a 23 GB Flux.1-dev model, or 1.8 GB AnimateDiff motion modules into your Docker image. Mount
models/andoutput/from the host or shared network storage. - Pin your base image tags: Lock your CUDA and PyTorch versions in the Dockerfile. Pulling
lateston container restart will eventually break a custom node. - Tune VRAM flags per workload: Video pipelines eat far more memory than static images. An SDXL 1024×1024 render fits in 8–10 GB of VRAM, while a 16-frame AnimateDiff clip with ControlNet can spike past 16 GB. Flags like
--normalvramor--lowvramlet you trade a bit of speed for stability.
Hands-On Practice: Containerizing ComfyUI and Automating via REST API
Here is the stripped-down setup we run on Ubuntu 22.04 servers with NVIDIA RTX 4090 and L4 GPUs.
Step 1: Verify Host GPU Support and Create the Compose File
Confirm that your host sees the GPU and that the NVIDIA Container Toolkit is working:
nvidia-smi
docker run --rm --gpus all nvidia/cuda:12.1.1-base-ubuntu22.04 nvidia-smi
If both commands print your GPU table, passthrough is ready. Next, create a Dockerfile that pins PyTorch and CUDA:
FROM pytorch/pytorch:2.3.1-cuda12.1-cudnn8-runtime
WORKDIR /app
RUN apt-get update && apt-get install -y git ffmpeg libgl1 && rm -rf /var/lib/apt/lists/*
RUN git clone https://github.com/comfyanonymous/ComfyUI.git /app/ComfyUI
WORKDIR /app/ComfyUI
RUN pip install --no-cache-dir -r requirements.txt
EXPOSE 8188
CMD ["python", "main.py", "--listen", "0.0.0.0", "--port", "8188"]
We include ffmpeg in the image because video nodes like VideoHelperSuite rely on it to encode MP4 and WebM files. Next, configure docker-compose.yml with GPU reservations and persistent volumes:
services:
comfyui:
build: .
container_name: comfyui-api
restart: unless-stopped
ports:
- "8188:8188"
volumes:
- ./models:/app/ComfyUI/models
- ./output:/app/ComfyUI/output
- ./custom_nodes:/app/ComfyUI/custom_nodes
deploy:
resources:
reservations:
devices:
- driver: nvidia
count: 1
capabilities: [gpu]
Run docker compose up -d --build to launch the container. Your headless ComfyUI server is now listening on port 8188.
Step 2: Export Your Workflow in API Format
Standard UI workflow files will not work with the REST API. Open ComfyUI in your browser once at http://your-server-ip:8188, click the gear icon for Settings, and toggle on Enable Dev mode Options. A new Save (API Format) button will appear in the menu.
Build your image (e.g., Flux or SDXL) or video (e.g., AnimateDiff or Stable Video Diffusion) graph and run a test render. Once it looks right, export it as workflow_api.json. Each node is keyed by a numeric string ID, so your code can swap prompts, seeds, or frame counts in seconds.
Step 3: Trigger Generation via Python
With workflow_api.json exported, any backend can drive ComfyUI over HTTP. The Python script below injects a prompt and seed, submits the job, polls for completion, and saves the output:
import json
import time
import uuid
import requests
COMFY_URL = "http://localhost:8188"
CLIENT_ID = str(uuid.uuid4())
with open("workflow_api.json", "r") as f:
workflow = json.load(f)
# Update prompt text and random seed (replace "6" and "3" with your actual node IDs)
workflow["6"]["inputs"]["text"] = "cinematic shot of a minimalist tech desk, soft morning light"
workflow["3"]["inputs"]["seed"] = int(time.time())
# 1. Queue the workflow
payload = {"prompt": workflow, "client_id": CLIENT_ID}
res = requests.post(f"{COMFY_URL}/prompt", json=payload, timeout=10)
res.raise_for_status()
prompt_id = res.json()["prompt_id"]
print(f"Queued job: {prompt_id}")
# 2. Poll the /history endpoint until the job finishes
while True:
history_res = requests.get(f"{COMFY_URL}/history/{prompt_id}", timeout=10)
history_res.raise_for_status()
history_data = history_res.json()
if prompt_id in history_data:
outputs = history_data[prompt_id]["outputs"]
break
time.sleep(2)
# 3. Download generated images or videos
for node_id, node_output in outputs.items():
media_items = node_output.get("images", []) + node_output.get("gifs", [])
for item in media_items:
params = {
"filename": item["filename"],
"subfolder": item["subfolder"],
"type": item["type"],
}
file_res = requests.get(f"{COMFY_URL}/view", params=params, timeout=30)
file_res.raise_for_status()
with open(item["filename"], "wb") as out_file:
out_file.write(file_res.content)
print(f"Saved output: {item['filename']}")
Checking both images and gifs is a useful trick here. Video nodes like VideoHelperSuite return MP4 and WebM files under the gifs key, so one loop handles both static images and video clips.
Wrapping Up: Six Months in Production — Is It Worth It?
Half a year in, containerized ComfyUI has earned its keep in our stack—as long as you plan around two operational limits.
The biggest win was killing dependency drift. Deploying to a new GPU node now takes one docker compose up command. Because everything runs behind a predictable REST API, our web app treats AI rendering like any other microservice. When traffic spikes, we spin up a second container on another GPU host behind a load balancer.
Two caveats still require planning. PyTorch and CUDA base images weigh around 6–8 GB, so keep your CI/CD registry pruned and cache layers aggressively.
More importantly, ComfyUI executes jobs sequentially on a single GPU. If a 1024×1024 Flux render takes 12 seconds and 20 users hit your endpoint at once, the last request waits four minutes—well past a standard 30-second HTTP timeout. Put Redis or RabbitMQ in front of ComfyUI, pull jobs with worker scripts, and fire a webhook when the render finishes.
If fragile local Python setups are slowing down your AI media work, give this architecture an afternoon. Once it is running, you get full programmatic control without babysitting environments.

