Amazon ECR with Terraform

The docker build command builds Docker images from a Dockerfile that you can store in the docker registry and run containers.

Dockerfile

A Dockerfile is a text document that contains all the commands a user could execute on the command line and add application code and configurations to assemble an image.

Dockerfile must start with a ‘FROM’ instruction that specifies the Base Image from which you are building.

Dockerfile example

FROM centos:7
RUN yum update && yum install httpd httpd-tools -y
ADD website/* /var/www/html/
EXPOSE 80
CMD ["/usr/sbin/httpd","-D","FOREGROUND"]

Building image

$ docker build -t mywebsite .

The above command creates a mywebsite image from docker file exists in the current directory. We can check images exists locally with ‘docker images’ command.

$ docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
mywebsite latest afbc42e98787 2 minutes ago 305MB
centos 7 1e1148e4cc2c 4 weeks ago 202MB
$ docker run --name website -d -p 8080:80 mywebsite

Registry :

The Registry is a stateless, highly scalable server-side application that stores and lets you distribute Docker images.

You can store your images in either your own private registry or registry provided by cloud services. All major cloud provider offers docker registry to store securely and to distribute among the team members.

AWS ECR

Amazon Elastic Container Registry (ECR) is a fully-managed Docker container registry that makes it easy for developers to store, manage, and deploy Docker container images.

Create ECR

The “aws_ecr_repository” resource allows you to create container registry on AWS.

ecr.tf

provider aws {}

resource "aws_ecr_repository" "website" {
name = "mywebsite"
}

output "Registry URL" {
value ="${aws_ecr_repository.website.repository_url}"
}

Run terraform init and apply commands. It will create a registry and displays the URL as below.

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.

Outputs:

Registry URL = 464890032310.dkr.ecr.us-east-1.amazonaws.com/mywebsite

Pushing images to ECR

We can push images to ECR using ‘docker push’ command. Before that, we have to log in to the repository with docker login command and we need to tag the image with repository URL.

To get login credentials for ECR, use ‘aws ecr get-login’ command. Copy and paste the entire output and log in.

Tag the image with registry URL and run docker push command as follows:

$ docker tag mywebsite:latest 464890032310.dkr.ecr.us-east-1.amazonaws.com/mywebsite:1.0

$ docker push 464890032310.dkr.ecr.us-east-1.amazonaws.com/mywebsite:1.0
The push refers to repository [464890032310.dkr.ecr.us-east-1.amazonaws.com/mywebsite]
d63a57e20557: Pushed
aec196387489: Pushed
071d8bd76517: Pushed

You can verify that the image is pushed to ECR in AWS console.

ECR_Image.PNG

 

Advertisements

Learn Technology

%d bloggers like this: