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.


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/
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
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.


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.

provider aws {}

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

output "Registry URL" {
value ="${}"

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.


Registry URL =

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

$ docker push
The push refers to repository []
d63a57e20557: Pushed
aec196387489: Pushed
071d8bd76517: Pushed

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