Skip to main content
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 Contents
  1. Prerequisites
  2. Adding the Deploy Stage
  3. Stopping & Removing the Existing Container
  4. Running the New Container
  5. Wrapping in a script Block
  6. Conditional Execution with when
  7. Verifying the Deployment
  8. 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)

1. Adding the Deploy Stage

After your Push Docker Image stage, insert a new stage called Deploy - AWS EC2. Here’s the skeleton of your declarative pipeline:
We’ll use the SSH Agent plugin to authenticate to EC2 using the private key credential aws-dev-deploy-ec2-instance.

2. Stopping & Removing the Existing Container

Use an SSH one-liner to detect if the solar-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 global environment block in your Jenkinsfile:
Define your environment variables at the top of the Jenkinsfile:

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

  1. Check Jenkins Console
    Sample logs:
  2. On the EC2 Instance
    Expected output:
  3. Access the Application
    Open a browser and navigate to:
Integration testing should follow to validate your application endpoints and data flow.
Happy Deploying!

Watch Video