Subscribe
AWS

Copying images between ECR repositories without Docker, and why blob mount silently does nothing

ECR answered our cross-repository blob mount with 202 and a fresh upload session, so a naive copy uploaded nothing. A standard-library Python copier for multi-arch images, the S3 redirect gotcha, and the BLOB_MOUNTING setting.

Copying images between ECR repositories without Docker, and why blob mount silently does nothing

In September I had to move a service's images from one ECR repository to another, in the same account and region. The service was being renamed, and the new repository needed the exact image that was running, same digest, so the deploy would be a pure rename and nothing else.

The machine I was on had no Docker daemon itself. That sounds like a problem, but a registry is just an HTTP API, so I thought I'd do it with the Registry v2 "cross-repository blob mount" call: ask the destination to link a layer that already exists in the source. No bytes move. It's the cheap way.

ECR answered with 202 Accepted. Not 201 Created. And a 202 there means "I did not mount anything, here is an empty upload session instead". If your code only checks for a 2xx, it carries on happily and you end up with a manifest pointing at layers the new repository doesn't have.

In this blog we will look at why that happens, a small Python script that copies an image (multi-arch included) with only the standard library, and the two gotchas I hit on the way.

What the mount call is

The OCI distribution spec lets a client open a blob upload with two query parameters:

POST /v2/<destination>/blobs/uploads/?mount=sha256:<digest>&from=<source>

If the registry can link the blob, it returns 201 Created and you are done with that layer. If it can't (or won't), the spec allows it to fall back to a normal upload session and return 202 Accepted with a Location header. So the 202 is legal. It's just very easy to read as success.

On our ECR registry that's what I got, for every layer. Later I found out why it might be: since 20 January 2026 ECR supports blob mounting, but only when you turn it on for the registry, and it's off unless someone does:

aws ecr put-account-setting --name BLOB_MOUNTING --value ENABLED

The AWS page for it is Blob mounting in Amazon ECR. There are conditions too: same account and region, both repositories with the same encryption type and key, the pusher needs ecr:GetDownloadUrlForLayer on the source, and images that came through a pull-through cache can't be mounted. I haven't gone back and enabled it on that account to test, so treat "the setting was off" as my best guess for the 202, not a fact I checked. Either way the lesson holds: code that talks to a registry should check for 201, and handle 202 as "now upload the bytes".

Copying without Docker

If mounting isn't available, a copy means streaming every blob. For one image manifest that is:

  1. GET the manifest from the source.
  2. For the config blob and every layer: GET it from the source, POST to open an upload on the destination, then PUT the bytes to the Location with ?digest= added.
  3. PUT the manifest to the destination, byte for byte as you read it.

A multi-arch image is an index (OCI image index or Docker manifest list) pointing to one manifest per platform. You do step 1 to 3 for every sub-manifest, PUT each one by its digest, and only then PUT the index under the tag. The order matters, a registry rejects a manifest whose blobs or sub-manifests aren't there yet.

Here is the whole thing. It uses only the standard library, so it runs anywhere Python 3.8+ is.

#!/usr/bin/env python3
"""Copy an image (single manifest or multi-arch index) between two repositories
of the same registry without a Docker daemon. Standard library only.

    export REGISTRY=https://111122223333.dkr.ecr.ap-south-1.amazonaws.com
    export REGISTRY_AUTH="Basic $(aws ecr get-authorization-token \
        --query 'authorizationData[0].authorizationToken' --output text)"
    python3 ecr_copy.py jobs-old:1.4.2 jobs-new:1.4.2 [--try-mount]
"""
import argparse
import hashlib
import json
import os
import sys
import tempfile
import urllib.error
import urllib.parse
import urllib.request

INDEX_TYPES = {
    "application/vnd.oci.image.index.v1+json",
    "application/vnd.docker.distribution.manifest.list.v2+json",
}
ACCEPT = ", ".join(sorted(INDEX_TYPES | {
    "application/vnd.oci.image.manifest.v1+json",
    "application/vnd.docker.distribution.manifest.v2+json",
}))


class Registry:
    def __init__(self, base, auth):
        self.base = base.rstrip("/")
        self.auth = auth

    def call(self, method, path, data=None, headers=None):
        url = path if path.startswith("http") else self.base + path
        req = urllib.request.Request(url, data=data, method=method)
        for k, v in (headers or {}).items():
            req.add_header(k, v)
        if self.auth:
            # Unredirected: urllib copies normal headers onto a redirect, and the
            # S3 URL that ECR redirects blob GETs to rejects an extra Authorization.
            req.add_unredirected_header("Authorization", self.auth)
        return urllib.request.urlopen(req)

    def has_blob(self, repo, digest):
        try:
            self.call("HEAD", f"/v2/{repo}/blobs/{digest}")
            return True
        except urllib.error.HTTPError:
            # 404, or a redirect we can't follow with HEAD: copy it anyway,
            # re-uploading a blob that exists is harmless.
            return False

    def copy_blob(self, src, dst, digest, try_mount):
        if self.has_blob(dst, digest):
            return "exists"
        path = f"/v2/{dst}/blobs/uploads/"
        if try_mount:
            q = urllib.parse.urlencode({"mount": digest, "from": src})
            resp = self.call("POST", f"{path}?{q}")
            if resp.status == 201:
                return "mounted"
            # 202 means "no mount, here is an upload session instead".
        else:
            resp = self.call("POST", path)
        location = urllib.parse.urljoin(self.base + path, resp.headers["Location"])

        with tempfile.TemporaryFile() as tmp:
            h = hashlib.sha256()
            with self.call("GET", f"/v2/{src}/blobs/{digest}") as body:
                while chunk := body.read(1 << 20):
                    h.update(chunk)
                    tmp.write(chunk)
            if "sha256:" + h.hexdigest() != digest:
                raise SystemExit(f"digest mismatch while reading {digest}")
            size = tmp.tell()
            tmp.seek(0)
            sep = "&" if "?" in location else "?"
            put = f"{location}{sep}digest={urllib.parse.quote(digest)}"
            self.call("PUT", put, data=tmp, headers={
                "Content-Type": "application/octet-stream",
                "Content-Length": str(size),
            })
        return "copied"

    def get_manifest(self, repo, ref):
        with self.call("GET", f"/v2/{repo}/manifests/{ref}", headers={"Accept": ACCEPT}) as r:
            raw = r.read()
            media = r.headers.get("Content-Type", "").split(";")[0]
        return raw, media or json.loads(raw).get("mediaType")

    def put_manifest(self, repo, ref, raw, media):
        # Send the exact bytes we read, so the digest cannot change.
        self.call("PUT", f"/v2/{repo}/manifests/{ref}", data=raw,
                  headers={"Content-Type": media})


def copy_manifest(reg, src, dst, ref, try_mount, put_ref=None):
    raw, media = reg.get_manifest(src, ref)
    doc = json.loads(raw)
    if media in INDEX_TYPES:
        for sub in doc["manifests"]:
            copy_manifest(reg, src, dst, sub["digest"], try_mount)
    else:
        for blob in [doc["config"], *doc["layers"]]:
            how = reg.copy_blob(src, dst, blob["digest"], try_mount)
            print(f"  {blob['digest'][:19]}  {how}")
    reg.put_manifest(dst, put_ref or ref, raw, media)
    return "sha256:" + hashlib.sha256(raw).hexdigest()


def main():
    p = argparse.ArgumentParser()
    p.add_argument("src", help="repo:tag")
    p.add_argument("dst", help="repo:tag")
    p.add_argument("--try-mount", action="store_true")
    a = p.parse_args()
    reg = Registry(os.environ["REGISTRY"], os.environ.get("REGISTRY_AUTH"))
    src_repo, src_tag = a.src.rsplit(":", 1)
    dst_repo, dst_tag = a.dst.rsplit(":", 1)

    want = copy_manifest(reg, src_repo, dst_repo, src_tag, a.try_mount, dst_tag)
    raw, _ = reg.get_manifest(dst_repo, dst_tag)
    got = "sha256:" + hashlib.sha256(raw).hexdigest()
    print(f"source {want}\ncopy   {got}")
    return 0 if got == want else 1


if __name__ == "__main__":
    sys.exit(main())

Run it with an ECR token:

export REGISTRY=https://111122223333.dkr.ecr.ap-south-1.amazonaws.com
export REGISTRY_AUTH="Basic $(aws ecr get-authorization-token \
    --query 'authorizationData[0].authorizationToken' --output text)"
python3 ecr_copy.py jobs-old:1.4.2 jobs-new:1.4.2

The token from get-authorization-token is already base64 of AWS:<password>, so it goes straight after Basic. Don't encode it again, that only gets you a 401. The token is valid for 12 hours.

Gotcha: the redirect to S3

ECR doesn't serve layer bytes itself. A blob GET answers with a redirect to a pre-signed S3 URL. Python's urllib follows the redirect and copies the request headers onto the new request, Authorization included. Basically S3 then sees two kinds of auth at once (the signature in the URL and your header) and refuses the request.

requests drops the header when the host changes. urllib doesn't. The fix in the script is one method: add_unredirected_header. Headers added that way go on the first request only and are left off any redirect. You can see why in CPython's HTTPRedirectHandler.redirect_request: it builds the new request from req.headers, and unredirected headers live in a separate dict.

Checking it works

I didn't want to trust my own code blindly, so for this post I ran it against a local registry:2 container. I loaded alpine:3.20 (an OCI index with one manifest per platform) into one repository with docker buildx imagetools create, then copied it into another repository with the script, under a different tag:

source sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc
copy   sha256:d9e853e87e55526f6b2917df91a2115c36dd7c696a35be12163d44e6e2a4b6bc

Same digest, so index bytes are identical and every sub-manifest it names had to be there for the PUT to succeed. Running it a second time printed exists for every blob, which is the HEAD check doing its job. With --try-mount, the local registry did mount the layers (201), which is how a registry with mounting on behaves.

One thing that surprised me while testing: a mount request for a digest the source doesn't have also returns 202 on the reference registry. So a 202 tells you "not mounted", never why.

The real copy in September came out the same way: the digest in the new repository matched the old one byte for byte, and the renamed service deployed the identical image.

When not to bother

If you have Docker or a tool like crane or skopeo on the machine, use those; they handle mount fallback properly. And if the copy is a one-off for a rename, the rest of the rename has its own list of leftovers (secrets, log groups, task definition families), which is a story for another post.

For pushing new images rather than copying old ones, the normal CI path is in Building and pushing Docker images to ECR and GHCR from GitHub Actions. And if your pushes fail with an IAM error naming the wrong role, that one is usually not IAM at all: see self-hosted runners sharing one Docker config.

Whatever you use, compare the digest at the end. It's one line.