-
Notifications
You must be signed in to change notification settings - Fork 0
/
jenkinsfile
87 lines (79 loc) · 2.51 KB
/
jenkinsfile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
pipeline {
agent {
docker { image 'node:14-alpine' }
}
environment {
DOCKERHUB_CREDENTIALS = credentials('dockerhub-credentials-id')
IMAGE_NAME = 'my-nodejs-app'
}
stages {
stage('Checkout') {
steps {
git branch: 'main', url: 'https://github.com/Denish3436/nodejs-app.git'
}
}
stage('Build Docker Image') {
steps {
script {
docker.build("${env.IMAGE_NAME}:${env.BUILD_NUMBER}")
}
}
}
stage('Run Tests') {
steps {
script {
docker.image("${env.IMAGE_NAME}:${env.BUILD_NUMBER}").inside {
sh 'npm install'
sh 'npm test'
}
}
}
}
stage('Push Docker Image') {
steps {
script {
docker.withRegistry('https://registry.hub.docker.com', 'DOCKERHUB_CREDENTIALS') {
docker.image("${env.IMAGE_NAME}:${env.BUILD_NUMBER}").push()
}
}
}
}
stage('Deploy to Staging') {
steps {
script {
sh '''
docker pull ${env.IMAGE_NAME}:${env.BUILD_NUMBER}
docker stop staging-container || true
docker rm staging-container || true
docker run -d --name staging-container -p 8080:8080 ${env.IMAGE_NAME}:${env.BUILD_NUMBER}
'''
}
}
}
stage('Optional: Deploy to Production') {
when {
branch 'main'
}
steps {
script {
sh '''
docker pull ${env.IMAGE_NAME}:${env.BUILD_NUMBER}
docker stop production-container || true
docker rm production-container || true
docker run -d --name production-container -p 80:8080 ${env.IMAGE_NAME}:${env.BUILD_NUMBER}
'''
}
}
}
}
post {
always {
cleanWs()
}
failure {
mail to: '[email protected]',
subject: "Failed Pipeline: ${currentBuild.fullDisplayName}",
body: "Something is wrong with ${env.JOB_NAME} ${env.BUILD_NUMBER}. Please check the logs."
}
}
}