| | |

Cloudflare 15 ☁️ Cloudflare Containers — Running custom OCI/Docker workloads and heavy compute alongside edge Workers

⏱️ Estimated read: 13 min | |

Cloudflare Workers revolutionized edge computing by utilizing V8 isolates, a lightweight technology that allows thousands of snippets of code to run on a single machine with minimal overhead. However, V8 isolates have inherent limitations: they cannot run arbitrary binaries, they lack a traditional filesystem, and they are restricted to languages that can compile to WebAssembly or run in a JavaScript environment. Cloudflare Containers bridge this gap by allowing developers to package any OCI-compliant image—including those built with Docker—and deploy it directly onto Cloudflare’s global network. This enables the execution of heavy compute tasks, the use of legacy C++ or Python libraries, and the deployment of full applications that require a traditional Linux environment.

Unlike traditional cloud container services that often live in a single “region,” Cloudflare Containers are designed to be serverless and globally distributed. They integrate seamlessly with the existing Workers ecosystem, allowing a lightweight Worker to act as an intelligent entry point that routes traffic to a more robust Container when heavy lifting is required. This “Hybrid Edge” architecture ensures that the user-facing latency remains low while providing the raw power needed for tasks like image processing, video transcoding with FFmpeg, or running machine learning models that require specific OS-level dependencies.

This chapter explores the move from lightweight isolates to full OCI containers. We will examine the underlying architecture that allows these containers to spin up rapidly across the network, the workflow for building and pushing images to the Cloudflare Container Registry, and the networking patterns used to connect Workers to Containers via service bindings. We will also discuss resource allocation, cold start mitigation, and the specific use cases where a container is a superior choice over a standard Worker or a WebAssembly module.

Key point: Cloudflare Containers allow for the execution of full OCI/Docker images on the edge, providing a Linux-based environment for heavy compute and custom binaries that cannot run within the standard V8 isolate sandbox.


Why exists

The V8 sandbox limitation. V8 isolates are designed for speed and safety, but they achieve this by stripping away access to the underlying operating system. If a project requires a library that relies on specific Linux kernel features, shared C libraries, or non-Wasm binaries, it cannot run in a standard Worker. Containers provide a full Linux user-space, removing these architectural barriers.

The heavy compute requirement. Standard Workers are optimized for short-lived, low-memory tasks. While “Workers Unbound” increased these limits, many workloads—such as complex video rendering, large-scale data transformation, or scientific simulations—require gigabytes of RAM and multiple CPU cores. Containers allow developers to define specific resource profiles that exceed the capabilities of the isolate model.

The legacy lift-and-shift problem. Many organizations have existing applications packaged as Docker images that are too complex to rewrite for a serverless JavaScript environment. Cloudflare Containers allow these teams to migrate their existing workloads to the edge with minimal code changes, gaining the benefits of a global network without a total architectural overhaul.

The binary dependency bottleneck. Tools like FFmpeg, Pandoc, or specialized CLI utilities are difficult to port to WebAssembly or rewrite in JavaScript. By using a container, developers can simply include these binaries in their image and call them via standard shell commands, drastically simplifying the development process for media-rich or document-heavy applications.

The environment consistency challenge. Docker became the industry standard because it ensures that code runs exactly the same way in development, staging, and production. By supporting OCI-compliant images, Cloudflare allows developers to use their existing CI/CD pipelines and local Docker Desktop environments to test and verify their edge workloads before deployment.

The integration with edge services. While the compute happens inside a container, it remains part of the Cloudflare platform. This means containers can easily access R2 for storage, D1 for relational data, and KV for caching, all while being protected by Cloudflare’s WAF and DDoS mitigation.


a. OCI Images and the Container Runtime

The core of this service is the support for OCI (Open Container Initiative) images. An OCI image is a standardized format that contains everything your application needs to run: the code, a runtime, system libraries, and default environment variables. Because Cloudflare adheres to this standard, you can build your image using docker build or any other OCI-compatible tool. When you deploy, Cloudflare takes this multi-layer image and distributes it across its network, preparing it to be instantiated as a container on demand.

# Example: A Dockerfile for a heavy compute task using Python and FFmpeg
FROM python:3.11-slim

# Install system-level dependencies
RUN apt-get update && apt-get install -y ffmpeg

# Set up application
WORKDIR /app
COPY . .
RUN pip install -r requirements.json

# The container listens on a port, just like a web server
EXPOSE 8080
CMD ["python", "processor.py"]

The runtime environment for Cloudflare Containers differs from traditional “Isolates.” While a Worker starts in milliseconds, a container must pull image layers (if not cached) and start the init process. To combat this, Cloudflare utilizes a specialized container host that optimizes layer caching and uses “MicroVM” technology to ensure that containers are isolated from each other while maintaining high performance.

Communication with these containers is typically handled via HTTP or WebSockets. When a container starts, it is assigned an internal IP or a service binding name. A Worker can then fetch this service, passing the request into the container. This allows the Worker to handle authentication, rate limiting, and caching at the “Front Edge,” while the container performs the intensive work in the “Background Edge.”


b. Deployment and Registry Integration

To deploy a container, you first need to get your image into a registry that Cloudflare can access. Cloudflare provides its own Container Registry, which is optimized for speed within the network. You can use the wrangler CLI to authenticate your local Docker environment, tag your images, and push them directly to Cloudflare. This creates a tight loop between building your code and seeing it live on the network.

# Example: Pushing a local image to the Cloudflare registry
# 1. Build the image locally
docker build -t cloudflare/media-processor:v1 .

# 2. Login via Wrangler
npx wrangler login

# 3. Push to the registry
npx wrangler containers push cloudflare/media-processor:v1

Once the image is pushed, you configure the container deployment in your wrangler.toml. This is where you define the hardware resources—such as the number of vCPUs and the amount of memory—as well as the environment variables and secrets. Unlike Workers, which share a common pool of resources, containers are allocated dedicated slices of the host machine’s hardware.

# wrangler.toml configuration for a container
[[containers]]
name = "MEDIA_WORKER"
image = "registry.cloudflare.com/my-account/media-processor:v1"
cpu = 2
memory = "4Gi"

[vars]
OUTPUT_BUCKET = "processed-media"

The deployment process handles versioning and rollouts. When you update the image tag in your configuration and redeploy, Cloudflare performs a rolling update, spinning up new instances of the container and draining traffic from the old ones. This ensures zero-downtime deployments even for heavy applications.


c. The Hybrid Edge: Worker-to-Container Routing

The most effective architectural pattern for Cloudflare Containers is the “Hybrid Edge.” In this model, a standard Worker acts as the public-facing entry point. It receives the initial HTTP request, performs fast operations (like checking a cookie or looking up a value in KV), and then decides if it needs to trigger a container. If it does, it uses a Service Binding to pass the request to the container.

// Entry-point Worker (Lightweight Isolate)
export default {
  async fetch(request, env) {
    const url = new URL(request.url);

    // Only route 'heavy' tasks to the container
    if (url.pathname === "/process-video") {
      // Forward the request to the container via binding
      return await env.MEDIA_WORKER.fetch(request);
    }

    // Handle lightweight tasks directly in the Worker
    return new Response("Normal edge response");
  }
};

This pattern solves several problems. First, it mitigates the impact of container cold starts. The Worker can return a “Processing started” response immediately, while the container works asynchronously. Second, it allows for granular scaling. You might have one Worker handling millions of requests, but only a few containers running for the subset of requests that actually require them.

Networking within this hybrid model is secure by default. The container does not need to be exposed to the public internet; it only needs to be accessible to the Worker via the service binding. This significantly reduces the attack surface of your application, as all public traffic must first pass through Cloudflare’s standard edge security layers before ever reaching the containerized environment.


Complete Example Session

# ============================================
# PART 1: DEFINING THE WORKLOAD (Dockerfile)
# ============================================
# Use a base image with heavy dependencies
FROM node:20-slim
RUN apt-get update && apt-get install -y graphicsmagick
WORKDIR /usr/src/app
COPY package*.json ./
RUN npm install
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]

# ============================================
# PART 2: THE SERVER LOGIC (server.js)
# ============================================
// Inside the container, we run a standard web server
// const express = require('express');
// app.post('/resize', (req, res) => { /* use gm to resize */ });

# ============================================
# PART 3: BUILDING THE IMAGE
# ============================================
docker build -t cf-image-processor .

# ============================================
# PART 4: AUTHENTICATING WRANGLER
# ============================================
npx wrangler login

# ============================================
# PART 5: PUSHING TO CLOUDFLARE REGISTRY
# ============================================
npx wrangler containers push cf-image-processor:latest

# ============================================
# PART 6: CONFIGURING THE BINDING (wrangler.toml)
# ============================================
# [[containers]]
# binding = "PROCESSOR"
# image = "registry.cloudflare.com/acct/cf-image-processor:latest"
# memory = "2Gi"

# ============================================
# PART 7: THE GATEWAY WORKER (index.js)
# ============================================
export default {
  async fetch(req, env) {
    // Logic to validate request
    return await env.PROCESSOR.fetch(req);
  }
}

# ============================================
# PART 8: DEPLOYING THE HYBRID STACK
# ============================================
npx wrangler deploy

# ============================================
# PART 9: TESTING THE HEAVY TASK
# ============================================
curl -X POST https://my-app.com/resize -F "image=@photo.jpg"

# ============================================
# PART 10: MONITORING LOGS
# ============================================
npx wrangler containers logs PROCESSOR

The example above demonstrated the end-to-end workflow: containerizing a legacy utility (GraphicsMagick), pushing it to the Cloudflare registry, binding it to a Worker, and deploying the hybrid architecture.


Quick Reference

Worker Isolates vs. Containers

FeatureWorkers (Isolates)Cloudflare Containers
RuntimeV8 IsolateFull Linux OCI Container
Startup1ms – 10ms100ms – 2s
Memory128MB – 512MBUp to 16GB+
BinariesWasm onlyAny Linux binary
FilesystemNo (ReadOnly/Ephemeral)Standard Posix Filesystem
Best ForRouting, Auth, APIsFFmpeg, Python, Legacy Apps

Hardware Profiles (Standard)

ProfilevCPUMemoryUse Case
Small1512 MiBBackground cron jobs
Medium22 GiBWeb servers, API proxies
Large48 GiBImage processing
X-Large816 GiBVideo encoding, ML

Common Wrangler Container Commands

CommandDescription
wrangler containers pushUploads image to Cloudflare registry
wrangler containers listShows active container deployments
wrangler containers logsStreams logs from the container
wrangler containers stopManually terminates an instance

Best Practices

✅ Do This:

# Use small base images like alpine or slim
FROM python:3.10-slim                                         # ✅

# Keep the Isolate Worker for auth and validation
if (!isAuthorized(req)) return new Response("Unauthorized");  // ✅

# Forward requests using Service Bindings
return await env.CONTAINER_BINDING.fetch(request);            # ✅

# Use environment variables for secrets
const apiKey = env.DB_PASSWORD;                               // ✅

# Multi-stage builds to reduce image size
FROM node:20 as builder ... FROM node:20-slim                 # ✅

❌ Don’t Do This:

# Don't use massive, unoptimized images
FROM ubuntu:latest  # (Slows down cold starts)              # ❌

# Don't expose the container directly to the internet
# (Use the Worker as a secure gateway)                       # ❌

# Don't store persistent data on the local filesystem
# (It is ephemeral; use R2 or D1 instead)                    # ❌

# Don't run long-running background loops
# (Scale to zero means the container may be killed)          # ❌

# Don't ignore SIGTERM in your application
# (Handle graceful shutdowns)                                # ❌

Common Pitfalls

PitfallWhy It HappensFix
High Cold StartImage is too large (>500MB)Use Alpine-based images and minimize layers.
Data LossWriting to /tmp and expecting it to persistUse R2 or D1 for persistent storage.
Connection RefusedContainer process isn’t listening on EXPOSE portEnsure your app binds to 0.0.0.0 and the correct port.
Resource ExhaustionMemory limit is set too low for the workloadIncrease memory in wrangler.toml profile.
Registry Auth FailureLocal Docker not logged into CloudflareRun npx wrangler login then docker login.
Zombie ProcessesContainer doesn’t handle PID 1 correctlyUse tini or a proper init system in Dockerfile.

Real-World Examples

1. On-the-fly Video Transcoding

Using FFmpeg inside a container to convert user uploads into different resolutions and formats.

2. PDF Generation from HTML

Running Headless Chrome or Puppeteer in a container to render complex invoices and reports.

3. Python Data Science

Executing NumPy or Pandas scripts that require C-extensions not compatible with standard Workers.

4. Image Optimization with GraphicsMagick

Providing a high-performance image manipulation API using legacy Linux binaries.

5. Markdown to Docx Conversion

Using Pandoc as a service to convert documentation formats on the edge.

6. Legacy API Proxy

Moving an existing Node.js Express application to the edge without refactoring for the Worker API.

7. Machine Learning Inference

Running small PyTorch or TensorFlow Lite models for sentiment analysis or image classification.

8. Database Migration Runner

A container that executes complex SQL migration scripts against D1 or external databases.

9. Custom Search Indexer

A background container that crawls content and builds a search index stored in R2.

10. Secure Sandbox Execution

Running user-submitted code in an isolated container environment for online IDEs or coding platforms.


Visual

Isolate vs. Container Execution

┌─────────────────────────────┐   ┌─────────────────────────────┐
│ WORKER ISOLATE (V8)         │   │ CLOUDFLARE CONTAINER (OCI)  │
│                             │   │                             │
│ ┌─────────────────────────┐ │   │ ┌─────────────────────────┐ │
│ │ JS / WASM ONLY          │ │   │ │ FULL LINUX OS           │ │
│ └─────────────────────────┘ │   │ ├─────────────────────────┤ │
│                             │   │ │ ANY BINARY (FFmpeg, etc)│ │
│   [ Shared Process ]        │   │ └─────────────────────────┘ │
│   [ Sub-millisecond ]       │   │                             │
│                             │   │   [ Dedicated Resources ]   │
│                             │   │   [ MicroVM Isolation ]     │
└─────────────────────────────┘   └─────────────────────────────┘

The Hybrid Edge Request Flow

      Internet
         │
         ▼
┌──────────────────┐
│  WORKER (ENTRY)  │ ──► [ Auth / WAF / Fast Cache ]
└────────┬─────────┘
         │
         │ (Service Binding)
         ▼
┌──────────────────┐
│    CONTAINER     │ ──► [ Heavy Compute / Binaries ]
└────────┬─────────┘
         │
         ▼
┌──────────────────┐
│  DATA / STORAGE  │ ──► [ R2 / D1 / External DB ]
└──────────────────┘

Image Layer Distribution

┌───────────────────────────────────────────────────────────┐
│ CLOUDFLARE CONTAINER REGISTRY                             │
│                                                           │
│ [ Layer A (Base OS) ] ───► Distributed to Global Cache    │
│ [ Layer B (Libs)    ] ───► Distributed to Global Cache    │
│ [ Layer C (App)     ] ───► Pushed from Developer CI       │
│                                                           │
│ Result: Cold starts only fetch Layer C if A/B are warm.   │
└───────────────────────────────────────────────────────────┘

Scaling and Resource Allocation

┌───────────────────────────────────────────────────────────┐
│ HOST MACHINE                                              │
│                                                           │
│ ┌──────────────┐  ┌──────────────┐  ┌──────────────┐      │
│ │ Worker Isolate│  │ Container A  │  │ Container B  │      │
│ │ (128MB)       │  │ (2GB RAM)    │  │ (8GB RAM)    │      │
│ └──────────────┘  │ (2 vCPU)     │  │ (4 vCPU)     │      │
│                   └──────────────┘  └──────────────┘      │
│                                                           │
└───────────────────────────────────────────────────────────┘

Summary

ItemValue
FormatOCI / Docker Image
DistributionGlobal Edge Network
CommunicationService Bindings / HTTP
Deploymentwrangler.toml + Registry
IsolationMicroVM / Hardware-level
Cold StartManaged via Layer Caching
Best LogicHybrid (Worker -> Container)
LimitScaling to zero supported

Key takeaways:

  • Cloudflare Containers remove the V8 sandbox. They allow you to run any Linux binary, custom OS libraries, and languages like Python or Ruby that don’t fit into the Isolate model.
  • Hybrid Edge is the recommended architecture. Use a standard Worker for lightweight tasks and security, then delegate heavy compute to a container via a Service Binding.
  • OCI compatibility ensures portability. You can use standard Docker tools to build, test locally, and push images to the Cloudflare Container Registry.
  • Dedicated resources enable heavy compute. Unlike Isolates that share memory aggressively, Containers are allocated specific slices of vCPU and RAM, making them ideal for media processing and ML.
  • Ephemeral filesystem requires external storage. The container’s disk is wiped on restart; always use Cloudflare R2 for files or D1 for structured data to ensure persistence.

Remember: Use Workers for the “Fast Path” and Containers for the “Heavy Path.” Cloudflare Containers are not a replacement for Workers; they are an extension that allows you to bring the entire Linux ecosystem to the edge.

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!