Introduction
Jenkins pipeline builds fail when stages encounter errors, agents become unavailable, or configuration issues prevent execution. Build logs show failure points requiring investigation and resolution.
Symptoms
Stage failure:
[Pipeline] stage
[Pipeline] { (Build)
[Pipeline] sh
+ npm run build
npm ERR! missing script: build
[Pipeline] }
[Pipeline] // stage
[Pipeline] }
[Pipeline] // node
[Pipeline] End of Pipeline
ERROR: script returned exit code 1
Finished: FAILUREAgent unavailable:
Waiting for executor on 'build-agent'
There are no nodes with the label 'build-agent'
ERROR: No agents registered for labelGroovy syntax error:
org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
WorkflowScript: 15: Expected a symbol @ line 15, column 5.
stages {
^
1 errorCommon Causes
- 1.Script errors - Build commands or tests failing
- 2.Agent offline - Build node not available
- 3.Dependency issues - Missing packages or tools
- 4.Syntax errors - Invalid Jenkinsfile Groovy syntax
- 5.Timeout - Stage exceeded time limit
- 6.Permission denied - Access to files or tools blocked
Step-by-Step Fix
- 1.Identify the error - Check logs for specific messages
- 2.Verify configuration - Review and correct settings
- 3.Test connectivity - Ensure network paths work
- 4.Apply correction - Make necessary changes
- 5.Verify the fix - Confirm issue is resolved
# Diagnostic commands
grep -r "error" /var/log/Step 1: Analyze Build Log
```bash # View build log in Jenkins UI # Job > Build #xxx > Console Output
# Or via CLI java -jar jenkins-cli.jar -s http://jenkins:8080 build my-job 1 -v
# Find specific error pattern grep -i "error|failed|exception" console.log
# Check stage that failed grep -B 10 "ERROR:" console.log
# Look for exit codes grep "exit code" console.log
# Common patterns: # "script returned exit code 1" = command failed # "No such file or directory" = missing file # "Permission denied" = access issue # "timeout" = exceeded limit ```
Step 2: Check Agent Availability
```bash # Check agent status in Jenkins UI # Manage Jenkins > Manage Nodes
# Via CLI java -jar jenkins-cli.jar -s http://jenkins:8080 node-provisioning
# Check agent is online curl -s http://jenkins:8080/computer/api/json | jq '.computer[] | {name: .name, offline: .offline}'
# Check agent logs # Node > Log
# Restart offline agent # Node > Mark this node temporarily offline (toggle)
# Check agent connection ssh jenkins-agent "echo 'Agent reachable'"
# Verify agent has required labels # Node > Configure > Labels # Pipeline uses: agent { label 'linux' } ```
Step 3: Validate Jenkinsfile Syntax
```bash # Use Jenkins linter to validate Jenkinsfile java -jar jenkins-cli.jar -s http://jenkins:8080 declarative-linter < Jenkinsfile
# Or via curl curl -X POST -F "jenkinsfile=<Jenkinsfile" http://jenkins:8080/pipeline-model-converter/validate
# Common syntax errors:
# Missing 'steps' block stage('Build') { sh 'make' # WRONG: must be inside steps }
# CORRECT: stage('Build') { steps { sh 'make' } }
# Missing agent declaration pipeline { // Must have agent agent any stages { ... } }
# Incorrect block nesting pipeline { stages { stage('Test') { steps { sh 'test' // CORRECT order } } } } ```
Step 4: Debug Pipeline Script
```groovy // Add debug output to Jenkinsfile
pipeline { agent any stages { stage('Debug') { steps { script { // Print environment variables sh 'env | sort'
// Print current directory sh 'pwd'
// List files sh 'ls -la'
// Print specific variable echo "BRANCH_NAME: ${env.BRANCH_NAME}" echo "BUILD_NUMBER: ${env.BUILD_NUMBER}" } } } stage('Build') { steps { // Use '|| true' to continue on error (debugging) sh 'npm run build || true'
// Capture output script { def output = sh(script: 'npm run build', returnStdout: true) echo "Build output: ${output}" } } } } } ```
Step 5: Fix Dependency Issues
```groovy // Ensure dependencies installed before build
pipeline { agent any stages { stage('Setup') { steps { // Node.js sh 'npm ci' // Or 'npm install'
// Python sh 'pip install -r requirements.txt'
// Java/Maven sh 'mvn dependency:resolve'
// Go sh 'go mod download'
// Ruby sh 'bundle install' } } stage('Build') { steps { sh 'npm run build' } } } }
// Cache dependencies for speed pipeline { agent any stages { stage('Dependencies') { steps { sh 'npm ci' } } } // Use workspace cleanup carefully post { always { // Don't delete node_modules // cleanWs() } } } ```
Step 6: Fix Permission Issues
```bash # Check Jenkins user permissions # Jenkins runs as 'jenkins' user
# Check file permissions ls -la /var/lib/jenkins/workspace/my-job/
# Fix ownership chown -R jenkins:jenkins /var/lib/jenkins/workspace/
# Check executable permissions ls -la ./gradlew chmod +x ./gradlew
# Check Jenkins agent permissions ssh jenkins-agent "ls -la /home/jenkins/"
# In Docker container, may need to run as root docker exec -u root container-name chmod +x /path/script.sh
// In Jenkinsfile, specify user: pipeline { agent { docker { image 'node:16' args '-u root' // Run as root } } } ```
Step 7: Handle Timeouts
```groovy // Add timeout to prevent hanging builds
pipeline { agent any options { timeout(time: 1, unit: 'HOURS') // Global timeout } stages { stage('Build') { options { timeout(time: 30, unit: 'MINUTES') // Stage timeout } steps { sh 'make build' } } stage('Deploy') { steps { timeout(time: 10, unit: 'MINUTES') { sh 'deploy.sh' } } } } }
// Handle timeout gracefully stage('Long Operation') { steps { timeout(time: 30, unit: 'MINUTES') { script { try { sh 'long-running-command' } catch (Exception e) { echo "Stage timed out: ${e.message}" currentBuild.result = 'UNSTABLE' } } } } } ```
Step 8: Fix Environment Issues
```groovy // Ensure environment variables available
pipeline { agent any environment { PATH = "/usr/local/bin:${env.PATH}" JAVA_HOME = "/usr/lib/jvm/java-11" NODE_HOME = "/usr/local/node" } stages { stage('Build') { steps { // Use environment variable sh "echo PATH: ${env.PATH}" sh 'java -version' sh 'node --version' } } } }
// Load credentials pipeline { agent any environment { AWS_ACCESS_KEY_ID = credentials('aws-access-key') AWS_SECRET_ACCESS_KEY = credentials('aws-secret-key') } }
// Use withCredentials for secrets stage('Deploy') { steps { withCredentials([usernamePassword( credentialsId: 'aws-creds', usernameVariable: 'AWS_ACCESS_KEY_ID', passwordVariable: 'AWS_SECRET_ACCESS_KEY' )]) { sh 'aws s3 cp file.txt s3://bucket/' } } } ```
Step 9: Add Error Handling
```groovy // Comprehensive error handling
pipeline { agent any stages { stage('Build') { steps { script { try { sh 'make build' } catch (Exception e) { echo "Build failed: ${e.message}" // Archive logs for debugging archiveArtifacts artifacts: 'build.log', allowEmptyArchive: true throw e // Re-throw to fail build } } } post { failure { echo 'Build stage failed' mail to: 'team@company.com', subject: "Build Failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}", body: "Check console output at ${env.BUILD_URL}" } success { echo 'Build succeeded' } } } } post { always { cleanWs() // Cleanup workspace } failure { echo 'Pipeline failed' } success { echo 'Pipeline succeeded' } } } ```
Step 10: Monitor Build Health
```groovy // Add health checks and notifications
pipeline { agent any stages { stage('Build') { steps { sh 'make build' } post { success { // Update build status script { currentBuild.description = "Build successful" } } } } } post { failure { script { // Send notification slackSend( channel: '#builds', color: 'danger', message: "Build Failed: ${env.JOB_NAME} #${env.BUILD_NUMBER}" ) } } } }
// Use Jenkins metrics // Install Prometheus plugin for monitoring // Track: build duration, failure rate, queue time ```
Pipeline Failure Checklist
| Check | Location | Action |
|---|---|---|
| Console log | Build page | Find error message |
| Agent status | Nodes page | Check online |
| Jenkinsfile | Linter | Fix syntax |
| Dependencies | Setup stage | Install missing |
| Permissions | Workspace | Fix ownership |
| Timeouts | Options | Increase limit |
Verification
```bash # After fixing pipeline issues
# 1. Run pipeline again # Trigger new build in Jenkins UI
# 2. Monitor console output # Watch for errors
# 3. Check stage results # All stages should pass
# 4. Verify artifacts # Check archived artifacts exist
# 5. Test deployment # If deployment stage, verify app works
# 6. Check agent health # Node should show online and executors available
# 7. Review build history # Failure rate should decrease ```
Prevention
To prevent Jenkins pipeline build failures from recurring, implement these proactive measures:
1. Monitor Build Failure Rate
groups:
- name: jenkins-builds
rules:
- alert: JenkinsBuildFailureRateHigh
expr: |
rate(jenkins_builds_failed_total[1h]) / rate(jenkins_builds_total[1h]) > 0.2
for: 5m
labels:
severity: warning
annotations:
summary: "Jenkins build failure rate above 20%"2. Use Pipeline Linter
```bash # Lint Jenkinsfile before committing jenkinsfile-lint < Jenkinsfile
# Or use Jenkins API curl -X POST -F "jenkinsfile=<Jenkinsfile" \ http://jenkins:8080/pipeline-model-converter/validate ```
3. Implement Build Health Checks
// Add health checks to pipeline
pipeline {
agent any
stages {
stage('Health Check') {
steps {
script {
// Check agent resources
def disk = sh(script: 'df -h / | tail -1 | awk \'{print $5}\'', returnStdout: true).trim()
if (disk.replaceAll('%', '').toInteger() > 90) {
error("Disk usage too high: ${disk}")
}
}
}
}
}
}Best Practices Checklist
- [ ] Monitor build failure rate with alerts
- [ ] Lint Jenkinsfile before committing
- [ ] Add comprehensive error handling
- [ ] Set appropriate timeouts
- [ ] Archive logs for debugging
- [ ] Use declarative pipeline syntax
Related Issues
- [Fix Jenkins Agent Offline](/articles/fix-jenkins-agent-offline)
- [Fix Jenkins Git Checkout Failed](/articles/fix-jenkins-git-checkout-failed)
- [Fix Jenkins Out of Memory](/articles/fix-jenkins-out-of-memory)
Related Articles
- [Technical troubleshooting: Fix Cicd Artifact Upload Failed Storage Issue in C](cicd-artifact-upload-failed-storage)
- [Technical troubleshooting: Fix Cicd Code Quality Gate Failed Sonarqube Issue ](cicd-code-quality-gate-failed-sonarqube)
- [Technical troubleshooting: Fix Cicd Deployment Failed Health Check Issue in C](cicd-deployment-failed-health-check)
- [Technical troubleshooting: Fix Cicd Github Actions Workflow Queue Timeout in ](cicd-github-actions-workflow-queue-timeout)
- [Technical troubleshooting: Fix Cicd Gitlab Runner Stuck Pending Issue in CI/C](cicd-gitlab-runner-stuck-pending)
<script type="application/ld+json"> { "@context": "https://schema.org", "@type": "TechArticle", "headline": "Fix Jenkins Pipeline Build Failed", "description": "Troubleshoot Jenkins pipeline build failures. Analyze logs, check agents, and fix script errors.", "url": "https://www.fixwikihub.com/fix-jenkins-pipeline-build-failed", "publisher": { "@type": "Organization", "name": "FixWikiHub", "url": "https://www.fixwikihub.com" }, "author": { "@type": "Person", "name": "FixWikiHub Editorial Team" }, "datePublished": "2026-04-04T14:11:36.081Z", "dateModified": "2026-04-04T14:11:36.081Z" } </script>