Repository navigation
Closed
Labels
area/documentationImprovements or additions to documentation
Description
Summary
Improve the registry workaround in the Load Container Images Into a Local Docker Engine guide using similar approach in 📖 Add import image from docker guide.
Rationale
Even though we don't have the plumbing to use a service in Container.publish yet, we can automate it all in dagger rather than providing manual steps for the user to run docker commands.
There's a big red warning that this approach is not recommended due to its complexity but I think that’s because of the manual steps required. However, those steps can be automated with dagger and shared/reused.
Example
In Python:
import contextlib
import uuid
import anyio
import dagger
from dagger import dag
IMAGE_NAME = "my-nginx"
async def main(img: str = IMAGE_NAME):
async with dagger.connection():
async with docker_image(img) as ref:
await (
dag.container()
.from_("nginx:alpine")
.with_new_file(
"/usr/share/nginx/html/index.html",
contents="Hello from Dagger!\n",
permissions=0o400,
)
.publish(ref)
)
ls = await docker("image", "ls", "-f", f"reference={img}")
print("Image is now available in the host's docker daemon:")
print(ls)
@contextlib.asynccontextmanager
async def docker_image(target: str):
"""Context manager to load a container into 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.
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 dagger engine's network so we can publish to it.
cid = await registry(vid, "--network", f"container:{ctr_name}")
# Yield the image reference to publish to.
try:
yield f"127.0.0.1:5000/{target}"
finally:
await docker("stop", cid)
# Run a registry in the host's network so we can pull the image from.
# 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]
# Pull and make a new tag to remove the registry URL.
source = f"127.0.0.1:{port}/{target}"
await docker("pull", source)
await docker("tag", source, target)
await docker("image", "rm", source)
# Cleanup. We don't need the volume anymore.
await docker("stop", host_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)Should output:
❯ dagger run python main.py
Image is now available in the host's docker daemon:
REPOSITORY TAG IMAGE ID CREATED SIZE
my-nginx latest 2e3b4f191c52 About a minute ago 43.4MBTry it:
❯ cid=$(docker run -d --rm -p 8001:80 my-nginx)
❯ curl localhost:8001
Hello from Dagger!
❯ docker stop $cid\cc @vikram-dagger
Metadata
Metadata
Assignees
Labels
area/documentationImprovements or additions to documentation
Activity
[-]📖 Update import image from docker guide[/-][+]📖 Update load image into docker guide[/+]helderco commentedon Dec 14, 2023
Of course, the logic in this workaround can be encapsulated in a module.
marcosnils commentedon Dec 17, 2023
I was casually thinking about this the other day and another approach with less moving parts could be just calling
AsTarballhttps://pkg.go.dev/dagger.io/dagger#Container.AsTarball within the pipeline and then by mounting the docker socket performing adocker loadanddocker tagrespectively. This will be probably be a bit slower for large images but it might be worth as it's simpler than the two registry dance approach.helderco commentedon Dec 17, 2023
Yes, good tip. The referred guide has two approaches: tar export and registry. I just mentioned updating the registry approach but the tar export also has a manual step in the end and that could also be more automated with
AsTarball.With the registry I actually meant the opposite in that the added complexity is worth it for better performance, especially if only one person needs to update the implementation when the plumbing for services lands.
marcosnils commentedon Dec 18, 2023
gotcha, totally makes sense. For fun I just created a dagger module with the
AsTarballapproach and it was quite straightforward to achieve: https://daggerverse.dev/mod/github.com/marcosnils/daggerverse/docker@dc54f5f13362aee50b8be69bc1676e943cb46dbf. I guess another performance gain about this approach vs the current tar export is that the tar file doesn't need to be streamed streamed back to the host, so maybe we can replace the current tar solution with this one.helderco commentedon Dec 18, 2023
Totally agree! I'll update the description here to include that when I'm back from PTO. Also want to make a module for the registry approach 🙂