⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:


Hey β€” It's Sandip Das πŸ‘‹

Using Jenkins to build Docker images and push to ECR makes deployments smooth and repeatable without the manual hassle.
It’s a game-changer for speeding up releases and keeping things clean and consistent across environments.

πŸ’‘ Prerequisites

  1. Jenkins with Docker installed on the agent.
  2. AWS CLI is installed and configured with proper IAM credentials, or the proper AWS IAM role is assigned if using AWS EC2.
  3. AWS ECR repository already created (e.g., 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app).

🧠 Learn here Step by Step:

Build Docker Image Using Jenkins Pipeline & Push to AWS ECR

Final Flow

πŸš€ Step 1: Install Jenkins

πŸ–₯️ For Ubuntu/Debian Based Systems:

# 1. Install Java (current Jenkins LTS requires Java 21+)
sudo apt update
sudo apt install -y fontconfig openjdk-21-jre

# 2. Add the Jenkins LTS repository and its signing key
sudo mkdir -p /etc/apt/keyrings
sudo wget -O /etc/apt/keyrings/jenkins-keyring.asc \
  https://pkg.jenkins.io/debian-stable/jenkins.io-2026.key
echo "deb [signed-by=/etc/apt/keyrings/jenkins-keyring.asc] https://pkg.jenkins.io/debian-stable binary/" | \
  sudo tee /etc/apt/sources.list.d/jenkins.list > /dev/null

# 3. Install Jenkins
sudo apt update
sudo apt install -y jenkins

# 4. Start Jenkins and enable at boot
sudo systemctl enable --now jenkins

☁️ For Amazon Linux 2023:

# 1. Update the system
sudo dnf upgrade -y

# 2. Install Java 21 (Amazon Corretto)
sudo dnf install -y fontconfig java-21-amazon-corretto

# 3. Add the Jenkins LTS repo
sudo wget -O /etc/yum.repos.d/jenkins.repo https://pkg.jenkins.io/rpm-stable/jenkins.repo

# 4. Install Jenkins
sudo dnf install -y jenkins
sudo systemctl daemon-reload

# 5. Start Jenkins and enable at boot
sudo systemctl enable --now jenkins

# 6. (Optional) Allow firewall access (if using firewalld)
sudo firewall-cmd --permanent --add-port=8080/tcp
sudo firewall-cmd --reload

🚨 Note: If you're deploying on AWS EC2, ensure port 8080 is open in your Security Groups.

πŸ“¦ For installation on other OS platforms, follow the official Jenkins documentation: πŸ‘‰ https://www.jenkins.io/doc/book/installing/

πŸ” Get Admin Password

After installation, retrieve the initial admin password:

sudo cat /var/lib/jenkins/secrets/initialAdminPassword

Then access Jenkins at:
🌐 http://<your-server-ip>:8080
Paste the password to unlock Jenkins and complete the setup wizard.

🐳 Step 2: Install Docker

πŸ–₯️ Install Docker on Ubuntu/Debian

# 1. Update packages
sudo apt update

# 2. Install dependencies
sudo apt install -y \
  ca-certificates \
  curl \
  gnupg \
  lsb-release

# 3. Add Docker’s GPG key
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | \
  sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg

# 4. Add Docker's repository
echo \
  "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
  https://download.docker.com/linux/ubuntu \
  $(lsb_release -cs) stable" | \
  sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

# 5. Install Docker
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

# 6. Enable and start Docker
sudo systemctl enable docker
sudo systemctl start docker

# 7. Let the jenkins user (and your user) run Docker without sudo
sudo usermod -aG docker jenkins
sudo usermod -aG docker $USER

☁️ Install Docker on Amazon Linux 2023

# 1. Install Docker
sudo dnf install -y docker

# 2. Start and enable Docker
sudo systemctl enable --now docker

# 3. Let ec2-user and the jenkins user run Docker
sudo usermod -aG docker ec2-user
sudo usermod -aG docker jenkins

πŸ’‘ Logout and log back in to apply Docker group permissions (or restart Jenkins if it runs as a service).

πŸ” Restart Jenkins:

# Restart Jenkins
sudo systemctl restart jenkins

# Check Jenkins status
sudo systemctl status jenkins

βœ… Verify Docker Installation

docker version
docker run hello-world

πŸ“¦ For installation on other OS platforms, follow Docker's official documentation: πŸ‘‰ https://docs.docker.com/get-docker/

☁️ Step 3: Install AWS CLI

πŸ–₯️ Install AWS CLI on Ubuntu

# 1. Update packages
sudo apt update

# 2. Install required dependencies
sudo apt install -y unzip curl

# 3. Download AWS CLI v2 installer
curl "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"

# 4. Unzip and install
unzip awscliv2.zip
sudo ./aws/install

# 5. Verify installation
aws --version

☁️ Install AWS CLI on Amazon Linux 2023

# AWS CLI v2 comes preinstalled on Amazon Linux 2023
aws --version

# If it's missing:
sudo dnf install -y awscli-2

πŸ” IAM Configuration

If you're running from a local machine, use an AWS IAM User and generate Access & Secret Keys. If you're running from AWS EC2, attach an IAM Role to the instance.

Assign the following IAM Policy:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "ecr:GetDownloadUrlForLayer",
        "ecr:BatchGetImage",
        "ecr:BatchCheckLayerAvailability",
        "ecr:PutImage",
        "ecr:InitiateLayerUpload",
        "ecr:UploadLayerPart",
        "ecr:CompleteLayerUpload",
        "ecr:GetAuthorizationToken"
      ],
      "Resource": "*"
    }
  ]
}

If you're not using an IAM Role (i.e., on local VMs or non-AWS compute), configure the AWS CLI manually:

aws configure

βœ… Provide:

  • AWS Access Key ID
  • AWS Secret Access Key
  • Default region name
  • Output format (e.g., json)

πŸ“¦ For installation on other platforms, follow the official AWS instructions:
πŸ‘‰ https://docs.aws.amazon.com/cli/latest/userguide/install-cliv2.html

πŸ”§ Step 4: Install Docker and Docker Pipeline Plugin & Create ECR Repository

πŸ‘‰ Follow the instructions mentioned in the video above ☝️ to:

  • Install Docker plugin
  • Install Docker Pipeline plugin
  • Create your AWS ECR repository

Step 5: Create Jenkins Pipeline (Jenkinsfile)

βœ… Using Docker Plugin + Docker Pipeline Plugin

Update environment variables based on your ECR repository details.

pipeline {
    agent any
    environment {
        AWS_REGION = 'us-east-1'
        ECR_REPO = '123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app'
        IMAGE_NAME = 'my-app'
        IMAGE_TAG = "${env.BUILD_NUMBER}"
    }
    stages {
        stage('Checkout Code') {
            steps {
                checkout scm
            }
        }
        stage('Login to AWS ECR') {
            steps {
                sh '''
                aws ecr get-login-password --region $AWS_REGION | \
                docker login --username AWS --password-stdin $ECR_REPO
                '''
            }
        }
        stage('Build Docker Image') {
            steps {
                script {
                    def image = docker.build("${IMAGE_NAME}:${IMAGE_TAG}")
                }
            }
        }
        stage('Tag & Push to ECR') {
            steps {
                script {
                    def localTag = "${IMAGE_NAME}:${IMAGE_TAG}"
                    def remoteTag = "${ECR_REPO}:${IMAGE_TAG}"
                    sh "docker tag ${localTag} ${remoteTag}"
                    sh "docker push ${remoteTag}"
                }
            }
        }
    }
    post {
        success {
            echo "βœ… Docker Image pushed: $ECR_REPO:$IMAGE_TAG"
        }
        failure {
            echo "❌ Build failed. Please check the logs."
        }
    }
}

🚫 Without Using Docker Plugin

pipeline {
    agent any
    environment {
        AWS_REGION = 'us-east-1'
        ECR_REPO = '123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app'
        IMAGE_TAG = "my-app:${env.BUILD_NUMBER}"
    }
    stages {
        stage('Checkout Code') {
            steps {
                checkout scm
            }
        }
        stage('Login to AWS ECR') {
            steps {
                script {
                    sh '''
                    aws ecr get-login-password --region $AWS_REGION | \
                    docker login --username AWS --password-stdin $ECR_REPO
                    '''
                }
            }
        }
        stage('Build Docker Image') {
            steps {
                script {
                    sh "docker build -t $IMAGE_TAG ."
                }
            }
        }
        stage('Tag Docker Image') {
            steps {
                script {
                    sh "docker tag $IMAGE_TAG $ECR_REPO:$BUILD_NUMBER"
                }
            }
        }
        stage('Push Docker Image to ECR') {
            steps {
                script {
                    sh "docker push $ECR_REPO:$BUILD_NUMBER"
                }
            }
        }
    }
    post {
        success {
            echo "Docker Image pushed: $ECR_REPO:$BUILD_NUMBER"
        }
        failure {
            echo "Build failed. Please check the logs."
        }
    }
}

⚑ Pro Tip: Speed up builds with Docker cache (the image must carry inline cache metadata, hence BUILDKIT_INLINE_CACHE=1; the push step uses double quotes so Groovy fills in the tag variables)

pipeline {
    agent any
    environment {
        AWS_REGION = 'us-east-1'
        ECR_REPO = '123456789012.dkr.ecr.us-east-1.amazonaws.com/my-app'
        IMAGE_NAME = 'my-app'
        IMAGE_TAG = "${env.BUILD_NUMBER}"
        CACHE_TAG = "latest"
    }
    stages {
        stage('Checkout Code') {
            steps {
                checkout scm
            }
        }
        stage('Login to AWS ECR') {
            steps {
                sh '''
                aws ecr get-login-password --region $AWS_REGION | \
                docker login --username AWS --password-stdin $ECR_REPO
                '''
            }
        }
        stage('Pull Previous Image for Caching') {
            steps {
                script {
                    sh '''
                    docker pull ${ECR_REPO}:${CACHE_TAG} || echo "No cache image found, building fresh."
                    '''
                }
            }
        }
        stage('Build Docker Image with Cache') {
            steps {
                script {
                    def localTag = "${IMAGE_NAME}:${IMAGE_TAG}"
                    def cacheFrom = "${ECR_REPO}:${CACHE_TAG}"
                    def image = docker.build(localTag, "--cache-from=${cacheFrom} --build-arg BUILDKIT_INLINE_CACHE=1 .")
                }
            }
        }
        stage('Tag & Push to ECR') {
            steps {
                script {
                    def localTag = "${IMAGE_NAME}:${IMAGE_TAG}"
                    def buildTag = "${ECR_REPO}:${IMAGE_TAG}"
                    def latestTag = "${ECR_REPO}:${CACHE_TAG}"
                    sh """
                    docker tag ${localTag} ${buildTag}
                    docker tag ${localTag} ${latestTag}
                    docker push ${buildTag}
                    docker push ${latestTag}
                    """
                }
            }
        }
    }
    post {
        success {
            echo "βœ… Docker Image pushed with cache: $ECR_REPO:$IMAGE_TAG"
        }
        failure {
            echo "❌ Build failed. Please check the logs."
        }
    }
}

⚑ Quick Reference

Keep the momentum going β€” everything you need on LearnXOps in one place:

Share this post