iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🫙

Using cdk-docker-image-deployment to Deploy Docker Images to Any ECR Repository

に公開
2026/08/18

Introduction

I discovered that a CDK library called CDK Docker Image Deployment (cdk-docker-image-deployment) has been released.

This allows Docker images configured with CDK to be stored in any repository, and it seems to have been created with the expectation of being officially incorporated into aws-cdk-lib in the future.

In this post, I would like to try using this library while walking through the problems it can solve.

Problems When Building and Pushing Docker Images to ECR with CDK

Building & Pushing Images with ContainerImage.fromAsset

For example, suppose you have application and CDK code in a single project as shown below.

.
├── app
│   ├── Dockerfile
│   └── index.js
└── cdk
    ├── bin
    ├── cdk.json
    ├── cdk.out
    ├── jest.config.js
    ├── lib
    ├── node_modules
    ├── package-lock.json
    ├── package.json
    └── tsconfig.json

When you want to build an application's Docker image with CDK and run it on ECS, the easiest way is to use ContainerImage.fromAsset to build a Docker image from a local path and utilize aws_ecs_patterns constructs.

//**************************************************** */
// Task Definition
//**************************************************** */
const taskDefinition = new ecs.FargateTaskDefinition(
  this,
  "TaskDefinition",
  {
    runtimePlatform: {
      operatingSystemFamily: ecs.OperatingSystemFamily.LINUX,
      cpuArchitecture: ecs.CpuArchitecture.ARM64,
    },
  }
);

// Add container to task definition
taskDefinition.addContainer("AppContainer", {
  image: ecs.ContainerImage.fromAsset(
    path.resolve(__dirname, "../..", "app")
  ),
  portMappings: [
    {
      containerPort: 3000,
    },
  ],
});

//**************************************************** */
// ECS Fargate Service
//**************************************************** */
new ecsPatterns.ApplicationLoadBalancedFargateService(this, "Service", {
  taskDefinition,
  vpc,
});

Deploying this will execute the application image build and deployment to ECS at the same time the CDK resources are deployed. This is the expected behavior so far.

However, where is the built image being pushed?

Looking at ECR, a repository with a name like cdk-hogehoge-container-assets-000000000000-ap-northeast-1 is automatically created, and the image tag is a random string.

In other words, images created with ContainerImage.fromAsset are intended to be used only within the CDK process flow. Since it is extremely difficult to identify the image, it cannot be reused.

This is a specification intended to allow deployment without having to be conscious of the image storage location. While this might be sufficient for very small projects, it is a somewhat scary mechanism for production use when considering things like emergency rollbacks.

Building & Pushing Images with DockerImageAsset

So, what if we configure it to create an ECR repository in advance and push to it?

The code would look something like the following. By the way, I'll mention upfront that this code is actually meaningless.

const repository = new ecr.Repository(this, "Repository", {
  repositoryName: "example-repository",
});

const dockerImageAsset = new ecrAssets.DockerImageAsset(
  this,
  "DockerImageAsset",
  {
    directory: path.join(__dirname, "../..", "app"),
  }
);

// Omitted

// Add container to task definition
taskDefinition.addContainer("AppContainer", {
  image: ecs.ContainerImage.fromEcrRepository(repository),
  portMappings: [
    {
      containerPort: 3000,
    },
  ],
});

If you look closely at the code, you'll notice something wrong: the image built and pushed with DockerImageAsset is not used anywhere. If you deployed this as-is, the task startup in ECS would keep failing because the image pushed to example-repository does not exist.

Ideally, we want the image built with DockerImageAsset to be pushed to the ECR repository configured with the Repository construct, and have ECS use that image. However, since DockerImageAsset does not allow specifying an ECR repository name or tags, we can't achieve what we want. We're stuck...

The cdklabs/cdk-ecr-deployment Library

To address this problematic situation, cdklabs/cdk-ecr-deployment was created.

This library is also mentioned in the official CDK documentation, which explains that the current behavior is by design and that cdklabs/cdk-ecr-deployment can be used as a tool to work around it.

DockerImageAsset is designed for seamless build & consumption of image assets by CDK code deployed to multiple environments through the CDK CLI or through CI/CD workflows. To that end, the ECR repository behind this construct is controlled by the AWS CDK. The mechanics of where these images are published and how are intentionally kept as an implementation detail, and the construct does not support customizations such as specifying the ECR repository name or tags.

If you are looking for a way to publish image assets to an ECR repository in your control, you should consider using cdklabs/cdk-ecr-deployment, which is able to replicate an image asset from the CDK-controlled ECR repository to a repository of your choice.

Using cdklabs/cdk-ecr-deployment allows you to copy an image to any ECR repository, making it possible to treat the destination repository as a managed resource. In CDK code, the process looks like the following added section:

const repository = new ecr.Repository(this, "Repository", {
  repositoryName: "example-repository",
});

const dockerImageAsset = new ecrAssets.DockerImageAsset(
  this,
  "DockerImageAsset",
  {
    directory: path.join(__dirname, "../..", "app"),
  }
);

// !! Added: cdk-ecr-deployment !!
new ecrdeploy.ECRDeployment(this, "DeployDockerImage", {
  src: new ecrdeploy.DockerImageName(dockerImageAsset.imageUri),
  dest: new ecrdeploy.DockerImageName(
    `${awsAccount}.dkr.ecr.ap-northeast-1.amazonaws.com/example-repository:latest`
  ),
});

// Omitted

// Add container to task definition
taskDefinition.addContainer("AppContainer", {
  image: ecs.ContainerImage.fromEcrRepository(repository, "latest"),
  portMappings: [
    {
      containerPort: 3000,
    },
  ],
});

This works as expected. Because cdklabs/cdk-ecr-deployment copies the image to example-repository, container deployment to ECS can be achieved using that specific image.

While I am using latest as the tag here, you could also devise a way to set something like a Git commit hash as the tag to facilitate rollbacks.

Problem solved!

And Now, cdk-docker-image-deployment

...Well, that was a long introduction. Finally, we get to the main topic.

Recently, while looking at an issue regarding the challenges discussed in this article, I came across this comment:

https://github.com/aws/aws-cdk/issues/12597#issuecomment-1243879965

It appears that a new library called cdk-docker-image-deployment has been created to solve the same problems as cdklabs/cdk-ecr-deployment.

https://github.com/cdklabs/cdk-docker-image-deployment

Although it is currently a project under cdklabs, it is maintained by the CDK team. They mentioned that if it proves popular, they will consider including it in the main aws-cdk-lib.

I just had to give it a try.

Trying it out

For now, I'll follow the instructions in the README.

const repository = new ecr.Repository(this, "Repository", {
  repositoryName: "example-repository",
});

new imagedeploy.DockerImageDeployment(
  this,
  "ExampleImageDeploymentWithTag",
  {
    source: imagedeploy.Source.directory(
      path.join(__dirname, "../..", "app")
    ),
    destination: imagedeploy.Destination.ecr(repository, {
      tag: "myspecialtag",
    }),
  }
);

// Omitted

// Add container to task definition
taskDefinition.addContainer("AppContainer", {
  image: ecs.ContainerImage.fromEcrRepository(repository, "myspecialtag"),
  portMappings: [
    {
      containerPort: 3000,
    },
  ],
});

First of all, I like how the code is much cleaner with significantly less boilerplate. Also, while cdklabs/cdk-ecr-deployment required specifying the destination as a string, this API accepts a Repository class, which is a great plus because TypeScript's type checking now works.

As for the results, it worked exactly as expected. Specifically, configuring an ECR repository with CDK, tagging and pushing the built image to that repository, and then deploying that image as an ECS container—all within a single CDK deployment—is now possible.

The README provides details on the internal mechanics, but essentially, a CodeBuild project plays a central role by performing docker pull from the source and docker push to the destination to copy between ECR repositories. Checking CodeBuild after the deployment, I found that a build project had indeed been created just for that purpose.

Conclusion

With the official release of cdk-docker-image-deployment, using ECS with CDK has become even easier. I feel that deploying applications via CDK for production use has become a more realistic option. I would really like to see this included in aws-cdk-lib.

On the other hand, since it is a brand-new project, there might be breaking changes or potential issues in the future. In fact, when I first tried it, I ran into a syntax error when copying and pasting the sample code from the README (so I submitted a pull request for that). That said, unless many people use it and provide feedback, it won't be incorporated into the main library. So, I plan to use it actively from now on. I encourage everyone to give it a try.

Finally, here is the sample CDK code I used for this experiment:

https://github.com/5t111111/docker-image-deployment-example

Discussion