Just posting if anyone comes on this page looking to understand.
you can checkout this https://github.com/awslabs/amazon-ecr-credential-helper?tab=readme-ov-file
you can install amazon-ecr-credentials-helper on ec2 and configure ~/.docker/config.json to use this