Docker Image Assets provide comprehensive functionality for building and deploying Docker images from local directories within AWS CDK applications. They handle Dockerfile-based builds with extensive customization options including build arguments, multi-stage builds, custom networking modes, and cross-platform compilation.
import { DockerImageAsset, DockerImageAssetProps, DockerImageAssetOptions, DockerImageAssetInvalidationOptions, NetworkMode, Platform } from "@aws-cdk/aws-ecr-assets";
import { IAsset } from "@aws-cdk/assets";
import { Construct } from "constructs";
import { Construct as CoreConstruct, CfnResource, FingerprintOptions, FileFingerprintOptions } from "@aws-cdk/core";
import * as ecr from "@aws-cdk/aws-ecr";Main construct for creating Docker image assets from local directories containing Dockerfiles.
/**
* An asset that represents a Docker image.
* The image will be created in build time and uploaded to an ECR repository.
*/
class DockerImageAsset extends CoreConstruct implements IAsset {
/**
* Creates a new Docker image asset
* @param scope - The scope in which to define this construct
* @param id - The scoped construct ID
* @param props - Configuration properties for the Docker image asset
*/
constructor(scope: Construct, id: string, props: DockerImageAssetProps);
/** The full URI of the image (including a tag). Use this reference to pull the asset. */
readonly imageUri: string;
/** Repository where the image is stored */
readonly repository: ecr.IRepository;
/** A hash of this asset, which is available at construction time */
readonly assetHash: string;
/** @deprecated use assetHash - A hash of the source of this asset */
readonly sourceHash: string;
/**
* Adds CloudFormation template metadata to the specified resource with
* information that indicates which resource property is mapped to this local asset
* @param resource - The CloudFormation resource which is using this asset
* @param resourceProperty - The property name where this asset is referenced
*/
addResourceMetadata(resource: CfnResource, resourceProperty: string): void;
}Usage Examples:
import { DockerImageAsset, NetworkMode, Platform } from "@aws-cdk/aws-ecr-assets";
import { Stack, Construct } from "@aws-cdk/core";
import path from "path";
// Basic Docker image asset
const basicImage = new DockerImageAsset(this, "BasicImage", {
directory: path.join(__dirname, "my-app")
});
// Image with build arguments
const imageWithArgs = new DockerImageAsset(this, "ImageWithArgs", {
directory: path.join(__dirname, "my-app"),
buildArgs: {
NODE_ENV: "production",
API_URL: "https://api.example.com"
}
});
// Multi-stage build with specific target
const multiStageImage = new DockerImageAsset(this, "MultiStageImage", {
directory: path.join(__dirname, "my-app"),
target: "production",
file: "Dockerfile.prod"
});
// Cross-platform build
const armImage = new DockerImageAsset(this, "ArmImage", {
directory: path.join(__dirname, "my-app"),
platform: Platform.LINUX_ARM64
});
// Custom networking mode
const hostNetworkImage = new DockerImageAsset(this, "HostNetworkImage", {
directory: path.join(__dirname, "my-app"),
networkMode: NetworkMode.HOST
});Configuration properties for DockerImageAsset construction.
/**
* Props for DockerImageAssets
*/
interface DockerImageAssetProps extends DockerImageAssetOptions {
/**
* The directory where the Dockerfile is stored
* Any directory inside with a name that matches the CDK output folder (cdk.out by default) will be excluded from the asset
*/
readonly directory: string;
}Extended configuration options for Docker image assets.
/**
* Options for DockerImageAsset
*/
interface DockerImageAssetOptions extends FingerprintOptions, FileFingerprintOptions {
/**
* ECR repository name
* Specify this property if you need to statically address the image, e.g.
* from a Kubernetes Pod. Note, this is only the repository name, without the
* registry and the tag parts.
*
* @deprecated to control the location of docker image assets, please override
* Stack.addDockerImageAsset. this feature will be removed in future releases.
* @default - the default ECR repository for CDK assets
*/
readonly repositoryName?: string;
/**
* Build args to pass to the `docker build` command.
* Since Docker build arguments are resolved before deployment, keys and
* values cannot refer to unresolved tokens (such as `lambda.functionArn` or `queue.queueUrl`).
* @default - no build args are passed
*/
readonly buildArgs?: { [key: string]: string };
/**
* Docker target to build to
* @default - no target
*/
readonly target?: string;
/**
* Path to the Dockerfile (relative to the directory).
* @default 'Dockerfile'
*/
readonly file?: string;
/**
* Networking mode for the RUN commands during build. Support docker API 1.25+.
* @default - no networking mode specified (the default networking mode NetworkMode.DEFAULT will be used)
*/
readonly networkMode?: NetworkMode;
/**
* Platform to build for. _Requires Docker Buildx_.
* @default - no platform specified (the current machine architecture will be used)
*/
readonly platform?: Platform;
/**
* Options to control which parameters are used to invalidate the asset hash.
* @default - hash all parameters
*/
readonly invalidation?: DockerImageAssetInvalidationOptions;
}Controls which parameters affect the asset hash calculation for cache invalidation.
/**
* Options to control invalidation of `DockerImageAsset` asset hashes
*/
interface DockerImageAssetInvalidationOptions {
/**
* Use `extraHash` while calculating the asset hash
* @default true
*/
readonly extraHash?: boolean;
/**
* Use `buildArgs` while calculating the asset hash
* @default true
*/
readonly buildArgs?: boolean;
/**
* Use `target` while calculating the asset hash
* @default true
*/
readonly target?: boolean;
/**
* Use `file` while calculating the asset hash
* @default true
*/
readonly file?: boolean;
/**
* Use `repositoryName` while calculating the asset hash
* @default true
*/
readonly repositoryName?: boolean;
/**
* Use `networkMode` while calculating the asset hash
* @default true
*/
readonly networkMode?: boolean;
/**
* Use `platform` while calculating the asset hash
* @default true
*/
readonly platform?: boolean;
}Defines networking modes for Docker builds.
/**
* networking mode on build time supported by docker
*/
class NetworkMode {
/** The default networking mode if omitted, create a network stack on the default Docker bridge */
static readonly DEFAULT: NetworkMode;
/** Use the Docker host network stack */
static readonly HOST: NetworkMode;
/** Disable the network stack, only the loopback device will be created */
static readonly NONE: NetworkMode;
/**
* Reuse another container's network stack
* @param containerId - The target container's id or name
*/
static fromContainer(containerId: string): NetworkMode;
/**
* Used to specify a custom networking mode
* Use this if the networking mode name is not yet supported by the CDK.
* @param mode - The networking mode to use for docker build
*/
static custom(mode: string): NetworkMode;
/** The networking mode to use for docker build */
readonly mode: string;
}Usage Examples:
// Use predefined networking modes
const defaultMode = NetworkMode.DEFAULT;
const hostMode = NetworkMode.HOST;
const noneMode = NetworkMode.NONE;
// Use another container's network
const containerMode = NetworkMode.fromContainer("my-container-id");
// Use custom networking mode
const customMode = NetworkMode.custom("bridge");Defines target platforms for Docker builds.
/**
* platform supported by docker
*/
class Platform {
/** Build for linux/amd64 */
static readonly LINUX_AMD64: Platform;
/** Build for linux/arm64 */
static readonly LINUX_ARM64: Platform;
/**
* Used to specify a custom platform
* Use this if the platform name is not yet supported by the CDK.
* @param platform - The platform to use for docker build
*/
static custom(platform: string): Platform;
/** The platform to use for docker build */
readonly platform: string;
}Usage Examples:
// Use predefined platforms
const amd64Platform = Platform.LINUX_AMD64;
const arm64Platform = Platform.LINUX_ARM64;
// Use custom platform
const customPlatform = Platform.custom("linux/riscv64");Docker Image Assets support extensive build configuration:
Build Arguments: Pass environment variables and configuration to Docker build process. Values must be resolved at synthesis time.
Multi-stage Builds: Use the target property to build specific stages in multi-stage Dockerfiles.
Custom Dockerfile: Specify alternative Dockerfile names with the file property.
Build Context: The entire directory specified in directory becomes the Docker build context, excluding CDK output directories.
Docker Ignore: Supports .dockerignore files for excluding files from build context.
The asset hash determines when images need rebuilding. Use invalidation options to control which parameters affect the hash:
const optimizedImage = new DockerImageAsset(this, "OptimizedImage", {
directory: path.join(__dirname, "my-app"),
buildArgs: {
BUILD_TIME: new Date().toISOString() // This changes every build
},
invalidation: {
buildArgs: false // Don't invalidate hash when buildArgs change
}
});Common errors and troubleshooting:
file path is relative to the directorydirectory path exists and is accessible