Introduction
Creating a Jenkins pipeline for a Node.js application involves setting up a Jenkinsfile which describes the pipeline stages and steps. Here is a simple example to guide you through the essential stages such as checkout, build, test, and deploy.
Jenkinsfile
Create a file named Jenkinsfile in your repository and populate it as follows:
pipeline {
agent any // Run on any available agent
environment {
NODE_ENV = 'production'
}
stages {
stage('Checkout') {
steps {
// Checkout the code from the version control system.
checkout scm
}
}
stage('Install Dependencies') {
steps {
// Install Node.js modules
sh 'npm install'
}
}
stage('Lint') {
steps {
// Perform linting.
sh 'npm run lint'
}
}
stage('Test') {
steps {
// Run unit tests.
sh 'npm test'
}
}
stage('Build') {
steps {
// Build the project. This could also include transpiling code.
sh 'npm run build'
}
}
stage('Deploy') {
steps {
// Your deployment logic here.
// For example, you could upload build artifacts to a web server.
sh './deploy.sh'
}
}
}
post {
always {
// Archive the build artifacts and test results.
archiveArtifacts artifacts: '**/target/*.jar', allowEmptyArchive: true
junit '**/target/test-*.xml'
}
success {
echo 'Build and Deploy succeeded.'
}
failure {
echo 'Build or Deploy failed.'
}
}
}Code language: PHP (php)
Explanation
- Agent: Specifies where the pipeline will run.
anymeans it can run on any available agent. - Environment: Environment variables can be set for the entire pipeline.
- Stages: The pipeline is divided into multiple stages, each of which consists of multiple steps.
- Checkout: Checks out the source code from the repository.
- Install Dependencies: Installs required Node.js modules using
npm install. - Lint: Lints the source code using
npm run lint. - Test: Runs unit tests using
npm test. - Build: Builds the application using
npm run build. - Deploy: Deploys the application. This is a placeholder, and you’ll need to fill in the actual deployment steps based on your requirements.
- Post: Defines additional steps that run after the stages have completed.
- always: Always run these steps, irrespective of the build status.
- success: Run steps if the pipeline was successful.
- failure: Run steps if the pipeline failed.
This is a basic example and may not cover all the specific requirements you might have. Depending on your project’s needs, you may need to add additional stages or modify existing ones. This could include steps for database migration, setting environment variables, caching, etc.