Skip to content

Repository files navigation

Docker.js

It is a library used to manipulate Docker containers, images and all interfaces that can be managed by the Docker Engine.

Zero dependency, no usage of shell calls, everything implemented in the finest manner and in the most secure way possible.

How to use

The entrypoint of this library is the DockerSocket object. It has to be instantiated given a UNIX socket (the one used by the Docker Engine) as well as the API hostname.

// index.tsimport{DockerSocket}from"@hallmaster/docker.js";(asyncfunction(){constsocket=newDockerSocket();awaitsocket.init();// prepare the UNIX socket to be used// get the information about the API (Docker Engine's version, ...)console.log(awaitsocket.info());})();

Once you have instantiated the DockerSocket object and initialized it with the init() method, you are ready to use it everywhere.

Containers

To fetch data from containers, you may use this snippet :

import{DockerContainersAPI,DockerSocket}from"@hallmaster/docker.js";asyncfunctionsleep(ms: number): Promise<void>{returnnewPromise<void>((resolve)=>setTimeout(resolve,ms));}(asyncfunction(){constsocket=newDockerSocket();awaitsocket.init();constdockerContainersApi=newDockerContainersAPI(socket);constcontainers=awaitdockerContainersApi.list();for(constcontainerofcontainers){constcontainerLogs=awaitdockerContainersApi.logs(container.Id,{stdout: true,stderr: true,});console.log("-----------");console.log(`Logs for the container #${container.Id}`);console.log(containerLogs);console.log("-----------");}constcreatedContainer=awaitdockerContainersApi.create({Image: "redis:8.2.1-bookworm",Labels: {"@hallmaster/docker.js": "true",},},"redis-container",);for(constwarningofcreatedContainer.Warnings){console.warn(`[CONTAINER WARNING]: ${warning}`);}awaitdockerContainersApi.start(createdContainer.Id);awaitsleep(2000);constlogs=awaitdockerContainersApi.logs(createdContainer.Id,{stderr: true,stdout: true,});console.log("--- REDIS TEST CONTAINER LOGS BEGIN ---");console.log(logs);console.log("--- REDIS TEST CONTAINER LOGS END ---");constoneShotStats=awaitdockerContainersApi.stats(createdContainer.Id,{stream: false,});console.log(oneShotStats.memory_stats.usage);conststatsStream=awaitdockerContainersApi.stats(createdContainer.Id,{stream: true,});statsStream.on("data",(stats)=>{console.log(`cpu=${stats.cpu_stats.cpu_usage.total_usage}`);});awaitsleep(5000);statsStream.destroy();console.log("Killing test container");awaitdockerContainersApi.kill(createdContainer.Id);console.log("Test container killed");console.log("Removing test container");awaitdockerContainersApi.remove(createdContainer.Id);console.log("Test container removed");constavailableContainers=awaitdockerContainersApi.list({all: true});constisAnyContainerMatchingTestContainer=availableContainers.filter((container)=>container.Id===createdContainer.Id,);if(isAnyContainerMatchingTestContainer.length===1){console.error("The test container has not been remove properly");}})();

Images

To create an image, you would use something similar to this :

import{DockerImagesAPI,DockerRegistryCredential,DockerSocket,}from"@hallmaster/docker.js";import{pack}from"tar-fs";// create a Readable tarball for build context(asyncfunction(){constsocket=newDockerSocket();awaitsocket.init();constdockerImagesApi=newDockerImagesAPI(socket);constimageName="dockerjs-test-image";consttag="latest";// create the Readable build contextconstbuildContext=pack("./test/context");// build the imageawaitdockerImagesApi.build(buildContext,[],{tag: `${imageName}:${tag}`,});// lookup all imagesconstimages=awaitdockerImagesApi.list({all: true,});// checks the image has been built properlyconstdockerjsTestImage=images.filter((image)=>image.RepoTags.includes(`${imageName}:${tag}`),);if(dockerjsTestImage.length===0){console.error("The Docker.js test image has not been built properly");return;}constregistryCredential: DockerRegistryCredential={serveraddress: "localhost:5001",username: "admin",password: "password",};consttaggedImageName=`${registryCredential.serveraddress}/${registryCredential.username}/${imageName}`;// tag the imageawaitdockerImagesApi.tag(imageName,{repo: taggedImageName,tag: tag,});// push the imageawaitdockerImagesApi.push(taggedImageName,{tag: tag,auth: registryCredential,});// remove the image for test cleanupfor(constimageNameToDeleteof[imageName,taggedImageName]){constdeletedImages=awaitdockerImagesApi.remove(imageNameToDelete,{force: true,noPrune: false,});// make sure the image has been deletedconsthasBeenDeleted=deletedImages.filter((deleted)=>Object.keys(deleted).includes("Untagged")&&Object.keys(deleted).includes(imageNameToDelete),);if(!hasBeenDeleted){console.error("The Docker.js test image has not been removed properly");return;}}// pull an image from remote registryawaitdockerImagesApi.create({fromImage: "nginx",tag: "latest",});// pull an image from remote private registryawaitdockerImagesApi.create({fromImage: taggedImageName,auth: registryCredential,});})().catch((e)=>{throwe;});

If you want to try to push the image to a registry, use the service located in the docker-compose.yml file. It will setup a local registry.

Then, use this command to setup the credentials inside :

docker run --rm --entrypoint htpasswd httpd:2 -Bbn admin password > auth/htpasswd

By default, username is admin and password is password. Obviously, this is not secure, it's for demonstration purpose only. Also, identitytoken-based authentication will not work, use the username/password and serveraddress authentication, as in the provided example

Contributors

To contribute, there is a docker-compose.yml file at the root of the project which contains a service called openapi-server. It's a web server listening on port 8080 which hosts the OpenAPI specs of the REST endpoints of the Docker Engine. It's an ease for development.

About

TypeScript Docker Engine API wrapper in order to manipulate containers, images, networks, volumes, logs, and so on.

Topics

Resources

Stars

6 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages