None
None

Reputation: 2433

How to pull ECS docker image from an EC2 instance?

What is the best practice to pull a Docker image located in a repository in ECS from an EC2 instance?

I am used to take advantage of the ECS task. To just run a Docker container for 5min, I need to go to Auto-Scale, set the minimum at 1, go to the ECS page, wait for an instance to be up and run my task. Too annoying for my personal use. I'd like to run it quickly and stop it quickly.

I wanted to simply run my Docker container but ok, that's not possible, then I am thinking of creating an EC2 template that will directly run my Docker container inside an EC2 instance.

I think my need is very basic and I couldn't find the best way to do it. Blog articles mainly explain how to run Docker on Linux, not the best way to do it on AWS.

Upvotes: 18

Views: 23710

Answers (1)

Kunal Nagpal
Kunal Nagpal

Reputation: 891

This can be accomplished with a combination of the EC2 instance role, and a script that performs docker login followed by a docker pull for your pushed image.

Pre-requisites: An EC2 instance with the AWS CLI and Docker installed.

First, you'll have to add the inbuilt AmazonEC2ContainerRegistryReadOnly IAM policy to your EC2 instance's IAM role (this grants read access to all pushed images). If you'd like things to be more restrictive, you can use the following policy instead:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "GrantSingleImageReadOnlyAccess",
      "Effect": "Allow",
      "Action": [
        "ecr:BatchCheckLayerAvailability",
        "ecr:GetDownloadUrlForLayer",
        "ecr:GetRepositoryPolicy",
        "ecr:DescribeRepositories",
        "ecr:ListImages",
        "ecr:DescribeImages",
        "ecr:BatchGetImage"
      ],
      "Resource": "<aws-account-id>.dkr.ecr.<region>.amazonaws.com/<image-name>"
    },
    {
      "Sid": "GrantECRAuthAccess",
      "Effect": "Allow",
      "Action": "ecr:GetAuthorizationToken",
      "Resource": "*"
    }
  ]
}

Next, you'll have to create a script to perform login and image pull for you. A typical script would look something like this:

aws ecr get-login-password --region <region> | docker login --username AWS --password-stdin <aws-account-id>.dkr.ecr.<region>.amazonaws.com;
docker pull <aws-account-id>.dkr.ecr.<region>.amazonaws.com/<image-name>:<optional-tag>;

Note that this script will have to run as the root user for proper Docker daemon access.

Another way of solving this altogether would be to look into automation options for ECS tasks.

Upvotes: 40

Related Questions