• TechOps

    Need clarity?
    Chat with our experts now

    • Web Hosting SupportWeb Hosting Support
    • Helpdesk Support

      Skilled and professional 24/7 helpdesk support

    • Product Support

      Boost your product support with our expertise

    • Managed ServicesManaged Services
    • Server Management

      Don't let server issues slow you down. Let us manage them for you

    • Server Monitoring

      Safeguard your server health with our comprehensive monitoring solutions

    • Staff AugmentationStaff Augmentation
    • Hire an Admin

      Transform your business operations with our expert administrative support

    • Hire a Team

      Augment your workforce with highly skilled professional from our diverse talent pool

  • CloudOps

    Confused?
    Discuss with our sales team now.

    • Author ProfileAWS
      Well Architected Review
    • Author ProfileFinOps As a Service

      FinOps As a Service

    • Migrate

      Upgrade the journey: Migrate & Modernize seamlessly

    • Modernize

      Effortless CloudOps mastery for seamless cloud management

    • Optimize

      Efficient CloudOps: Boosting performance through optimization

    • Manage

      Simplify compliance complexities with our dedicated service

  • DevOps

    How Supportsages
    is creating an
    impact?

    View Casestudies
    • Author Profile24/7 DevOps As a Service

      Round-the-clock DevOps for uninterrupted efficiency

    • Author ProfileCI/CD Pipeline

      Automated CI/CD pipeline for seamless deployments

    • Author ProfileInfrastructure As a Code

      Crafting infrastructure with ingenious code

    • Author ProfileDevSecOps

      Integrated security in continuous DevOps practices

    • Author ProfileHire DevOps Engineers

      Level up your team with DevOps visionaries

    • Author ProfileConsulting Services

      Navigate success with expert DevOps consulting

  • SecOps

    Expert SecOps Services
    for any Scale

    • Author ProfileVAPT

      Vulnerability Assessment and Penetration Testing

    • Author ProfileSource Code Review

      Ensuring source code security and safe practices to reduce risks

    • Author ProfileSecurity Consultation

      On demand services for improving server security

    • Author ProfileSystem Hardening

      Reduced vulnerability and proactive protection

    • Author ProfileManaged SOC

      Monitors and maintains system security. Quick response on incidents

    • Author ProfileCompliance as a Service

      Regulatory compliance, reduced risk

  • Insights

    Explore our latest
    insights and resources

    Blog

    Explore our latest articles and insights

    Case Studies

    Read about our client success stories

  • Contact Us

  • About
  • Certifications
  • Life at Supportsages
  • Events
  • Contact
  • Careers
  • Blog

  • Dedicated Support Team
  • Quasi-dedicated Support Team
  • Hire a DevOps Engineer
  • Hire a Billing Support Staff
  • Per-ticket Support Plan
  • Managed Services

  • Microsoft Azure Expert
  • AWS Cloud Expert
  • Hire a developer
SS

SupportSages

Bites of wisdom @ work


Copyright © 2008 - 2026 SupportSages Pvt Ltd. All Rights Reserved.
Privacy PolicyLegal TermsData ProtectionCookie Policy

How to deploy container image from ECR to EC2 instances using AWS code-deploy agent

TECH

  • 6 min read
How to deploy container image from ECR to EC2 instances using AWS code-deploy agent

Generating audio, please wait...

In this blog, we are going to learn how to deploy a container image from AWS ECR to an EC2 instance using AWS code-deploy. Prerequisite:

Aws account with access.

Must have an ec2 instance with docker and code-deploy agent installed.

Follow https://docs.aws.amazon.com/codedeploy/latest/userguide/codedeploy-agent-operations-install.html

You must already have a code code-commit Repo with your codes.

Steps Involved:

1: Create the files in the repo which is used by the code-deploy agent to deploy the image.

2: Create an ECR Repo in order to push the docker image.

3:Creating a build project which fetches artifacts from the code-commit repo and builds the docker image and pushes to ECR.

4:Create a code-deploy application and deployment group with consist of an ec2 instance.

5: Automate the process using a code pipeline.

Step-1: Create appspec.yaml file for Code-deploy.

Here we are assuming your repo already has a Dockerfile which is tested and working fine to build the image.

The appspec.yaml file in AWS CodeDeploy is used to define the deployment configuration for an application. It specifies details such as the location of the application files, the scripts to run during the deployment process, and the environment variables to set. The file is used by the CodeDeploy service to manage and automate the deployment of the application to the specified instances.

Here the code-deploy detects the app spec file and it is just calling a script to execute.

version: 0.0 os: linux
hooks: 
ApplicationStart:
- location: start-process.s 
timeout: 00

The script

#!/bin/bash 
container_name=name

#ECR Login
aws ecr get-login-password --region us-east-1 | docker login --username AWS --password-stdin awsaccountid.dkr.ecr.us-east-1.am

#Pulling image from ECR
docker pull .dkr.ecr.us-east-1.amazonaws.com/image:latest

##Changing image tag
docker image tag awsaccountid.dkr.ecr.us-east-1.amazonaws.com/image:latest $container_name:latest

#stop and remove the current container docker rm -f $container_name

#Creating and starting a docker container using a new image
docker run -d -p 80:80 --name $container_name $container_name:latest

This script is used to deploy a Docker container to a host. The script performs the following actions:

  1. It defines a variable container_name with the desired name for the container.
  2. It logs in to the AWS Elastic Container Registry (ECR) using the aws ecr get-login-password command, which retrieves an authentication token for the registry. The docker login command is then used to log in to the registry using the retrieved token.
  1. The script pulls the latest version of an image from the specified ECR repository.
  2. It changes the image tag to the desired container name and tag version.
  3. The script stops and removes the currently running container with the same name defined in the variable.
  4. Finally, it creates and starts a new Docker container using the new image, mapping port 80 of the host to port 80 of the container and naming it with the defined container_name variable.

This script can be used as a part of the deploy command in the appspec.yaml file in AWS CodeDeploy.

Step-2: Create an ECR repo.

To create an Amazon Elastic Container Registry (ECR) repository and push a Docker image to it, you can follow these steps:

  1. Open the Amazon ECR console in the AWS Management Console
  2. Choose the region where you want to create the repository.
  3. Choose to Create a repository.
  4. Enter a repository name and choose to Create repository.

Step-3: Create a Build project.

Creating a building project which fetches artifacts from the code-commit repo and builds the docker image and pushes to ECR.

  1. Click on the “Create project” button.
  2. Enter a name for the project and select the source repository that contains the code you want to build.
  3. Choose the environment for your You can either use one of the pre-configured environments or create a custom environment.
  4. Define the build specification for your project.
  5. Set up the Artifacts that will be produced by the Artifacts can be stored in Amazon S3 or AWS CodeArtifact.
  6. Configure the build settings, including the build timeout, AWS Identity and Access Management (IAM) roles, and any additional environment variables.
  7. Review the build project settings and click the “Create project” button to create the project.

The build spec for building the image and pushing it to ECR.

version: 0.2

env:
variables: 
   IMAGE_TAG: "latest"
   IMAGE_REPO_NAME: ".dkr.ecr.us-east-1.amazonaws.com/repo-name"

phases: 
  pre_build:
    commands:
    -$(aws ecr get-login --no-include-email --region us-east-1)

build:
  commands:
     - echo Build started on `date`
     - echo Building the Docker image...
     - docker build --build-arg AWS_CONTAINER_CREDENTIALS_RELATIVE_URI=$AWS_CONTAINER_CREDENTIALS_RELATIVE_URI
     --build-arg AWS_REGION=$AWS_REGION -t .dkr.ecr.us-east-1.amazonaws.com/repo-name:latest . 
post_build:
  commands:
     - echo Build completed on `date`
     - echo Pushing the Docker image...
     - docker push $IMAGE_REPO_NAME:$IMAGE_TAG
     - printf '[{"name":"image-name","imageUri":"%s"}]' .dkr.ecr.us-east-1.amazonaws.com/repo-name:latest > i artifacts:
files:
-	imagedefinitions.json
-	appspec.yml
-	start-process.sh


 

The version of the buildspec file format is version 0.2. The environment variables, which include the IMAGE_TAG, IMAGE_REPO_NAME, and several others retrieved from the AWS Systems Manager Parameter Store. These must be the name of the ECR repo which you have created in step 2.

The build phases, include pre_build, build, and post_build. In the pre_build phase, the Docker login command is executed to authenticate to the Amazon Elastic Container Registry (ECR).

The build phase contains the commands for building the Docker image.

The post_build phase contains the commands for pushing the image to ECR.

The artifacts, include a file named “imagedefinitions.json,” “appspec.yml,” and “start-process.sh.” These files will be produced as the output of the build process.

Create a code-deploy

  1. Open the AWS CodeDeploy console.
  2. Choose to Create application.
  3. In the Application name section, specify a name for the application, In the Compute platform section, choose EC2/On-premises. the choose create an application.
  4. Choose to Create a deployment group.
  5. In the Application name section, choose the application you just created.
  6. In the Deployment group name section, specify a name for the deployment group.
  7. In the Environment configuration section, choose Amazon EC2.
  8. In the Deployment settings section, choose the deployment method and configure any other deployment-specific settings.
  9. In the Deployment configuration section, choose the deployment configuration and specify any additional settings.
  10. In the Service role section, choose an existing role or create a new one with sufficient permissions to access and deploy to the EC2 instances.

Create a pipeline to automate all the processes and add the source-build-deploy stage in the pipeline so that each push to the repo will result in deploy of the image to the ec2 instance.

  • AWS

Looking for AWS Experts?

We provide top-of-the-line custom AWS setup services tailored to your needs.

How to deploy container image from ECR to EC2 instances using AWS code-deploy agent

Creating Cloudwatch Alarm and pushing the Notifications to Email

Creating Cloudwatch Alarm and pushing the Notifications to Email
  • AWS
logo

How to create multiple S3 buckets using Cloudformation template

How to create multiple S3 buckets using Cloudformation template
  • AWS
logo

How to install apache on ubuntu 20.04 using ansible roles.

How to install apache on ubuntu 20.04 using ansible roles.
  • Apache
logo
Posts by TECH

TECH