In this guide, you’ll learn how to deploy a Dockerized Node.js application to an AWS EC2 instance using a Jenkins Pipeline. We’ll cover every step—from adding a deploy stage and managing Docker containers on EC2, to conditional execution and verifying your deployment. Table of ContentsDocumentation Index
Fetch the complete documentation index at: https://notes.kodekloud.com/llms.txt
Use this file to discover all available pages before exploring further.
- Prerequisites
- Adding the Deploy Stage
- Stopping & Removing the Existing Container
- Running the New Container
- Wrapping in a
scriptBlock - Conditional Execution with
when - Verifying the Deployment
- Links and References
Prerequisites
- A Jenkins instance with the SSH Agent plugin installed
- An AWS EC2 Ubuntu server accessible via SSH
- A Dockerized application pushed to a Docker registry
- Jenkins credentials configured for:
- SSH key (e.g.,
aws-dev-deploy-ec2-instance) - MongoDB username & password (
mongo-db-username,mongo-db-password)
- SSH key (e.g.,
1. Adding the Deploy Stage
After yourPush Docker Image stage, insert a new stage called Deploy - AWS EC2. Here’s the skeleton of your declarative pipeline:
| Stage Name | Description |
|---|---|
| Build Docker Image | Build and tag your Docker image |
| Trivy Vulnerability Scanner | Scan the image for vulnerabilities |
| Push Docker Image | Push the image to your Docker registry |
| Deploy - AWS EC2 | SSH into EC2 and restart the container |
aws-dev-deploy-ec2-instance.
2. Stopping & Removing the Existing Container
Use an SSH one-liner to detect if thesolar-system container is running, then stop and remove it:
Suppressing
StrictHostKeyChecking avoids interactive host key prompts, which is essential for unattended CI/CD pipelines.3. Running the New Container
Next, start a fresh container with your environment variables. These variables come from the globalenvironment block in your Jenkinsfile:
| Variable | Source |
|---|---|
| MONGO_URI | Hard-coded connection string |
| MONGO_USERNAME | Jenkins credential mongo-db-username |
| MONGO_PASSWORD | Jenkins credential mongo-db-password |
| GIT_COMMIT | Jenkins built-in variable |
4. Wrapping in a script Block
Because we’re using conditional logic (if), wrap the SSH commands in a script step inside the declarative stage:
5. Conditional Execution with when
Run the deploy stage only on feature branches by adding a when condition. You can also configure this filter in the Jenkins UI:
Using
when { branch 'feature/*' } ensures that deployment only triggers for feature branches, preventing accidental prod deployments.6. Verifying the Deployment
-
Check Jenkins Console
Sample logs:
-
On the EC2 Instance
Expected output:
-
Access the Application
Open a browser and navigate to: