You have Github repository with application code and a Dockerfile to build the code image. You can use Github Actions to create workflow. This workflow will get triggered on any commit to the repository and will build the docker image and push it to AWS Elastic Container Registry.
Steps:
1. Create and keep ready AWS ECR repository to upload the image. You can login to AWS console and create AWS ECR repository. In the below example I have created repository by name “test-hello-world“. Note down the AccountID, Region and Repository name from the URI, we will need later.
2. Now create a repository in Github for your application. Add your app code and Dockerfile to build the image. I have provide sample golang app code and Dockerfile. You can download it from – https://github.com/subudear/helloworld
“hello-world.go” code. It just shows “Hello World” for index page and shows “Service Health Check : Pass” for /health path.
package maino import "fmt" import "net/http" func index(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "<h1>Hello World</h1>") } func health(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "<h1>Service Health Check : Pass</h1>") } func main() { http.HandleFunc("/",index) http.HandleFunc("/health",health) fmt.Println("Server Starting...") http.ListenAndServe(":8080",nil) }
Dockerfile content:
FROM golang:1.16 AS base WORKDIR /go/src/app COPY *.go . RUN go mod init RUN go build -o main . EXPOSE 8080 ENTRYPOINT ["/go/src/app/main"]
Github Action workflow file dockerimage.yaml content:
name: Publish Docker Image on: push: branches: [ master ] jobs: build: runs-on: ubuntu-latest steps: - name: Check out uses: actions/checkout@v2 - name: Configure AWS Credentials 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: ${{ secrets.REGION }} - name: Push to ECR id: tag run: | aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${accountid}.dkr.ecr.${region}.amazonaws.com docker build --tag ${accountid}.dkr.ecr.${region}.amazonaws.com/${ecr_repository}:v1.${GITHUB_RUN_NUMBER} . docker push ${accountid}.dkr.ecr.${region}.amazonaws.com/${ecr_repository}:v1.${GITHUB_RUN_NUMBER} env: accountid: ${{ secrets.ACCOUNTID}} region: ${{ secrets.REGION }} ecr_repository: ${{ secrets.ECR_REPOSITORY }}
3. You have to create secrets in repository so that the workflow can access them during the execution of job.
Create following secrets in repository-
AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY
REGION
ACCOUNTID
ECR_REPOSITORY
4. Once Secrets are created, make any change to the app code and commit it. It will trigger the workflow. It will build and push the docker image to AWS ECR.