
buildspec.yml (or buildspec.yaml). This YAML file describes the lifecycle of the build and the commands to run in each phase.
Recommendation: Use the
buildspec.yml filename (lowercase .yml) for consistency; .yaml is functionally equivalent.
buildspec.yml for building a Docker image and pushing it to Amazon ECR. The file is organized into sections: version, env > variables, and phases (including pre_build, build, and post_build).
buildspec.yml sections:
Phases explained:
- pre_build: Preparation tasks such as authenticating to ECR, installing dependencies, or setting up credentials. The example uses
aws ecr get-login-passwordto log Docker in to ECR. - build: Core build steps — for Docker this includes
docker buildanddocker tag. - post_build: Finalization steps such as pushing the image to ECR, uploading artifacts to S3, or notifying CI/CD systems.
- Environment variables:
- Ensure
AWS_ACCOUNT_IDandAWS_DEFAULT_REGIONare defined either in the CodeBuild project environment variables or replaced with literal values in thebuildspec.yml. They are not injected automatically unless configured.
- Ensure
- Privileged mode:
- To execute Docker commands inside CodeBuild, enable “Privileged” mode on the build environment and use an image that includes Docker (or supports Docker-in-Docker).
- Service role permissions:
- The CodeBuild service role must include ECR permissions such as:
ecr:GetAuthorizationTokenecr:BatchCheckLayerAvailabilityecr:PutImageecr:InitiateLayerUploadecr:UploadLayerPartecr:CompleteLayerUpload
- Add any additional permissions required by your workflow (KMS, S3, CloudWatch Logs, etc.).
- The CodeBuild service role must include ECR permissions such as:
Important: Without Privileged mode enabled or the appropriate service-role IAM permissions, Docker commands and pushing to ECR will fail. Verify both the build environment settings and the IAM policy before running the build.
- For language-specific projects (Java, Node, Python), use
pre_buildto install dependencies,buildto compile/package artifacts, andpost_buildto upload artifacts or publish releases. - Use environment variables to parameterize repository names and tags so a single
buildspec.ymlcan work across environments (dev, staging, prod). - If you use KMS-encrypted images or private S3 artifacts, ensure the service role has access to KMS/S3 as needed.
- AWS CodeBuild User Guide
- Pushing a Docker container image to Amazon ECR
- CodeBuild buildspec reference
buildspec.yml in your repository and a configured CodeBuild project, CodeBuild will run the defined steps and produce your Docker image in ECR automatically.
That’s it for this lesson. Speak with you in the next lesson.