How to Set Up a Jenkins Pipeline for an Angular App and Deploy via Nginx
Introduction
This guide will walk you through setting up a Jenkins pipeline to build and deploy an Angular application using Git SCM and a Jenkinsfile. The built application will then be served using Nginx.
Prerequisites
Step 1: Creating the Jenkins Pipeline
1.1 Create a New Pipeline Job in Jenkins
Step 2: Writing the Jenkinsfile
Here’s the Jenkinsfile that defines the CI/CD pipeline:
pipeline {
agent any
environment {
BUILD_DIR = "dist/velzon" // Output folder after Angular build
DEPLOY_DIR = "/var/lib/jenkins/workspace/IMS-Frontend/ims-alert" // Target directory for deployment
}
stages {
stage('Clone Repository') {
steps {
git branch: 'main', url: 'git@github.com:MrNerdyPants/ims-alert.git'
}
}
stage('Verify Node.js and npm') {
steps {
sh 'node -v'
sh 'npm -v'
sh 'ng version'
}
}
stage('Install Dependencies') {
steps {
sh 'npm ci' // More reliable than 'npm install' for CI/CD
}
}
stage('Build Angular App') {
steps {
sh 'ng build --configuration=production'
}
}
stage('Deploy') {
steps {
script {
if (fileExists(BUILD_DIR)) {
echo "🚀 Deploying build to ${DEPLOY_DIR}..."
// Ignore errors if DEPLOY_DIR does not exist
sh "rm -rf ${DEPLOY_DIR} || true"
// Create the deployment directory
sh "mkdir -p ${DEPLOY_DIR}"
// Copy build artifacts
sh "cp -r ${BUILD_DIR}/* ${DEPLOY_DIR}/"
echo "✅ Deployment complete."
} else {
error "❌ Build directory not found: ${BUILD_DIR}"
}
}
}
}
}
post {
success {
echo '✅ Build and Deployment Successful!'
}
failure {
echo '❌ Build Failed!'
}
}
}
Explanation of Jenkinsfile Blocks
Step 3: Setting Up Nginx to Serve the Angular App
After deployment, we need to configure Nginx to serve the Angular application.
Recommended by LinkedIn
3.1 Create an Nginx Configuration File
Create a new configuration file for your application:
sudo nano /etc/nginx/sites-available/ims-alert
Add the following content:
server {
listen 80;
server_name ims-alert.example.com; # Replace with your domain or IP
root /var/lib/jenkins/workspace/IMS-Frontend/ims-alert;
index index.html;
location / {
try_files $uri /index.html;
}
error_page 404 /index.html;
location ~* \.(?:ico|css|js|gif|jpe?g|png|woff2?|eot|ttf|svg)$ {
expires 6M;
access_log off;
}
}
3.2 Enable the Configuration
sudo ln -s /etc/nginx/sites-available/ims-alert /etc/nginx/sites-enabled/
3.3 Test and Restart Nginx
Before restarting, test the Nginx configuration:
sudo nginx -t
If the test is successful, restart Nginx:
sudo systemctl restart nginx
Step 4: Running the Pipeline
Conclusion
In this guide, we set up a Jenkins pipeline for an Angular application using Git SCM and a Jenkinsfile, deployed it to a server, and configured Nginx to serve it. This setup ensures a smooth CI/CD process with automated deployment. 🚀