Skip to content

📖 Add import image from docker guide #5235

Closed

Description

@helderco

Summary

Similarly to the Load Container Images into a Local Docker Engine guide, add a “Import Container Images from a Local Docker Engine”.

Rationale

This is pretty simple with an external registry, accessible by both docker and dagger. Otherwise you need to spin one up. It's the same idea as the guide referenced above, but in reverse.

This can all be automated in dagger. We still need some plumbing to be able to use a Service in Container.from but in the meantime, the workaround can still be pretty much automated and reused.

Example

In Python:

import contextlib
import uuid

import anyio
import dagger
from dagger import dag


IMAGE_NAME = "my-local-image"


async def main(img: str):
    async with dagger.connection():
        async with docker_image(img) as ref:
            output = await (
                dag.container()
                .from_(ref)
                .env_variable("HELLO")
            )

    print(f"Hello {output}!")


@contextlib.asynccontextmanager
async def docker_image(source: str):
    """Context manager to get a docker image from a local docker daemon.

    This automates several setup steps in the host's docker, using ephemeral
    resources that are cleaned up afterward.

    Parameters
    ----------
    source:
        The name of the image to pull from the host's docker daemon.
    """

    # Get the engine container name so we can use its network.
    # Do it first to fail fast.
    ctr_name = await docker(
        "ps",
        "--filter", "name=^dagger-engine-.*",  # this assumes a released dagger
        "--format", "{{.Names}}"
    )

    if not ctr_name.strip():
        raise RuntimeError("Could not find dagger engine container")

    # Create an ephemeral volume that can be used between registry instances.
    vid = await docker("volume", "create")

    # Run a registry in the host's network so we can push the image to it.
    # Assign a random port to avoid conflicts.
    host_cid = await registry(vid, "-p", "5000")
    port = (await docker("port", host_cid, "5000")).split("\n")[0].split(":")[1]

    # Tag and push to registry.
    target = f"127.0.0.1:{port}/{source}"
    await docker("tag", source, target)
    await docker("push", target)

    # Cleanup. We have what we need in the volume now.
    await docker("image", "rm", target)
    await docker("stop", host_cid)

    # Run another registry in the dagger engine's network so we can pull the image.
    cid = await registry(vid, "--network", f"container:{ctr_name}")

    # Yield the new image reference where it's reachable from the running registry.
    try:
        yield f"127.0.0.1:5000/{source}"
    finally:
        # Returned from context manager. Cleanup.
        await docker("stop", cid)
        await docker("volume", "rm", vid)


async def docker(*cmd: str):
    """Run a docker command in the host's docker daemon."""
    return (
        await (
            dag.container()
            .from_("docker:cli")
            .with_unix_socket(
                "/var/run/docker.sock",
                dag.host().unix_socket("/var/run/docker.sock"),
            )
            .with_env_variable("CACHE_BUSTER", uuid.uuid4().hex)
            .with_exec(cmd)
            .stdout()
        )
    ).strip()


async def registry(volume: str, *opts: str):
    """Run a docker registry in a container.

    Will run in the backround and be removed when stopped.
    """
    return await docker(
        "run", "-d",
        "--rm", "-q",
        "-v", f"{volume}:/var/lib/registry",
        *opts,
        "registry:2",
    )


anyio.run(main, IMAGE_NAME)

Build a local image:

❯ docker build -t my-local-image - <<EOF
FROM alpine
ENV HELLO=Docker
EOF

Should output:

❯ dagger run python main.py
Hello from Docker!

Activity

  1. added
    area/documentation
    on Jun 1, 2023
  2. helderco commented on Nov 21, 2023

    @helderco
    ContributorAuthor

    It would be nice to be able to do it all in dagger, i.e., spinning an ephemeral registry service, binding it to a docker cli container to push to it, then pulling from the registry as normal. However I don't know how to make docker reach this registry service, thus we may need instructions to do it manually like in the above guide.

    Since we now have host networking, this is now doable. Similarly, we can also improve the reverse guide now without workarounds.

    The Using an exported archive example is still useful in case you already have the exported archive from other means, not for the full export + import in dagger which is no longer necessary as a workaround.

  3. vikram-dagger commented on Nov 22, 2023

    @vikram-dagger
    Contributor

    Since we now have host networking, this is now doable. Similarly, we can also improve the reverse guide now without workarounds.

    I discussed this with @vito and my understanding is that this is not yet supported. I'll wait a bit longer to work on this.

  4. helderco commented on Dec 5, 2023

    @helderco
    ContributorAuthor

    I discussed this with @vito and my understanding is that this is not yet supported. I'll wait a bit longer to work on this.

    How so? From my understanding we decided to wait because there was an open PR for host networking. There's no open PR or issue (that I know of) for supporting a direct import from a docker engine, but with host networking we can support it via an ephemeral docker registry in dagger, no?

    So it's still a workaround but it can be hidden away in implementation, it doesn't require a lot of manual setup from users anymore like when this issue was created. Unless the direct import is right around the corner, I suggest not waiting on it. The current workaround seems viable enough.

    Or am I missing something? Is it not possible today to use ctr.From() with a registry service (http URL)?

  5. vikram-dagger commented on Dec 5, 2023

    @vikram-dagger
    Contributor

    @vito mentioned that This still needs a bit more plumbing: namely we need container Publish and From to support services.

    Does that change anything @helderco ? In any case, I will try it and update here.

  6. helderco commented on Dec 6, 2023

    @helderco
    ContributorAuthor

    Does that change anything @helderco ?

    Yes, that answers my last question that's not possible to use ctr.From() with a registry service. Surprised about Publish since we have examples with localhost:5000 for example and thought the same would work for From but haven't tried it.

  7. helderco commented on Dec 14, 2023

    @helderco
    ContributorAuthor

    @vikram-dagger I've updated the description with a single example. Even though we can't use a service directly in Container.from yet, the workaround above is usable and shareable. Can even be put in a module (cc @kpenfound).

    As you can see, those setup steps using the docker CLI can be entirely automated in dagger, in a way that avoids conflicts (random ports, volume and container names, etc).

    The opposite Load Container Images into a Local Docker Engine guide has some of the commands in the above example as manual steps for the user. It can be updated to do it entirely with dagger in an automated way as well.

  8. jedevc commented on Jul 29, 2025

    @jedevc
    Contributor

    I suspect the idea behind this use case would be fixed by #10810?

    @helderco does that sound right to you? Beyond the need to add some docs.

  9. helderco commented on Jul 29, 2025

    @helderco
    ContributorAuthor

    I suspect the idea behind this use case would be fixed by #10810?

    Yes, this issue was to document the workaround but if there's a more direct way to do it this would not be necessary.

  10. linked a pull request that will close this issueci: improve version module performance #10801on Jul 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area/documentation

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions