Docker With ECR

Install docker

  • Docker on EC2
$ sudo yum update -y
$ sudo amazon-linux-extras install docker
$ sudo service docker start
$ sudo usermod -a -G docker ec2-user
$ docker info
  • EC2 User Data
#! /bin/sh
yum update -y
amazon-linux-extras install docker
service docker start
usermod -a -G docker ec2-user
chkconfig docker on

Create image

  • sample docker file
FROM alpine
LABEL description="Running Docker from EC2"
WORKDIR /src
RUN echo "Hello world" > hello.txt
CMD ["cat", "hello.txt"]
  • Build the image
# build image
docker build -t alpine-tw .
docker build -t alpine-tw2 -f Dockerfile2 .

# List image
docker image list

REPOSITORY    TAG       IMAGE ID       CREATED         SIZE
alpine-tw     latest    07353d83c5d9   4 minutes ago   5.53MB
alpine        latest    d7d3d98c851f   12 days ago     5.53MB

# Run the image
docker run --name alpine-tw-test  alpine-tw

Push image to ECR

  • Create a EC2 role with access to ECR, and attach it to EC2
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "ecr:*",
      "Effect": "Allow",
      "Resource": "*"
    }
  ]
}
  • Create a repository in Amazon -> Repositoies or with command line
aws ecr create-repository --repository-name twtest --region us-east-1
  • Tag and push the image
# tag the image
docker tag alpine-tw {accountid}.dkr.ecr.us-east-1.amazonaws.com/twtest

# list images
docker image ls

REPOSITORY                                            TAG       IMAGE ID       CREATED          SIZE
{accountid}.dkr.ecr.us-east-1.amazonaws.com/twtest    latest    07353d83c5d9   36 minutes ago   5.53MB
alpine-tw                                             latest    07353d83c5d9   36 minutes ago   5.53MB
alpine                                                latest    d7d3d98c851f   12 days ago      5.53MB

# docker login
$(aws ecr get-login --no-include-email --region us-east-1)

WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your password will be stored unencrypted in /home/ec2-user/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

# push the image to repo
docker push {accountid}.dkr.ecr.us-east-1.amazonaws.com/twtest

# pull & run the imgage
docker pull {accountid}.dkr.ecr.us-east-1.amazonaws.com/twtest
docker run {accountid}.dkr.ecr.us-east-1.amazonaws.com/twtest

Reference