28 October 2022

Build and Push Image to ECR Using GitHub Actions

Throughout this article, we will use four key files to demonstrate the validity of the title. The following files should be part of your repository in order for the GitHub action to be invoked.

Dockerfile
package.json
index.js
workflow/main.yaml

As a pre-requisite, you must have an active AWS & GitHub account.

STEP 1 - write a Dockerfile for Nodejs App that we are going to deploy on ECR.

STEP 2 - Write a package.json file & include index.js in it.

STEP 3 - Create a custom workflow/main.yaml that plays a vital role in this experiment

from our repository, we are intending to use GitHub Actions to add a custom workflow to build the image and push it to AWS ECR.

understand the workflow -


 name: Build and push image to AWS-ECR

 on: push

 jobs:

   build:
 
     name: Build Image
     runs-on: ubuntu-latest
   
     steps:
     
     - name: This job scans Dockerfile in repository
       uses: actions/checkout@v2
    
     - name: This job reads the AWS credentials defined in secrets-actions to connect to ECR
       uses: aws-actions/configure-aws-credentials@v1
       with:
         aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
         aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
         aws-region: eu-west-2

     - name: This job will login to Amazon ECR
       id: login-ecr
       uses: aws-actions/amazon-ecr-login@v1
   
     - name: Here it will build, tag, and push image to AWS ECR
       env:
         ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
         ECR_REPOSITORY: repo-to-host-github-images
         IMAGE_TAG: github_action_image
       run: |
         docker build -t $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG .
         docker push $ECR_REGISTRY/$ECR_REPOSITORY:$IMAGE_TAG
 

STEP 4 - Create an ECR repository

$ aws ecr create-repository --repository-name repo-to-host-github-images


STEP 5 - Create Secret-actions in GitHub repo

From your repository navigate to Settings > Secrets > Actions > New Repository Secret

STEP 6
- Add custom workflow -

From your repository navigate to Actions > New workflow > setup a workflow yourself > paste above workflow > start commit 

the workflow will be queued and start doing its job 

once the action job is successful you should be able to see them

Your pushed image should be visible in AWS ECR as shown below


STEP 7 (Optional) - Test your docker image by pulling it from registry and run it

$ docker pull 295xxx576.dkr.ecr.eu-west-2.amazonaws.com/repo-to-host-github-images:github_action_image
$ docker run -d -p 8080:8080 295xxx576.dkr.ecr.eu-west-2.amazonaws.com/repo-to-host-github-images:github_action_image


--

No comments:

Post a Comment