How to write a Jenkinsfile?

· Category: DevOps & CI/CD

Short answer

A Jenkinsfile is a text file containing the definition of a Jenkins pipeline. It can be written in declarative or scripted syntax and is stored in version control alongside application code.

Steps

  1. Create a file named Jenkinsfile in the repository root.
  2. Define the pipeline block.
  3. Specify the agent.
  4. Add stages and steps.
  5. Configure post-build actions.

Example

pipeline {
    agent any
    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }
        stage('Build') {
            steps {
                sh 'npm ci'
                sh 'npm run build'
            }
        }
        stage('Test') {
            steps {
                sh 'npm test'
            }
        }
    }
    post {
        always {
            junit 'reports/**/*.xml'
        }
    }
}

Tips

  • Use declarative pipelines for standard workflows.
  • Use scripted pipelines only when you need advanced logic.
  • Validate Jenkinsfile syntax with the Jenkins linter.

Common issues

  • Missing agent causes the pipeline to fail.
  • Shell commands behave differently on Windows and Linux agents.
  • Credentials must be referenced with withCredentials.