docker.ts
Overview
The [docker.ts](/projects/291/68797) file provides utility functions for automating Docker image lifecycle operations, specifically building, tagging, caching, and pushing images to Docker registries. It streamlines and standardizes how container images are created and deployed by:
Logging into Docker registries programmatically.
Building Docker images with customizable build arguments, multi-tag support, and caching optimizations.
Pushing multiple tags of the built images to a Docker registry.
Checking remotely if a particular image tag already exists on Docker Hub to avoid redundant builds.
This file is a core part of the Docker Image Automation workflow, enabling efficient, repeatable, and reliable container image management in deployment pipelines, especially when integrated with Pulumi infrastructure-as-code deployments.
Exports
Interface: BuildAndPushImageArgs
Defines the arguments accepted by the `buildAndPushImage` function.
Property | Type | Description |
|---|---|---|
`auth` | `Dockerhub` | Authentication credentials for Docker Hub (username and password). |
`buildArgs?` | `Record` | Optional key-value pairs passed as `--build-arg` to customize Docker build. |
`env?` | `Record` | Optional environment variables injected during the Docker build process. |
`cacheFroms?` | `Array` | Optional list of images to use as cache sources (`--cache-from`). |
`context` | `string` | Build context directory for Docker (path where Dockerfile and source files reside). |
`dockerFile?` | `string` | Optional path to a Dockerfile to use instead of the default `Dockerfile`. |
`image` | `string` | Name of the Docker image to build (without tag). |
`tags?` | `Array` | Optional list of tags to apply to the image. Defaults to `latest` if omitted. |
Function: buildAndPushImage(args: BuildAndPushImageArgs): Promise<void>
Builds a Docker image with specified options, tags it with one or more tags, and pushes all tags to the Docker registry.
Parameters
args: BuildAndPushImageArgs: Configuration object specifying authentication, build context, tags, cache, and environment variables.
Returns
Promise<void>: Resolves when the build and push process completes.
Behavior and Implementation Details
Docker Login:
Executes docker login using provided credentials (
args.auth) to authenticate with the Docker registry.Errors are suppressed by redirecting stderr to
/dev/null.
Tag Preparation:
Builds a list of image tags to assign.
If args.tags is provided, each tag is prefixed with the image name (
image:tag).Ensures the
latesttag is included if not explicitly provided.If no tags are specified, defaults to a single
latesttag.
Docker Build Arguments:
Starts with tags (
-t image:tag) for all tags.Adds build arguments (
--build-arg key=value) fromargs.buildArgs.Adds caching options (
--cache-from image) forargs.cacheFroms.Specifies Dockerfile location if args.dockerFile is set (
-f Dockerfile).Appends the build context directory.
Environment Variables:
Converts args.env key-value pairs into a single string of environment variable assignments prepended to the
docker buildcommand.
Docker Build Execution:
Runs the assembled
docker buildcommand with--pull(to always pull latest base images) and targets platformlinux/amd64.Uses
execSyncwithstdio: 'inherit'so build logs stream to the console.
Push to Registry:
Unless Pulumi is in a dry-run mode (
pulumi.runtime.isDryRun()), pushes each tagged image (docker push image:tag).
Usage Example
import { buildAndPushImage } from './docker'
import { Dockerhub } from '.'
const auth: Dockerhub = { username: 'user', password: 'pass' }
await buildAndPushImage({
auth,
context: './app',
image: 'user/my-app',
tags: ['v1.0.0', 'stable'],
buildArgs: { NODE_ENV: 'production' },
env: { API_URL: 'https://api.example.com' },
cacheFroms: ['user/my-app:latest'],
dockerFile: 'Dockerfile.prod'
})
Function: hasTag(repository: string, tag: string): Promise<boolean>
Checks if a Docker image tag exists on Docker Hub.
Parameters
repository: string: The Docker Hub repository name (e.g.,username/my-image).tag: string: The tag name to check for existence (e.g.,v1.0.0).
Returns
Promise<boolean>: Resolves totrueif the tag exists;falseotherwise.
Implementation Details
Sends a GET request to Docker Hub's tags API endpoint:
https://hub.docker.com/v2/repositories/{repository}/tags/{tag}If the request succeeds (status 200), returns
true.If the request fails (e.g., 404 Not Found), returns
false.
Usage Example
const exists = await hasTag('user/my-app', 'v1.0.0')
if (!exists) {
// Build and push the image since tag does not exist
}
Important Implementation Notes
Synchronous Shell Commands: Uses Node.js
execSyncto run Docker CLI commands synchronously, ensuring sequential execution and output streaming.Tag Management: Automatically manages multiple tags per build, always including a
latesttag if not specified explicitly.Caching: Supports Docker layer caching by passing
--cache-fromimages to speed up builds.Pulumi Integration: Skips pushing images during Pulumi dry runs (preview mode) to avoid side effects.
Error Handling: Minimal explicit error handling; failures in shell commands will throw exceptions, expected to be caught upstream.
Environment Variables: Injects environment variables inline before the
docker buildcommand, influencing build-time behavior.
Integration with Other System Components
Dockerhub Interface: Uses a
Dockerhubtype (imported from the current directory) for authentication credentials, indicating a larger system managing Docker registry access.Pulumi Infrastructure as Code: The file checks Pulumi runtime mode (
isDryRun) to conditionally skip pushing images during previews, showing tight integration with deployment pipelines managed by Pulumi.Deployment Automation: This file is a utility module that higher-level deployment scripts or Pulumi programs invoke to ensure container images are built and available before deployment to Kubernetes or other orchestrators.
Docker CLI Dependency: Relies on the local environment having the Docker CLI installed and configured.
Visual Diagram
classDiagram
class BuildAndPushImageArgs {
+auth: Dockerhub
+buildArgs?: Record<string, string>
+env?: Record<string, string>
+cacheFroms?: Array<string>
+context: string
+dockerFile?: string
+image: string
+tags?: Array<string>
}
class buildAndPushImage {
+async(args: BuildAndPushImageArgs): Promise<void>
}
class hasTag {
+async(repository: string, tag: string): Promise<boolean>
}
buildAndPushImage ..> BuildAndPushImageArgs : uses
buildAndPushImage ..> Dockerhub : uses auth
hasTag ..> "Docker Hub API" : queries tag existence
Summary
The [docker.ts](/projects/291/68797) file is a focused utility module that automates Docker image build, tagging, caching, and push operations with support for multiple tags and build-time customization. Through synchronous Docker CLI invocations and integration with Pulumi, it fits seamlessly into deployment pipelines requiring robust container image management. The remote tag existence check via Docker Hub API further optimizes workflows by preventing unnecessary rebuilds and uploads, saving resources and time. This module is foundational for orchestrating consistent and efficient container deployments within the broader system infrastructure.