Skip to content

Launch ECS container using AWS CLI - Step 3 - Create Docker Image

Setup an ECS container repository, create a Docker image, and upload the Docker image to the repository.

This is part of a multi-post thread involving these steps:

  1. Network Setup
  2. Launch EC2 Instance
  3. Create Docker Image (this post)
  4. Create Service
  5. Cleanup

Define names

# registry (in the form $registryId.dkr.ecr.$region.amazonaws.com)
region=$(aws configure get region)
registryId=$(aws ecr describe-registry | jq -r '.registryId')
registry="$registryId.dkr.ecr.$region.amazonaws.com"

# image
image="ecs-test"
tag="latest"

Create ECS Repository

echo "Create repository $image in registry $registry ..."
aws ecr create-repository --repository-name $image
repository=$(aws ecr describe-repositories | jq -r ".repositories[] | select(.repositoryName==\"$image\") | .repositoryUri")

Create Docker Image

Dockerfile

Create a Dockerfile with the following contents:

cat << "EOT" > ./Dockerfile
# See https://hub.docker.com/_/oraclelinux for all supported 
# Oracle Linux categories from Docker Hub.

# this image will be the actual running container
FROM  oraclelinux:8

LABEL Name=ecs-test

## System Config
ENV TZ=America/Los_Angeles

# Packages
RUN yum -y install bind-utils 

CMD ["/bin/ping", "localhost"]
EOT

Build Image

echo "Build image ..."
docker build --tag ${image}:${tag} .

Tag Image

echo "Tag image ..."
docker tag ${image}:${tag} ${repository}:${tag}

Publish Image

# refresh AWS token for docker
aws ecr get-login-password --region $region \
  | docker login --username AWS --password-stdin $registry

# push image
echo "Push image ..."
docker push ${repository}:${tag}

Verify

# verify
red='\e[0;31m'    
green='\e[0;32m'    
clear='\e[0m'

pushed_tag=$(reg categories ${repository} | grep "${tag}")
if [ "${pushed_tag}" != "${tag}" ]; then
    printf "${red}Failed${clear}"; echo
else    
    printf "${green}Success${clear}"; echo
fi