This Bitbucket Pipelines error occurs when one or more steps in your CI/CD pipeline fail during execution. The failure can stem from test failures, build errors, configuration issues, or resource limits. To resolve it, examine the pipeline logs, identify the root cause, and fix the underlying issue in your code or configuration.
When you see "Pipeline failed for branch main" (or any other branch name), Bitbucket is telling you that your CI/CD pipeline did not complete successfully. A pipeline fails when any step returns a non-zero exit code, indicating an error. Bitbucket Pipelines runs the commands defined in your `bitbucket-pipelines.yml` file as bash/shell commands. The pipeline runner checks the exit status of each command - zero means success, non-zero means failure. When a step fails, subsequent steps are typically skipped unless configured otherwise. This error is Bitbucket's way of protecting your codebase and deployment targets from broken code. The failed pipeline prevents merging or deployment until the issue is resolved. Understanding why the pipeline failed requires examining the step logs, which show exactly what went wrong. Common categories of pipeline failures include: test failures, build compilation errors, linting violations, missing dependencies, environment variable issues, timeout errors, and memory exhaustion.
First, identify what caused the pipeline to fail by examining the logs:
1. Navigate to your repository in Bitbucket
2. Click on Pipelines in the left sidebar
3. Find the failed pipeline (marked with red X)
4. Click on the pipeline to see the steps
5. Click on the failed step to view its logs
# Example log showing a test failure:
+ npm test
> [email protected] test
> jest
FAIL src/__tests__/utils.test.js
✕ should calculate correctly (5 ms)
Test Suites: 1 failed, 2 passed, 3 total
Tests: 1 failed, 8 passed, 9 total
error: command failed with exit code 1The key information is usually near the end of the log, right before the "command failed with exit code" message. Look for error messages, stack traces, or assertion failures.
Check your pipeline configuration file for common issues:
Ensure the file exists and is named correctly:
- File must be in the repository root
- Must use .yml extension (not .yaml)
- File name is case-sensitive: bitbucket-pipelines.yml
Validate YAML syntax:
# Correct structure:
image: node:18
pipelines:
default:
- step:
name: Build and Test
caches:
- node
script:
- npm ci
- npm test
branches:
main:
- step:
name: Deploy to Production
script:
- npm run deployCommon configuration mistakes:
1. Missing step definition:
# Wrong - branches section needs step(s):
branches:
main:
- npm run deploy
# Correct:
branches:
main:
- step:
script:
- npm run deploy2. Incorrect indentation (YAML is sensitive to spaces):
# Wrong - mixed indentation:
pipelines:
default:
- step: # Only 1 space!
script:
- npm test
# Correct - consistent 2-space indentation:
pipelines:
default:
- step:
script:
- npm test3. Branch-specific pipeline not in target branch:
If you commit bitbucket-pipelines.yml to main, only the main or default pipeline runs. For branch-specific pipelines to work, the file must exist in that branch.
Before making changes, try to reproduce the issue on your machine:
# Pull the latest code
git fetch origin
git checkout main
# Run the same commands that failed in CI
# For test failures:
npm test
# or
pytest
# or
go test ./...
# For build failures:
npm run build
# For lint failures:
npm run lintIf the failure only happens in CI, check for environment differences:
- Different Node/Python/Go version
- Missing environment variables
- Cached dependencies vs fresh install
- Different OS or architecture
Use Docker to match CI environment more closely:
# Run the same Docker image used in pipeline
docker run -it --rm -v $(pwd):/app -w /app node:18 bash
# Inside the container, run your commands
npm ci
npm testBitbucket provides a way to debug locally using Docker - you can run an identical container to find the root cause interactively.
If the pipeline failed due to failing tests, address the test or code issues:
Common test failure scenarios:
1. Assertion failure - Update the test or fix the code:
// Fix the actual code
function calculateTotal(items) {
return items.reduce((sum, item) => sum + item.price, 0); // was missing initial value
}2. Snapshot mismatch - Update snapshots if changes are intentional:
npm test -- --updateSnapshot
# or
jest --updateSnapshot3. Async test timeout - Increase timeout or fix async handling:
test('async operation', async () => {
jest.setTimeout(10000); // Increase timeout
const result = await slowOperation();
expect(result).toBeDefined();
}, 10000);4. Environment-dependent test - Mock external dependencies:
// Mock API calls that may fail in CI
jest.mock('./api', () => ({
fetchData: jest.fn().mockResolvedValue({ data: 'test' })
}));After fixing, push your changes:
git add .
git commit -m "fix: resolve failing tests"
git push origin mainFor build failures, address the compilation or bundling issues:
TypeScript/JavaScript build errors:
# Check for TypeScript errors locally
npx tsc --noEmit
# Common fixes:
# - Add missing type definitions
# - Fix type mismatches
# - Install missing @types packages
npm install --save-dev @types/nodeImport/export issues:
// Wrong - named vs default export mismatch
import MyComponent from './MyComponent'; // expects default export
export const MyComponent = () => {}; // but this is named export
// Fix:
export default MyComponent;
// or
import { MyComponent } from './MyComponent';Missing dependencies:
# Make sure all dependencies are listed in package.json
npm install missing-package --save
# Use npm ci in pipelines for reproducible builds
# bitbucket-pipelines.yml:
script:
- npm ci # Not 'npm install'
- npm run buildDocker build issues:
# Ensure you're using the right image
image: node:18
# Or specify a custom Docker image
definitions:
services:
docker:
memory: 2048 # Increase memory if neededFix problems related to missing or incorrect environment variables:
Set repository variables in Bitbucket:
1. Go to Repository settings > Pipelines > Repository variables
2. Add your variables (e.g., API_KEY, DATABASE_URL)
3. Mark sensitive values as "Secured"
Reference variables in bitbucket-pipelines.yml:
image: node:18
pipelines:
default:
- step:
script:
- echo "Deploying to $ENVIRONMENT"
- npm run deployDefine variables inline for non-sensitive values:
definitions:
variables:
NODE_ENV: &node_env "production"
pipelines:
default:
- step:
script:
- export NODE_ENV=*node_env
- npm run buildDebug missing variables:
script:
# Print available environment variables (be careful not to expose secrets!)
- printenv | grep -v PASSWORD | grep -v SECRET | grep -v KEY
- npm run buildCommon variable issues:
- Variable name typo (case-sensitive)
- Variable set in wrong scope (repository vs deployment)
- Secured variables not available in pull request builds from forks
If your pipeline fails with exit code 137, it's running out of memory:
error: command failed with exit code 137Exit code 137 means the process was killed by the system (SIGKILL), typically due to memory exhaustion.
Solution 1: Use a larger build step size:
pipelines:
default:
- step:
size: 2x # Doubles memory from 4GB to 8GB
script:
- npm ci
- npm run buildAvailable sizes:
- 1x: 4 GB RAM (default)
- 2x: 8 GB RAM (uses 2x build minutes)
Solution 2: Optimize memory usage:
script:
# For Jest - limit parallel workers
- npm test -- --maxWorkers=2
# or run sequentially
- npm test -- --runInBand
# For Node.js - increase heap size
- export NODE_OPTIONS="--max-old-space-size=4096"
- npm run buildSolution 3: Split into multiple steps:
pipelines:
default:
- step:
name: Build
script:
- npm ci
- npm run build
artifacts:
- dist/**
- step:
name: Test
script:
- npm ci
- npm testIf your pipeline exceeds time limits, optimize or extend the timeout:
Increase step timeout:
pipelines:
default:
- step:
name: Long Running Tests
max-time: 60 # Maximum time in minutes (default is 120)
script:
- npm run test:e2eOptimize to reduce build time:
1. Use caching effectively:
definitions:
caches:
npm: ~/.npm
node: node_modules
pipelines:
default:
- step:
caches:
- npm
- node
script:
- npm ci
- npm test2. Run tests in parallel:
pipelines:
default:
- parallel:
- step:
name: Unit Tests
script:
- npm run test:unit
- step:
name: Integration Tests
script:
- npm run test:integration3. Skip unnecessary steps:
pipelines:
pull-requests:
'**':
- step:
name: Quick Tests Only
script:
- npm ci
- npm run test:unit # Skip slow e2e tests for PRsBy default, piped commands in bash only report the exit code of the last command, potentially hiding errors:
Problem:
script:
# This won't fail even if npm test fails!
- npm test | tee test-output.logSolution 1: Enable pipefail:
script:
- set -o pipefail
- npm test | tee test-output.logSolution 2: Chain commands properly:
script:
# Run test and save output, failing if tests fail
- npm test 2>&1 | tee test-output.log; test ${PIPESTATUS[0]} -eq 0Capturing exit codes correctly:
script:
# Wrong - printf intercepts $?
- failing-command
- echo "Exit code: $?" # Always shows 0!
# Correct - combine on same line
- set +e
- failing-command; exit_code=$?; set -e
- echo "Exit code: $exit_code"
- if [ $exit_code -ne 0 ]; then exit $exit_code; fiAllow specific commands to fail:
script:
# This command can fail without failing the pipeline
- npm run optional-check || true
# This one will still fail the pipeline
- npm testFor temporary failures (network issues, flaky tests), you can retry:
Manual retry:
1. Navigate to the failed pipeline
2. Click the Rerun button to retry failed steps
3. Or click Run pipeline to start fresh
Rerun only failed steps:
Bitbucket Pipelines allows you to rerun only the failed steps rather than the entire pipeline, saving time and build minutes.
Configure automatic retries in script:
script:
# Retry a flaky command up to 3 times
- |
for i in 1 2 3; do
npm run flaky-test && break || {
if [ $i -lt 3 ]; then
echo "Attempt $i failed, retrying..."
sleep 10
else
echo "All attempts failed"
exit 1
fi
}
doneTrigger pipeline via API:
curl -X POST \
-u "$BITBUCKET_USERNAME:$BITBUCKET_APP_PASSWORD" \
"https://api.bitbucket.org/2.0/repositories/{workspace}/{repo}/pipelines/" \
-H "Content-Type: application/json" \
-d '{
"target": {
"ref_type": "branch",
"type": "pipeline_ref_target",
"ref_name": "main"
}
}'Push an empty commit to trigger:
git commit --allow-empty -m "ci: retry pipeline"
git push origin main### Understanding Exit Codes in Bitbucket Pipelines
Common exit codes and their meanings:
| Exit Code | Meaning | Common Cause |
|-----------|---------|--------------|
| 1 | General error | Test failure, script error |
| 2 | Misuse of command | Invalid arguments |
| 126 | Permission problem | Script not executable |
| 127 | Command not found | Missing binary/tool |
| 128 | Invalid exit argument | Script returned invalid code |
| 137 | SIGKILL (128+9) | Out of memory, killed by system |
| 139 | SIGSEGV (128+11) | Segmentation fault |
| 143 | SIGTERM (128+15) | Job timeout, terminated |
### Pipeline Artifacts for Debugging
Preserve logs and test results from failed pipelines:
pipelines:
default:
- step:
script:
- npm test -- --coverage
artifacts:
- coverage/**
- test-results/**
- logs/**Artifacts are available for download from the pipeline UI even when the step fails.
### Branch-Specific Pipeline Behavior
The bitbucket-pipelines.yml file must exist in the branch being built:
pipelines:
# Runs for any branch without a specific pipeline
default:
- step:
script:
- npm test
# Runs only for specific branches
branches:
main:
- step:
script:
- npm run deploy:prod
develop:
- step:
script:
- npm run deploy:staging
'feature/*':
- step:
script:
- npm test -- --coverage### Push Limits
Bitbucket accepts up to five branches in one push. Exceeding this limit may prevent pipelines from triggering. Push branches individually if you hit this limit.
### Using Services for Integration Tests
For tests requiring databases or other services:
definitions:
services:
postgres:
image: postgres:15
variables:
POSTGRES_DB: test_db
POSTGRES_USER: test
POSTGRES_PASSWORD: test
pipelines:
default:
- step:
services:
- postgres
script:
- export DATABASE_URL="postgresql://test:test@localhost:5432/test_db"
- npm run db:migrate
- npm test### Docker-in-Docker (DinD)
For pipelines that build Docker images:
definitions:
services:
docker:
memory: 2048
pipelines:
default:
- step:
services:
- docker
script:
- docker build -t myapp .
- docker push myapp### Debugging with SSH
For complex failures, you can SSH into a pipeline build (requires configuration):
pipelines:
custom:
debug:
- step:
script:
- echo "Debug session ready"
# Enable SSH access in Bitbucket settings first### Conditional Steps
Skip steps based on conditions:
pipelines:
default:
- step:
name: Deploy
script:
- npm run deploy
condition:
changesets:
includePaths:
- "src/**"
- "package.json"kex_exchange_identification: Connection closed by remote host
Connection closed by remote host when connecting to Git server
fatal: unable to access: Proxy auto-configuration failed
How to fix 'Proxy auto-configuration failed' in Git
fatal: unable to access: Authentication failed (proxy requires basic auth)
How to fix 'Authentication failed (proxy requires basic auth)' in Git
fatal: unable to access: no_proxy configuration not working
How to fix 'no_proxy configuration not working' in Git
fatal: unable to read tree object in treeless clone
How to fix 'unable to read tree object in treeless clone' in Git