Build Docker Image and Push it to AWS ECR Using Jenkins
1 min readAug 25, 2024
Prerequisites:
- Jenkins server running on an EC2 instance.
- The EC2 instance should have an IAM role attached with ECR access.
- GitHub credentials should be added to the Jenkins server.
- EC2 should have Docker and AWS CLI installed.
Create AWS ECR to store images using below command line
aws ecr create-repository --repository-name jenkins-images --region us-east-1
Pipeline
Create Jenkins pipeline and add below script to it
pipeline {
agent any
environment {
IMAGE_URI = '12789321751.dkr.ecr.us-east-1.amazonaws.com/jenkins-images'
IMAGE_NAME = 'nginx'
IMAGE_TAG = 'v1'
}
stages {
stage('Checkout') {
steps {
script {
git branch: 'main', credentialsId: 'github', url: 'https://github.com/nivas-22/devops.git'
}
}
}
stage('Build') {
steps {
script {
sh '''
ls -la
docker build -t $IMAGE_URI:$IMAGE_TAG .
docker images
'''
}
}
}
stage('Push') {
steps {
script {
sh '''
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin 12789321751.dkr.ecr.us-east-1.amazonaws.com
docker push $IMAGE_URI:$IMAGE_TAG
'''
}
}
}
}
}