I made myself these utility functions for building & running a container locally. Mosty for testing containers before sending them to remote registery. Am I duplicating some dagger functionality? Can this be simplified?
async function runLocally() {
withDaggerClient(async client => {
const container = createContainer(client); // this runs several withExecs withDirectories etc eventually adds a withEntryPoint
const containerPath = await buildContainer({ runner: container });
console.log('containerPath', containerPath);
const imageId = await loadContainer({ path: containerPath });
console.log('imageId', imageId);
console.log('Running container');
await runContainer({
imageId,
port: PORT,
env: [
...ENV,
{
name: 'AUTH_CALLBACK_URL',
value: 'http://localhost:3000/auth/callback',
},
],
});
});
}
// basically runs container.sync then grabs the image path
export async function buildContainer({ runner }: { runner: Container }) {
const container = await runner.sync();
console.log('Container built');
const exportPath = `${os.tmpdir()}/${uuid()}.tar`;
const exported = await container.export(exportPath);
if (!exported) throw new Error('Failed to export image');
return exportPath;
}
// loads the image from the path from previous function, then grabs the id
export async function loadContainer({ path }: { path: string }) {
const dockerLoadResult = await $`docker load -i ${path}`;
const [, imageId] = dockerLoadResult.stdout.split('sha256:');
if (!imageId) throw new Error('Failed to determine imageId');
return imageId.trim();
}
type Env = { name: string; value: string };
// runs the container from image id with provided environment variables & port if applicable
export async function runContainer({
imageId,
port,
env = [],
}: {
imageId: string;
port: number;
env?: Env[];
}) {
let args: string[] = [];
args = env.reduce((args, { name, value }) => {
return [...args, '-e', `${name}=${value}`];
}, args);
try {
await $({
stdio: 'inherit',
})`docker run --rm ${args} -p ${port}:${port} ${imageId}`;
} catch (error) {
console.error('Failed while running container', error);
}
}