In this exercise, you will set up a Jenkins Pipeline to:
- Pull a React App from GitHub
- Build the React app inside a Docker container
- Run the Docker container on the same Jenkins server
- Jenkins installed on your server.
- Docker installed (
docker --version
to check). - Jenkins user added to the Docker group (to avoid permission issues):
sudo usermod -aG docker jenkins
- Node.js installed (for building React app).
- A GitHub repository containing a React app with a
Dockerfile
.
If you don’t have a Dockerized React App, create a simple one:
npx create-react-app my-app
cd my-app
Create a Dockerfile in the root:
# Base image
FROM node:18-alpine
# Set working directory
WORKDIR /app
# Copy package.json and install dependencies
COPY package.json ./
RUN npm install
# Copy all files
COPY . .
# Build the React app
RUN npm run build
# Serve app with a lightweight web server
RUN npm install -g serve
CMD ["serve", "-s", "build", "-l", "3000"]
# Expose port
EXPOSE 3000
Initialize Git and push to GitHub:
git init
git add .
git commit -m "Initial commit"
git branch -M main
git remote add origin https://github.com/your-username/my-react-app.git
git push -u origin main
- Go to Jenkins Dashboard → Click
New Item
- Enter Job Name → Select
Pipeline
- Click OK → Scroll to
Pipeline
Section - Choose Pipeline script from SCM and enter your GitHub repository URL.
Create a Jenkinsfile
in your repository root:
pipeline {
agent any
environment {
IMAGE_NAME = "my-react-app"
CONTAINER_NAME = "react-container"
}
stages {
stage('Clone Repository') {
steps {
git branch: 'main', url: 'https://github.com/your-username/my-react-app.git'
}
}
stage('Build React App') {
steps {
sh 'npm install'
sh 'npm run build'
}
}
stage('Build Docker Image') {
steps {
sh 'docker build -t $IMAGE_NAME .'
}
}
stage('Run Docker Container') {
steps {
script {
sh '''
docker stop $CONTAINER_NAME || true
docker rm $CONTAINER_NAME || true
docker run -d -p 3000:3000 --name $CONTAINER_NAME $IMAGE_NAME
'''
}
}
}
}
post {
success {
echo "✅ React app successfully deployed! Access it at http://your-jenkins-server-ip:3000"
}
failure {
echo "❌ Build or deployment failed!"
}
}
}
- Go back to Jenkins and trigger the pipeline build.
- Once completed, check the logs for success messages.
- Open your browser and visit:
http://your-jenkins-server-ip:3000
- You should see your React app running inside the Docker container!
- Set up a GitHub Webhook to trigger Jenkins on every push.
- Configure Auto-Restart in case of failures:
docker run -d --restart unless-stopped -p 3000:3000 --name react-container my-react-app
✔ Cloned a React app from GitHub.
✔ Built and containerized it using Docker.
✔ Deployed it on the same Jenkins server.
✔ Accessed it via a web browser.
Would you like me to help you troubleshoot any steps? 🚀