docker.ts
Overview
The [docker.ts](/projects/291/68795) file provides a utility function to automate the building and pushing of Docker images, specifically focusing on a base image variant. Its primary purpose is to:
Construct a Docker base image name based on a Dockerhub username and an image name.
Compute a unique base tag, typically a hash, to ensure image versioning and cache consistency.
Check if a Docker image with the given tag already exists on Dockerhub to avoid redundant builds.
If the tagged image does not exist, build and push the Docker image using custom build contexts, Dockerfiles, build arguments, environment variables, and caching strategies.
This file is a specialized helper within the broader Docker Image Automation system, ensuring efficient image creation workflows by leveraging remote tag existence checks and build caching.
Detailed Explanation
Imports
hasTag(from'../docker'): Async function to check if a Docker image tag exists remotely.buildAndPushImage(from'../docker'): Async function to build and push a Docker image with detailed options.getBaseHash(from'../hasher'): Async function that returns a hash string representing the current base image contents or state.Dockerhub(from'..'): Type or class representing Dockerhub authentication/connection credentials.
Function: buildAndPushDockerImages
export const buildAndPushDockerImages = async (dockerhub: Dockerhub, name: string) => {
...
}
Purpose
This asynchronous function orchestrates building and pushing a base Docker image tagged with a unique hash. It prevents unnecessary builds by checking if the image with the computed tag already exists.
Parameters
Parameter | Type | Description |
|---|---|---|
`dockerhub` | `Dockerhub` | Represents Dockerhub credentials and configuration used for authentication during push and build. |
`name` | `string` | Base name for the image; the function constructs the full image name as `${dockerhub.username}/${name}-base`. |
Behavior & Workflow
Construct Base Image Name:
The base image name is built as:
{dockerhub.username}/{name}-baseFor example, if
dockerhub.usernameis"alice"andnameis"blockchain-node", the base image would be"alice/blockchain-node-base".Calculate Base Tag:
Calls
getBaseHash()to get a unique hash representing the base image version. This hash is typically content-based and ensures reproducibility and cache consistency.Check Remote Tag Existence:
Uses
hasTag(baseImage, baseTag)to verify if the image with the computed tag already exists on the Docker registry.Conditional Build and Push:
If the tag does not exist, it triggers
buildAndPushImage()with the following options:image: The full base image name.
context: Relative path
'../../..'indicating the Docker build context directory.dockerFile: Relative path
'../../../Dockerfile.node'specifying the Dockerfile to use.auth: Dockerhub credentials for authentication.
buildArgs: Build argument
BUILDKIT_INLINE_CACHE=1to enable inline caching.env: Environment variable
DOCKER_BUILDKIT=1to enable BuildKit during build.tags: Array with the computed base tag.
cacheFroms: Array of images used for build caching, including the base image with current tag and the
latesttag.
Return Value
Returns a
Promise<void>indicating completion of the build and push operation (or skip if tag exists).
Usage Example
import { Dockerhub } from '..'
import { buildAndPushDockerImages } from './docker'
const dockerhub = new Dockerhub({ username: 'alice', token: '...' })
const imageName = 'blockchain-node'
await buildAndPushDockerImages(dockerhub, imageName)
// Builds and pushes alice/blockchain-node-base:<hash> if not already present
Important Implementation Details
Remote Tag Existence Check:
The function avoids redundant operations by querying Docker Hub or the configured registry for the existence of the image tag, saving build time and network usage.BuildKit Integration:
BuildKit is enabled both through environment variables and build arguments, allowing for advanced caching and performance optimizations.Cache Management:
ThecacheFromsoption references previous builds (<tag>andlatest) to reuse Docker layers and reduce build times.Deterministic Tagging:
The use ofgetBaseHash()ensures that image tags are content-based, promoting reproducible builds and consistent deployments.Context and Dockerfile Pathing:
Relative paths ensure the build context and Dockerfile are resolved correctly in relation to this script, important for multi-directory project structures.
Interaction with Other System Components
Docker Image Automation Utilities (
../docker):
This file depends heavily on utility functionshasTagandbuildAndPushImagefor core Docker registry interactions and build orchestration.Hasher Module (
../hasher):
ThegetBaseHashfunction provides deterministic tagging based on source contents or configurations, enabling cacheable and repeatable builds.Dockerhub Credentials (
..):
TheDockerhubobject abstracts authentication and configuration details required to push images to Docker registries.Deployment Pipelines / Infrastructure:
Higher-level deployment scripts or CI/CD pipelines invoke this function to ensure that base images are up-to-date and available for downstream container deployments.
Mermaid Diagram: Class and Function Structure
Since this file contains a single exported asynchronous function and uses imported utilities, a flowchart best illustrates its workflow and dependencies:
flowchart TD
A[Start: buildAndPushDockerImages(dockerhub, name)]
B[getBaseHash()]
C[Construct baseImage and baseTag]
D{Check if tag exists?}
E[Tag exists -> Skip build]
F[Tag missing -> Call buildAndPushImage()]
G[Build and push image with options]
H[End]
A --> B --> C --> D
D -- Yes --> E --> H
D -- No --> F --> G --> H
Summary
The [docker.ts](/projects/291/68795) file is a focused utility that encapsulates the logic needed to:
Determine whether a base Docker image for a given project and tag already exists.
Build and push the base image using an optimized Docker build process with caching and BuildKit.
Use content hashes for tagging to maintain reproducibility and efficient cache usage.
It is a critical part of the automated Docker image lifecycle within the overall deployment automation framework, interfacing with Docker registries and build tooling to streamline container image management.
**End of documentation for [docker.ts](/projects/291/68795).**