On December 4, 2026, Hugging Face added a fourth kind of repository to the Hub. Next to models, datasets, and Spaces, you can now publish Docker and OCI container images — in the same organization, under the same permissions, tokens, and storage, served from the registry at cr.hf.co. If you ship models, this closes a gap you have felt for years: your weights lived on the Hub, but the image that actually serves them lived on Docker Hub or in a private registry, with its own account, its own billing, and its own access list.

This tutorial takes the feature end to end. You will build a small CPU inference service — FastAPI plus a quantized DistilGPT-2 running on ONNX Runtime — test it locally, push it to the Hub with the hf containers CLI, pull it on another machine, and wire the same flow into GitHub Actions and Kubernetes. Every command is either run and tested here or quoted from Hugging Face's Container Repos documentation and checked against the CLI's own help output. The one thing you need that this machine did not have is Docker itself: the build, push, and pull steps run on any machine with Docker and the containerd image store enabled.

What you'll need#

  • A Hugging Face account (free) and a User Access Token with write scope for pushing, read for pulling. Create one at Settings → Access Tokens.
  • Docker with the containerd image store enabled — required by hf containers. In Docker Desktop, turn on "Use containerd for pulling and storing images" under Settings → General; on Linux, add {"features": {"containerd-snapshotter": true}} to /etc/docker/daemon.json and restart the daemon.
  • Python 3.12 and pip, for the hf CLI and the local test run.
  • About 30 minutes and roughly 300 MB of disk for the demo model.
  • A namespace to publish under — your username or an organization you administer.

On cost: images count toward your organization's Hub storage, public or private, with no separate registry bill. A free organization includes 100 GB of private storage; Team and Enterprise organizations get 1 TB per seat, then $18 per TB per month. Pulls count against the egress allowance in your plan. The demo image in this tutorial is under 1 GB, so it fits comfortably in the free tier.

Step 1: Install the hf CLI and the containers extension#

The hf command line ships with huggingface_hub 2.x. Install it, confirm the version, then add the containers extension — the recommended client for the new registry. It uploads only the parts of a layer that changed since the previous version, and pulls layers straight from Xet storage with nothing to decompress.

pip install -U huggingface_hub
hf --version
hf extensions install hf-containers
hf containers --help

Expected output: hf --version prints 2.6.0 (the version tested here), and hf containers --help lists the subcommands build, copy, create, delete, pull, push, remove, run, and tag. Then authenticate — either run the interactive login or export your token:

hf auth login
# or, non-interactively:
export HF_TOKEN="hf_your_token_here"

If the extension install fails on its first attempt with an ensurepip error, just run it again — the install is idempotent, and a retry succeeds once the extension virtualenv is cleanly created.

Step 2: Enable Container Repos and create the repository#

Container Repos are switched on per account: toggle the setting in your personal settings, or in your organization's Account settings. Then create the repository before the first push — a push to a repository that does not exist fails with NAME_UNKNOWN. You can create it in the browser at huggingface.co/new-container, or from the CLI:

hf containers create my-org/distilgpt2-onnx --private \
  --description "CPU inference service: DistilGPT-2 (ONNX int8) behind FastAPI"

Replace my-org with your username or organization. The --private flag keeps the image visible only to members of the namespace; omit it for a public repository. --exist-ok makes the command succeed when the repository already exists, which is what you want in scripts. The equivalent API call, if you prefer curl:

curl -X POST https://huggingface.co/api/containers/my-org/distilgpt2-onnx \
  -H "Authorization: Bearer $HF_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{"private": true}'

Who can pull and push follows the repository's visibility and each member's role in the organization, exactly like a model repository. The image's page will live at https://huggingface.co/containers/my-org/distilgpt2-onnx, listing its tags.

Step 3: Build the demo inference service#

The service is deliberately small and CPU-only, so you can run it on a laptop: a FastAPI app that loads a quantized DistilGPT-2 (82M parameters, ONNX int8, Apache-2.0 weights from Xenova/distilgpt2) and serves greedy text generation. DistilGPT-2 is not a frontier model — its continuations read like a small 2019 model, because they are — but the plumbing is identical to serving a real model, and every line below was executed locally before publication.

Create the project:

mkdir distilgpt2-onnx && cd distilgpt2-onnx
mkdir -p app model
hf download Xenova/distilgpt2 onnx/model_quantized.onnx \
  tokenizer.json tokenizer_config.json config.json \
  vocab.json merges.txt generation_config.json special_tokens_map.json \
  --local-dir model
rm -rf model/.cache   # the downloader leaves a cache folder behind

Now the application. Save this as app/main.py:

"""Tiny inference service: FastAPI + ONNX Runtime + DistilGPT-2 (int8).

Loads the model once at startup, then serves greedy text generation on
POST /generate. Health probe on GET /health.
"""
import os

import numpy as np
import onnxruntime as ort
from fastapi import FastAPI
from pydantic import BaseModel
from tokenizers import Tokenizer

MODEL_DIR = os.environ.get("MODEL_DIR", "model")
N_LAYERS, N_HEADS, HEAD_DIM = 6, 12, 64
EOS_ID = 50256

app = FastAPI(title="distilgpt2-onnx")
_tokenizer = Tokenizer.from_file(os.path.join(MODEL_DIR, "tokenizer.json"))
_session = ort.InferenceSession(
    os.path.join(MODEL_DIR, "onnx", "model_quantized.onnx"),
    providers=["CPUExecutionProvider"],
)


class GenerateRequest(BaseModel):
    prompt: str
    max_new_tokens: int = 32


class GenerateResponse(BaseModel):
    text: str
    tokens_generated: int


def _empty_past(past_len=0):
    return {
        f"past_key_values.{i}.{kv}": np.zeros((1, N_HEADS, past_len, HEAD_DIM), dtype=np.float32)
        for i in range(N_LAYERS)
        for kv in ("key", "value")
    }


def _generate(prompt: str, max_new_tokens: int) -> tuple[str, int]:
    ids = _tokenizer.encode(prompt).ids
    n = len(ids)
    feed = {
        "input_ids": np.array([ids], dtype=np.int64),
        "attention_mask": np.ones((1, n), dtype=np.int64),
        "position_ids": np.arange(n, dtype=np.int64)[None, :],
        **_empty_past(),
    }
    out = _session.run(None, feed)
    logits, present = out[0], out[1:]
    generated = 0
    for step in range(max_new_tokens):
        nxt = int(np.argmax(logits[0, -1]))
        if nxt == EOS_ID:
            break
        ids.append(nxt)
        generated += 1
        if step == max_new_tokens - 1:
            break
        past = {
            f"past_key_values.{i}.{kv}": present[2 * i + (0 if kv == "key" else 1)]
            for i in range(N_LAYERS)
            for kv in ("key", "value")
        }
        feed = {
            "input_ids": np.array([[nxt]], dtype=np.int64),
            "attention_mask": np.ones((1, n + step + 1), dtype=np.int64),
            "position_ids": np.array([[n + step]], dtype=np.int64),
            **past,
        }
        out = _session.run(None, feed)
        logits, present = out[0], out[1:]
    return _tokenizer.decode(ids), generated


@app.get("/health")
def health():
    return {"status": "ok", "model": "Xenova/distilgpt2 (ONNX int8)"}


@app.post("/generate", response_model=GenerateResponse)
def generate(req: GenerateRequest):
    text, count = _generate(req.prompt, max(1, min(req.max_new_tokens, 128)))
    return GenerateResponse(text=text, tokens_generated=count)

Two details deserve a sentence. The ONNX file is a key-value-cache model, so each step feeds the previous step's present.* outputs back in as past_key_values.* — that is what the loop above does, and it is why the first call passes empty past tensors. And the response text includes your prompt followed by the continuation, because the decoder returns the full sequence; strip the prompt on the client if you only want the new tokens.

Pinned dependencies, as requirements.txt — these exact versions were installed into a fresh virtualenv and run:

fastapi==0.165.1
uvicorn[standard]==0.55.0
onnxruntime==1.32.0
tokenizers==0.23.3
numpy==2.5.5

And the Dockerfile:

FROM python:3.12-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY app/ ./app/
COPY model/ ./model/
EXPOSE 8000
ENV MODEL_DIR=/app/model
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]

Note what is not in the image: no model download at build time. The weights are already in model/, so the build is reproducible offline and the image is self-contained. If your model is large, add a .dockerignore that excludes model/.cache/ and anything else you do not want baked in.

Step 4: Test the service locally#

Before anything touches a registry, prove the service works. Install the dependencies, start the server from the project root, and hit both endpoints:

pip install -r requirements.txt
MODEL_DIR=$PWD/model uvicorn app.main:app --host 127.0.0.1 --port 8000
curl -s http://127.0.0.1:8000/health
curl -s -X POST http://127.0.0.1:8000/generate \
  -H "Content-Type: application/json" \
  -d '{"prompt": "The capital of France is", "max_new_tokens": 20}'

Expected output, exactly as observed in testing:

{"status": "ok", "model": "Xenova/distilgpt2 (ONNX int8)"}
{"text": "The capital of France is to be named the \"Souvenir\" of the French capital of France.


", "tokens_generated": 20}

The continuation is vintage small-model prose — again, the point here is the plumbing, not the poetry. The docs at http://127.0.0.1:8000/docs should also return HTTP 200, giving you FastAPI's interactive Swagger page for the /generate endpoint. If /generate fails, check MODEL_DIR first: the app looks for tokenizer.json and onnx/model_quantized.onnx under it.

Step 5: Build and push the image to cr.hf.co#

One command builds the image and pushes it. hf containers build hands the build to docker buildx build, then uploads only the changed chunks of each layer through Xet:

hf containers build -t cr.hf.co/my-org/distilgpt2-onnx:v1 .

That is the whole publish step. Two variations matter in practice. If you already have a local image and only want to push it, tag it and push:

hf containers tag distilgpt2-onnx cr.hf.co/my-org/distilgpt2-onnx:v1
hf containers push cr.hf.co/my-org/distilgpt2-onnx:v1

And if you prefer plain Docker — or your deployment pins images by digest — the registry speaks standard OCI, so the familiar flow works unchanged. Log in with your Hugging Face username and a token as the password (read to pull, write to push):

echo $HF_TOKEN | docker login cr.hf.co -u my-username --password-stdin
docker build -t cr.hf.co/my-org/distilgpt2-onnx:v1 .
docker push cr.hf.co/my-org/distilgpt2-onnx:v1

The trade-off between the two clients is a real one, and Hugging Face documents it with numbers. hf containers stores layers uncompressed, so a rebuild that touches 100 MB of a 2 GB layer uploads roughly 100 MB — Xet recognizes the unchanged chunks — but the rebuilt layer counts as 2 GB toward your storage, and the image gets different digests than a docker push would produce. Pass --preserve-digests to keep Docker's digests (for signatures or digest-pinned deployments); it is slower, because a changed layer is then uploaded in full. As a rule of thumb: use hf containers while you iterate, and --preserve-digests or plain docker push for releases you pin by digest.

Four-step diagram: Dockerfile and app code, hf containers build, the cr.hf.co registry, and docker run anywhere
AI-generated illustration for AI Frontier Post: the build, publish, distribute, run workflow for a Hugging Face container image.

Step 6: Pull and run it anywhere#

On any machine with Docker — a server, a teammate's laptop, a CI runner — pull and run. hf containers run is docker run with a fast pull first when the local image is missing or stale:

hf containers pull cr.hf.co/my-org/distilgpt2-onnx:v1
hf containers run --rm -p 8000:8000 cr.hf.co/my-org/distilgpt2-onnx:v1

Or with plain Docker, after the same docker login cr.hf.co from Step 5:

docker pull cr.hf.co/my-org/distilgpt2-onnx:v1
docker run --rm -p 8000:8000 cr.hf.co/my-org/distilgpt2-onnx:v1
curl -s http://127.0.0.1:8000/health

The health check should return the same {"status": "ok", ...} JSON as your local run. Public images can be pulled without logging in at all; for private ones, pull with a read token. One behavior to know: pulls count toward Hub rate limits as resolver requests, so log in even for public images — pulls then count against your account rather than your IP address.

Step 7: Copy an existing image instead of building one#

You do not have to build to publish. hf containers copy moves an image from any registry — Docker Hub, ghcr.io, quay.io, registry.k8s.io — into a container repository, without pulling it into Docker first. Every platform of a multi-arch image is copied:

hf containers copy vllm/vllm-openai:v0.11.0 cr.hf.co/my-org/vllm-openai
hf containers copy registry.k8s.io/pause:3.10 cr.hf.co/my-org/pause:3.10

The destination repository must already exist (Step 2), and a destination without a tag takes the source's tag. For a private source, log in to its registry first with docker login — copy reads it with the login Docker saved. This is the fastest way to adopt the Hub as your registry: mirror the images you already depend on, then point your deployments at cr.hf.co. The official vLLM image is a good first mirror, since it turns the Hub into a one-stop shop for both the model weights and the server that runs them.

Step 8: Push from GitHub Actions without a stored token#

Long-lived tokens in repository secrets are the thing that eventually leaks. Container Repos support trusted publishers: add one for your GitHub repository in the container repository's Settings → Trusted Publishers, and the job exchanges its OIDC identity token for a token that can only push to and pull from that repository, expiring after 60 minutes. Set HF_OIDC_RESOURCE to the repository and push with hf containers:

permissions:
  id-token: write  # lets the job request an OIDC token
  contents: read
steps:
  - uses: actions/checkout@v4
  - uses: docker/setup-docker-action@v5
    with:
      daemon-config: '{"features": {"containerd-snapshotter": true}}'  # hf containers needs the containerd image store
  - name: Install hf containers
    run: |
      curl -LsSf https://hf.co/cli/install.sh | bash
      echo "$HOME/.local/bin" >> "$GITHUB_PATH"
      "$HOME/.local/bin/hf" extensions install hf-containers
  - name: Build and push
    env:
      HF_OIDC_RESOURCE: containers/my-org/distilgpt2-onnx
    run: hf containers build -t cr.hf.co/my-org/distilgpt2-onnx:${{ github.sha }} .

To push with Docker instead, replace the last step with a login using the exchanged token, then build and push as usual:

  - name: Log in to cr.hf.co
    env:
      HF_OIDC_RESOURCE: containers/my-org/distilgpt2-onnx
    run: hf auth token | docker login cr.hf.co -u oauth2 --password-stdin
  - uses: docker/build-push-action@v7
    with:
      push: true
      tags: cr.hf.co/my-org/distilgpt2-onnx:${{ github.sha }}

Without a trusted publisher, store a write token as a repository secret and set HF_TOKEN: ${{ secrets.HF_TOKEN }} instead of HF_OIDC_RESOURCE. A read-only publisher exists too, for jobs that only need to pull.

Diagram of a CI/CD pipeline: GitHub Actions, OIDC trusted publisher, cr.hf.co registry, and a Kubernetes pod pulling the image
AI-generated illustration for AI Frontier Post: pushing from GitHub Actions with OIDC and deploying to Kubernetes.

Step 9: Pull the image from Kubernetes#

The registry is standard OCI, so Kubernetes needs nothing special — a pull secret holding a read token, and the image reference in the pod spec:

kubectl create secret docker-registry hf-registry \
  --docker-server=cr.hf.co \
  --docker-username=my-username \
  --docker-password=$HF_TOKEN
apiVersion: v1
kind: Pod
metadata:
  name: distilgpt2-onnx
spec:
  containers:
    - name: distilgpt2-onnx
      image: cr.hf.co/my-org/distilgpt2-onnx:v1
  imagePullSecrets:
    - name: hf-registry

Public images need no pull secret, but adding one anyway makes pulls count against your account's rate limits instead of your cluster's IP address. Images pushed with hf containers pull exactly the same way as images pushed with Docker.

Which approach should you use?#

ApproachBest forWatch out for
hf containers build / pushDay-to-day iteration; frequent rebuilds of large imagesUncompressed layers use more storage; digests differ from docker push
Plain docker pushReleases pinned by digest; signed images; existing Docker workflowsA rebuilt layer re-uploads in full, even if only 100 MB changed
hf containers copyMirroring images you already use (vLLM, base images) onto the HubDestination repository must exist first; copies also convert layers unless --preserve-digests
Docker Hub / GHCRProjects with no Hub footprint, or registries your org already standardizes onSeparate account, billing, and access list from the models the image serves

The deciding question is where your models already live. If your weights, datasets, and demos are on the Hub, putting the image there removes an entire account and access list from your deployment story — one token, one permissions model, one storage bill. If nothing else you run touches the Hub, Docker Hub or GHCR is the simpler choice. Either way, the image itself is a standard OCI artifact: nothing in this tutorial locks you to Hugging Face's registry.

What it costs#

Images are billed as storage of the organization that owns them, shared with its models, datasets, and buckets — each repository counts a layer once, however many tags and images use it. Hugging Face's own examples make the math concrete: 20 tagged versions of an image pushed as 5 GB, all sharing the same 4 GB of base layers, take 4 + 20 × 1 = 24 GB, which fits in a free organization's 100 GB of private storage. The catch is the uncompressed trade-off: 12 releases of a vLLM image, about 9 GB each compressed and 21 GB uncompressed, use 110 GB pushed with docker push but 250 GB pushed with hf containers. For the demo image in this tutorial the difference is noise; for multi-gigabyte inference images, push release tags with --preserve-digests and keep the fast hf containers path for development tags. And remember the garbage collection: images no tag points to are deleted automatically, so untag aggressively and your storage follows what you actually ship.

Make it real: swap in a frontier model#

The demo proves the pipeline with a toy model. The same pattern scales directly: Hugging Face's own custom-container documentation walks through a FastAPI inference server for HuggingFaceTB/SmolLM3-3B (Apache-2.0), built on a CUDA base image with the model mounted from /repository on Inference Endpoints. Two changes carry you there: swap the python:3.12-slim base for a CUDA PyTorch image, and replace the ONNX loader with a transformers pipeline — the Dockerfile, the push, and the pull stay exactly as written above. Or skip building entirely: copy the official vLLM image with Step 7 and serve any Hub model behind an OpenAI-compatible API. Either way, the registry, the token, and the workflow you just set up do not change.

The takeaway#

Container Repos are a small feature with an outsized effect on how model work ships: the image that serves your model now lives next to the model, governed by the same permissions and paid for out of the same storage. The workflow is four commands — hf containers create, build, pull, run — plus the standard OCI escape hatches (plain Docker, copy, OIDC in CI, pull secrets in Kubernetes) for everything else. Start with the demo image, mirror one image you already depend on, and point your next deployment at cr.hf.co.