Dealing with DockerHub rate limit on AWS CodeBuild

Docker pulls has a rate-limit of 100-200 pulls per six hours. This limit exceeds much faster than you think.
February 12, 2024
Docker on AWS CodeBuild sometimes gives the following error.
429 Too Many Requests - Server message: toomanyrequests: You have reached your pull rate limit. You may increase the
limit by authenticating and upgrading: https://www.docker.com/increase-rate-limit
According to the link given in the error, it should reset every 6 hours. However, in my case it didn't reset even after 12 hours. An AWS blog post recommends two ways to deal with this situation.
  1. Copying Docker Images to ECR Private Repositories
  2. Consideration of Paid Docker Plans
Let's delve into the first method:

Step 1: Transferring Docker Image to ECR Private Repository

Login to the AWS console and start the CloudShell (located in the top navigation bar). Then execute the following commands one by one. Make sure to update the image name, AWS account ID, and the platform parameter before doing that. $AWS_DEFAULT_REGION resolves to your current AWS region in the CloudShell.
IMAGE_NAME=node:20-alpine
AWS_ACCOUNT_ID=XXXXXX
 
aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com
 
docker pull --platform linux/arm64 $IMAGE_NAME
 
docker tag $IMAGE_NAME $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_NAME
 
docker push $AWS_ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com/$IMAGE_NAME
For more details, refer to the AWS documentation.

Step 2: Adjusting Dockerfile Configuration

In your Dockerfile, replace FROM node:20-alpine with the following line:
FROM <AWS_ACCOUNT_ID>.dkr.ecr.us-west-2.amazonaws.com/node:20-alpine
# Include remaining Dockerfile instructions

Step 3: Updating CodeBuild Service Role

Ensure the CodeBuild service role has the arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly policy attached.
Here's an example using Terraform:
resource "aws_iam_role_policy_attachment" "code_build_ecr_read_policy_attachment" {
  policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ContainerRegistryReadOnly"
  role       = aws_iam_role.<your_code_build_service_role>.name
}
With these steps completed, you've successfully mitigated Docker pull rate limits on AWS CodeBuild.