I have a parent directory containing multiple sub-directories. Each of these child directories is a different application and contains a Dockerfile.

I want to build and push each image to AWS ECR.

The directory looks as follows:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
├── apps
    ├── microservice1
        ├── app.js
        ├── Dockerfile
        ├── package.json
        └── readiness.txt
    ├── frontend
        ├── Dockerfile
        ├── index.html
        ├── package.json
        ├── server.js
    ├── microservice2
        ├── app.py
        ├── bootstrap.sh
        ├── Dockerfile
        └── requirements.txt

Notice there are 3 apps, each with their own Dockerfile, under the parent apps directory.

In the below code snippet, we have already set AWS_REGION to our desired region name.

If you have not done this, run export AWS_REGION='eu-west-1', or appropriate.

Also set the ACCOUNT_ID to your AWS’s account ID.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com
PROJECT_NAME=our-project-name
export APP_VERSION=1.0
for app in microservice1 microservice2 frontend; do
  aws ecr describe-repositories --repository-name $PROJECT_NAME/$app >/dev/null 2>&1 || \
  aws ecr create-repository --repository-name $PROJECT_NAME/$app >/dev/null
  TARGET=$ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/$PROJECT_NAME/$app:$APP_VERSION
  docker build -t $TARGET apps/$app
  docker push $TARGET
done

Note how we use the for loop on line 4 above to loop through our directory names within the apps parent directory.