What Is AWS CodeBuild? How It Works and When to Use It
AWS CodeBuild is a fully managed build service that compiles code, runs tests, and produces deployable artifacts without you managing any build servers. You define what to run in a buildspec.yml file. CodeBuild executes those commands in a temporary container on AWS infrastructure. When the build finishes, the container disappears and you are charged only for the time it ran.
Teams use CodeBuild as the build stage in an AWS CI/CD pipeline: source code arrives from a repository, CodeBuild compiles and tests it, and the output artifact or Docker image moves to a deployment stage. Because CodeBuild runs inside AWS, it has straightforward access to ECR, ECS, EKS, Lambda, SSM, and Secrets Manager without handing credentials to an external CI service.
If you are deciding whether CodeBuild fits your workflow, this page covers how it works, what it does best, and where a simpler tool might serve you better.
AWS CodeBuild, simply explained
CodeBuild is the build runner in AWS CI/CD. When you push code, CodeBuild spins up a fresh container, clones your repository into it, and runs whatever commands you put in your buildspec.yml. It carries no state between builds. Every build starts from a clean environment. When it finishes, the container is gone.
That is the core loop: trigger, ephemeral environment, your commands, output. There are no agents to install, no persistent servers to patch, and no idle billing when nothing is building.
Think of CodeBuild like a pop-up workshop. Every time you need to build something, AWS assembles a fully equipped workspace. You do your work, and then it tears the workspace down. You pay only while it is active. The alternative is keeping a permanent build server running 24/7, paying for it even when no builds are happening.
What AWS CodeBuild is used for
CodeBuild handles the build and test portion of a CI/CD workflow. Practical uses include:
- Running automated tests. Unit tests, integration tests, and linting on every pull request or push. See automated testing in CodeBuild for configuring test reports.
- Compiling and packaging applications. Building a Java JAR, a Go binary, a Node.js bundle, or a Python package, then uploading the result to S3.
- Building Docker images. Building a container image from a Dockerfile, tagging it, and pushing it to Amazon ECR. See building Docker images with CodeBuild for a full buildspec walkthrough.
- Pushing artifacts to S3. Uploading build outputs (zipped binaries, static site files, deployment packages) to an S3 bucket so downstream pipeline stages can consume them.
- Preparing deployments. Running the build step before deploying with CodeBuild or handing off to CodeDeploy.
How AWS CodeBuild works
Every build follows the same flow:
- Source is pulled. CodeBuild fetches your code from GitHub, GitLab, Bitbucket, CodeCommit, or an S3 bucket.
- A build environment starts. AWS provisions a fresh container using the image you specified. No state is carried over from previous builds.
- buildspec.yml runs. CodeBuild executes the phases in your buildspec: install dependencies, pre-build checks, compile, then post-build tasks.
- Logs and artifacts are produced. Build output streams in real time to CloudWatch Logs. Artifacts are pushed to S3 or ECR.
- Downstream stages receive the output. If CodeBuild runs inside a CodePipeline, the next stage picks up where the build left off.
Real-world example: containerised app workflow
Here is what this looks like in practice for teams running ECS deployments:
- Developer pushes code to GitHub.
- CodeBuild triggers, runs unit tests, and fails fast if anything breaks.
- If tests pass, CodeBuild builds a Docker image from the
Dockerfilein the repository. - The image is tagged with the Git commit SHA and pushed to ECR. See ECR best practices for tagging conventions.
- A deployment stage updates the ECS task definition with the new image tag and rolls it out.
This entire flow runs without external CI credentials. CodeBuild uses an IAM service role, so Docker authentication and deployment access stay inside AWS.
Core concepts you need to understand
Build project — The configuration object in AWS that defines the source, build environment, buildspec location, artifacts destination, and service role. Create one build project per workflow (for example, one for tests and one for Docker builds).
Source provider — Where CodeBuild pulls your code from. Supported options: GitHub, GitLab, Bitbucket, CodeCommit, and S3. You can also trigger builds without a code source by passing inputs through environment variables.
Build environment — The container image and compute size that CodeBuild uses for the build. AWS provides managed images for common runtimes. You can also supply a custom Docker image from ECR or Docker Hub for specialised toolchains.
buildspec.yml — The file in your repository that defines what commands run during the build. If this file is missing or misconfigured, the build fails before any meaningful work starts.
Artifacts — Files that CodeBuild saves after the build. Typically uploaded to an S3 bucket so downstream pipeline stages can retrieve them.
Logs — Build output streamed to CloudWatch Logs. View them in real time during a build or look them up afterward to diagnose failures.
Service role / IAM permissions — Every CodeBuild project runs as an IAM role that determines what AWS resources the build can access. Missing permissions are one of the most common causes of CodeBuild failures. See IAM access denied errors for troubleshooting guidance.
buildspec.yml example
The buildspec is the heart of every CodeBuild project. It must be named buildspec.yml and placed in the root of your repository (or at a path you specify in the project settings). The file uses a fixed structure with named phases.
version: 0.2
env:
variables:
NODE_ENV: "test"
parameter-store:
DB_PASSWORD: "/myapp/dev/db-password"
phases:
install:
runtime-versions:
nodejs: 20
commands:
- echo "Installing dependencies"
- npm ci
pre_build:
commands:
- echo "Running linting and unit tests"
- npm run lint
- npm test
build:
commands:
- echo "Building the application"
- npm run build
post_build:
commands:
- echo "Build completed on $(date)"
artifacts:
files:
- dist/**/*
- package.json
base-directory: .
discard-paths: no
cache:
paths:
- node_modules/**/*Understanding the phases
install — Runs once at the start. Use it for installing runtime versions and system dependencies. The runtime-versions key selects a pre-installed language runtime from the managed image.
pre_build — Runs before the main build. Good for logging into ECR, running linting, and setting up test databases.
build — The main work phase: compilation, Docker image construction, packaging. If commands here fail, CodeBuild marks the build as failed.
post_build — Runs after the build phase, even after a failure (unless the environment itself is interrupted). Common uses: push Docker images to ECR, upload artifacts to S3, send a notification.
Phase failure behavior: If any command returns a non-zero exit code, that phase fails and the build is marked failed. Later phases do not run, except post_build which always runs unless the environment is interrupted. Use || true intentionally if you want to ignore a specific command’s failure.
Never put secrets in buildspec.yml. The file is committed to your repository. Anyone with repo access can read it. Use SSM Parameter Store or Secrets Manager references instead. See secrets in CI/CD pipelines for the recommended approach.
Compute and build environment options
CodeBuild provides AWS-managed build images covering common language runtimes and build tools. You can also supply your own Docker image from ECR or Docker Hub for custom toolchains.
Managed images cover most application build needs: Node.js, Python, Java, Go, Ruby, PHP, .NET, and more. AWS maintains these images, so you do not need to think about base OS patching or runtime availability.
Compute type controls how much CPU and RAM the build container gets. Smaller types cost less per minute but run builds more slowly. Larger types finish faster and are worth the cost when build time is the bottleneck.
Lambda compute is an alternative to the default EC2-backed environment. Lambda compute starts builds faster (no host provisioning delay) and is billed per millisecond. It suits short, frequent builds such as PR test runs. EC2-backed environments handle longer builds and support VPC networking.
Docker builds require privileged mode. If your buildspec runs docker build, you must enable privileged mode in the build environment settings. Without it, the Docker daemon cannot start inside the container and the build fails immediately.
When to use AWS CodeBuild
CodeBuild is a strong choice when:
- Your deployments target AWS services. Deploying to ECS, EKS, Lambda, or Elastic Beanstalk is straightforward because the CodeBuild IAM role handles authentication without storing AWS credentials in a third-party system.
- You push images to ECR. CodeBuild authenticates to ECR using its service role alone. No Docker credentials to store or rotate.
- Your builds need VPC access. CodeBuild can run inside a VPC, giving the build container access to private databases, internal services, or other resources not reachable from the public internet.
- Security and compliance matter. Keeping build infrastructure inside AWS reduces the surface area for credential exposure. Combined with secure CI/CD pipeline practices, CodeBuild fits well in regulated environments.
- You are already using CodePipeline. CodeBuild integrates natively as a pipeline stage with no extra wiring needed.
- You want AWS-native observability. Build logs go directly to CloudWatch Logs, consistent with the rest of your AWS monitoring setup.
When not to use AWS CodeBuild
CodeBuild is not always the right tool:
- Your team lives in GitHub and builds are simple. If your workflow is “run tests, deploy to a non-AWS target”, GitHub Actions is faster to set up and has a large marketplace of pre-built steps. There is no AWS-native benefit worth the extra configuration overhead.
- You want a repository-first CI experience. GitHub Actions and GitLab CI keep your workflow files entirely in the repo. CodeBuild requires a separate build project resource in AWS, which is external state to manage.
- Your team is already standardised on another runner. Switching CI tools has a real cost in ramp-up time and debugging muscle memory. If GitHub Actions or Jenkins is working well, CodeBuild may not justify the migration unless you specifically need VPC access or IAM-native integration.
- You need tight PR feedback in GitHub’s interface. GitHub Actions shows inline check results with required status checks built into the PR experience. CodeBuild can be wired to GitHub webhooks, but the integration is less seamless for PR-centric workflows.
AWS CodeBuild vs CodePipeline vs GitHub Actions
These three tools are often confused because they all appear in CI/CD conversations. The key distinction: CodeBuild is a build runner, CodePipeline is a pipeline orchestrator, and GitHub Actions combines both in a repository-centric workflow.
| Tool | Primary role | Best use case | AWS integration | Setup complexity |
|---|---|---|---|---|
| CodeBuild | Build runner | Compile, test, build Docker images, push to ECR | Native (IAM role, VPC, ECR, SSM, CloudWatch) | Moderate — requires a build project resource in AWS |
| CodePipeline | Pipeline orchestrator | Sequencing stages: Source, Build, Test, Deploy | Native — calls CodeBuild, CodeDeploy, Lambda, etc. | Moderate — pipeline definition in AWS console or IaC |
| GitHub Actions | General CI/CD | PR tests, simple deployments, GitHub-centric workflows | External — requires OIDC federation or stored credentials | Low — YAML workflow files live in the repository |
CodePipeline is not a competitor to CodeBuild. It calls CodeBuild as one of its stages. An AWS CodeDeploy stage typically sits after the CodeBuild stage in a full pipeline. You use all three together, not one instead of another.
Many teams use CodeBuild and GitHub Actions together: GitHub Actions handles pull request tests (fast feedback in GitHub’s interface) and CodeBuild handles production deployments (VPC access, IAM role, no credentials leaving AWS). See GitHub Actions for AWS for how to set up OIDC-based AWS authentication from GitHub Actions when you choose that path.
Environment variables and secrets
CodeBuild supports three ways to pass environment variables to builds, each with different security tradeoffs:
Plain text variables are set directly in the CodeBuild project or in the buildspec. Use these for non-sensitive values like NODE_ENV=production or AWS_REGION=us-east-1.
Parameter Store variables reference SSM paths. CodeBuild fetches the value at build start. Use these for environment-specific config that is not secret, such as a database hostname.
Secrets Manager variables reference Secrets Manager ARNs. The value is never shown in the CodeBuild console or logs. Use these for passwords, API keys, and other sensitive values.
env:
variables:
NODE_ENV: "production"
parameter-store:
DATABASE_HOST: "/myapp/prod/db-host"
secrets-manager:
DATABASE_PASSWORD: "myapp/prod/db-credentials:password"The CodeBuild service role must have IAM permissions to read from SSM and Secrets Manager. Without those permissions, the build fails at startup when it tries to fetch the values. For a full guide on secrets handling, see secrets in CI/CD pipelines.
Common beginner mistakes
- Missing IAM permissions on the service role. Builds that access ECR, SSM, S3, or other AWS services fail with cryptic errors when the service role lacks permissions. Add permissions incrementally and check CloudWatch Logs when builds fail unexpectedly.
- Hardcoding secrets in buildspec.yml. The buildspec is committed to your repository. Anyone with repo access can read it. Use SSM Parameter Store or Secrets Manager references, not raw secrets in the file.
- Forgetting privileged mode for Docker builds. Running
docker buildinside CodeBuild requires privileged mode enabled in the build environment. Without it, the Docker daemon cannot start and the build fails immediately with a permission error. - Skipping build caching. CodeBuild downloads dependencies fresh on every build unless you configure caching. A build that downloads hundreds of megabytes of packages every run is slow and more expensive than necessary. Configure S3 caching for dependency directories from day one.
- Confusing CodeBuild with CodePipeline. CodeBuild runs build commands. CodePipeline sequences pipeline stages. They solve different problems at different levels and are typically used together.
- Using CodeBuild when GitHub Actions would be simpler. If your code is on GitHub and you only need to run tests and deploy to a non-VPC target, a CodeBuild project adds infrastructure overhead with no practical benefit.
- Not separating environments. Using one CodeBuild project for staging and production builds creates risk. See managing environments in CI/CD for how to separate concerns safely.
Pricing basics
CodeBuild charges per build minute based on the compute type you choose. There is no flat monthly fee. If nothing is building, you pay nothing.
Smaller compute types cost less per minute but run builds more slowly. Larger compute types finish faster and cost more per minute. The right balance depends on whether your bottleneck is build speed or budget.
There is a free tier: 100 build minutes per month on the general1.small compute type. For most teams evaluating CodeBuild, this covers early experimentation at no cost.
Lambda compute is billed per millisecond of build duration and is generally cheaper for short, frequent builds. EC2-backed compute is more cost-effective for longer builds where the per-minute rate matters more than startup speed.
Exact pricing figures are not repeated here to avoid stale information. Check the official AWS CodeBuild pricing page for current numbers, as pricing varies by region and compute type.
Summary
- CodeBuild is a managed build runner. It executes your build commands in a temporary container with no persistent servers to manage.
- The buildspec.yml file defines four phases: install, pre_build, build, and post_build.
- Build environments use AWS-managed images for common runtimes, or your own custom Docker image from ECR.
- Secrets belong in SSM Parameter Store or Secrets Manager, not hardcoded in the buildspec file.
- The IAM service role controls what AWS resources the build can access. Missing permissions are the most common source of build failures.
- Configure S3 caching for dependency directories from the start. It can dramatically reduce build times.
- CodeBuild is the right choice for AWS-integrated builds (ECR pushes, ECS/EKS deployments, VPC access). Consider GitHub Actions for simpler workflows where code lives on GitHub and AWS-native access is not required.
- CodeBuild is the build runner. CodePipeline is the orchestrator that sequences stages including CodeBuild.
Frequently asked questions
What is the difference between CodeBuild and CodePipeline?
CodeBuild is the build engine. It runs your build commands inside an isolated container. CodePipeline is the orchestrator. It defines the stages (Source, Build, Test, Deploy) and triggers each stage in sequence. CodeBuild is typically one stage within a CodePipeline, though it can also be triggered directly by webhooks without a pipeline.
Can I use CodeBuild without CodePipeline?
Yes. CodeBuild can be triggered by webhooks from GitHub, GitLab, or Bitbucket directly. When a pull request is opened or a branch is pushed, CodeBuild starts a build with no CodePipeline involved. This is common for build-only use cases like running tests on every pull request.
When should I use CodeBuild instead of GitHub Actions?
Use CodeBuild when your builds need deep AWS access: pushing to ECR, deploying to ECS or EKS, running inside a VPC, or reading from SSM or Secrets Manager without exposing credentials to an external service. GitHub Actions is usually simpler when your code lives on GitHub and your builds do not need internal AWS network access.
Do I need a buildspec.yml file?
Yes, unless you define build commands inline in the CodeBuild project configuration. Using a buildspec.yml checked into your repository is strongly recommended because it keeps your build definition in version control alongside your code.
Does CodeBuild support Docker builds?
Yes, but you must enable privileged mode in the build environment settings. Without it, docker build commands fail with permission errors. Once enabled, your buildspec can build images and push them to ECR using the AWS CLI or Docker CLI commands.