b. Create Docker and buildspec files

If you have not created the container repository as part Lab II, complete the Create container repository section of Lab II before proceeding.

In this section, you will create a Docker container for the application and a buildspec file in the CodeCommit repository created in the previous section

A buildspec is a collection of build commands and related settings in YAML format. This file is used by AWS CodeBuild to automatically create an updated version of the container upon code changes. The buildspec file informs CodeBuild of all the actions that should be taken during a build run for your application. In the next section, you will dive deeper on what is CodeBuild and how to set it up as part of a pipeline.

  1. Confirm you are in the MyDemoRepo repository:
pwd # should be MyDemoRepo
  1. Create a Docker container for the application. We’re going to use the Amazon Linux container from Amazon Elastic Container Registry (ECR) Public Gallery.
cat > Dockerfile << EOF
FROM public.ecr.aws/amazonlinux/amazonlinux:latest

ADD script.py /

CMD python /script.py
  1. Create a buildspec file to build and push the Docker container to Amazon ECR
cat > buildspec.yml << EOF
version: 0.2

      - echo Logging in to Amazon ECR...
      - aws --version
      - \$(aws ecr get-login --region \$AWS_REGION --no-include-email)
      - echo IMAGE TAG \$IMAGE_TAG

      - echo Build started at \$(date)
      - echo Building the Docker image...
      - docker build -t \$REPOSITORY_URI:latest .
      - docker tag \$REPOSITORY_URI:latest \$REPOSITORY_URI:\$IMAGE_TAG

      - echo Build completed at $(date)
      - echo Pushing the Docker images...
      - docker push \$REPOSITORY_URI:latest
      - docker push \$REPOSITORY_URI:\$IMAGE_TAG

  1. Create a file script.py with a simple hello world:
cat > script.py << EOF
# Hello World Python Script

print('Hello World!')
  1. Commit and Push your local created files to the remote repository hosted in CodeCommit.
git add Dockerfile buildspec.yml script.py
git commit -m "Created Dockerfile and buildspec file"
git push origin main
  1. Now update the default Codecommit branch to main:
aws codecommit update-default-branch --repository-name MyDemoRepo --default-branch-name main --region $AWS_REGION