End-to-End Guide: Pushing a Docker Image to AWS ECR from an EC2 Instance
In this step-by-step guide, you’ll learn how to build a Docker image on an Amazon EC2 Instance and push it to Amazon Elastic Container Registry (ECR). We’ll cover everything from setting up your EC2 instance to advanced configurations like IAM roles and lifecycle policies. Let’s dive in!
Table of Contents
- Introduction to AWS ECR and EC2
- Prerequisites
- Step 1: Set Up an EC2 Instance
- Step 2: Install Docker on the EC2 Instance
- Step 3: Create an ECR Repository
- Step 4: Authenticate Docker with AWS ECR
- Step 5: Build a Docker Image
- Step 6: Tag the Docker Image
- Step 7: Push the Docker Image to ECR
- Step 8: Verify the Image in ECR
- Optional Configurations and Best Practices
- Troubleshooting Common Issues
1. Introduction to AWS ECR and EC2
Amazon Elastic Container Registry (ECR)
ECR is a fully managed Docker container registry that integrates seamlessly with AWS services like ECS, EKS, and Lambda. It provides secure, scalable storage for Docker images and supports vulnerability scanning and lifecycle management.
Amazon EC2 (Elastic Compute Cloud)
EC2 offers resizable compute capacity in the cloud. It’s ideal for hosting applications, running batch processes, and building CI/CD pipelines. In this guide, we’ll use an EC2 instance to build and push a Docker image to ECR.
2. Prerequisites
Before starting, ensure you have:
- An AWS account with permissions to create EC2 instances and ECR repositories.
- AWS CLI installed on your local machine (optional but recommended for advanced users).
- Basic familiarity with Docker, Linux commands, and AWS services.
3. Step 1: Set Up an EC2 Instance
3.1 Launch an EC2 Instance
- Log in to the AWS Management Console.
- Navigate to EC2 > Instances > Launch Instances.
- Choose an Amazon Machine Image (AMI):
- Amazon Linux 2023 (for simplicity) or Ubuntu 22.04 LTS.
- Select an instance type (e.g.,
t2.micro
for testing). - Configure security groups to allow SSH (Port 22).
- Launch the instance and download the key pair (
.pem
file).
3.2 Connect to the EC2 Instance
Use SSH to connect:
- For Amazon Linux:
ssh -i /path/to/key.pem ec2-user@<public-ip>
- For Ubuntu:
ssh -i /path/to/key.pem ubuntu@<public-ip> # Default username is "ubuntu"
4. Step 2: Install Docker on the EC2 Instance
4.1 Update Packages
- Amazon Linux:
sudo yum update -y
- Ubuntu:
sudo apt update -y && sudo apt upgrade -y
4.2 Install Docker
- Amazon Linux:
sudo yum install docker -y sudo systemctl start docker sudo usermod -aG docker ec2-user # Add user to the "docker" group
- Ubuntu:
sudo apt install docker.io -y sudo systemctl start docker sudo usermod -aG docker ubuntu # Replace "ubuntu" with your username
4.3 Apply Changes
After adding the user to the Docker group, restart your SSH session or run:
newgrp docker # Activates group changes without re-logging in
Verify Docker installation:
docker --version # Output: Docker version 24.0.6, build ed223bc
5. Step 3: Create an ECR Repository
- Go to the ECR Dashboard in the AWS Console.
- Click Create repository.
- Configure settings:
- Repository name:
my-app-repo
(project-specific name). - Tag immutability: Enable to prevent overwriting images.
- Scan on push: Enable automatic vulnerability scanning.
- Repository name:
- Click Create repository.
6. Step 4: Authenticate Docker with AWS ECR
6.1 Install AWS CLI (if not already installed)
- Amazon Linux:
sudo yum install aws-cli -y
- Ubuntu:
sudo apt install awscli -y
6.2 Configure AWS Credentials
Run aws configure
and provide:
- AWS Access Key ID and Secret Access Key (for IAM users).
- Default region (e.g.,
us-east-1
).
Optional: Instead of credentials, attach an IAM role to your EC2 instance with ECR permissions (see Step 11.1).
6.3 Authenticate Docker with ECR
Replace <account-id>
and <region>
with your AWS account ID and region (e.g., 123456789012
and us-east-1
):
aws ecr get-login-password --region <region> | \
docker login --username AWS --password-stdin <account-id>.dkr.ecr.<region>.amazonaws.com
Successful output: Login Succeeded
.
7. Step 5: Build a Docker Image
7.1 Create a Sample Application
- Create a project directory:
mkdir my-app && cd my-app
- Create a
Dockerfile
:nano Dockerfile
- Add the following content (example Node.js app):
FROM node:18-alpine WORKDIR /app COPY package.json . RUN npm install COPY . . EXPOSE 3000 CMD ["node", "index.js"]
7.2 Build the Image
docker build -t my-app .
Explanation:
-t my-app
: Tags the image asmy-app:latest
..
: Build context (current directory).
8. Step 6: Tag the Docker Image
Why Tagging Matters
ECR requires images to be tagged with the repository URI to identify where to push them.
Tag the Image
Use your ECR repository URI (found in the ECR Console):
docker tag my-app:latest <account-id>.dkr.ecr.<region>.amazonaws.com/my-app-repo:latest
9. Step 7: Push the Docker Image to ECR
Run the push command:
docker push <account-id>.dkr.ecr.<region>.amazonaws.com/my-app-repo:latest
Output:
latest: digest: sha256:... size: 2200
10. Step 8: Verify the Image in ECR
- Go to the ECR Dashboard.
- Select your repository (
my-app-repo
). - Confirm the image appears under Images.
11. Optional Configurations and Best Practices
11.1 Use IAM Roles Instead of AWS Credentials
- Create an IAM role with the AmazonEC2ContainerRegistryFullAccess policy.
- Attach the role to your EC2 instance:
- Go to EC2 > Instances > Actions > Security > Modify IAM Role.
Example IAM Policy (minimal permissions):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:GetDownloadUrlForLayer",
"ecr:PutImage"
],
"Resource": "*"
}
]
}
11.2 Enable Lifecycle Policies
Automatically delete untagged or old images:
- In your ECR repository, go to Lifecycle Policies > Create.
- Add rules (e.g., “Expire images older than 30 days”).
11.3 Multi-Stage Docker Builds
Reduce image size by separating build and runtime environments:
# Build stage
FROM node:18 AS builder
WORKDIR /app
COPY . .
RUN npm install && npm run build
# Runtime stage
FROM nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
12. Troubleshooting Common Issues
Issue 1: “no basic auth credentials” Error
- Cause: Docker is not authenticated with ECR.
- Fix: Re-run the
aws ecr get-login-password
command.
Issue 2: “Requested access to the resource is denied”
- Cause: The IAM role or user lacks ECR permissions.
- Fix: Attach the
AmazonEC2ContainerRegistryFullAccess
policy.
Issue 3: Large Image Push Failures
- Cause: ECR has a 10GB layer size limit.
- Fix: Optimize layers or split large files.
By following this guide, you’ve successfully pushed a Docker image to AWS ECR from an EC2 instance. You’ve also learned advanced practices like IAM roles, lifecycle policies, and multi-stage builds. These steps form the foundation for deploying scalable containerized applications on AWS.
Next Steps
- Automate the process using AWS CodePipeline or GitHub Actions.
- Explore deploying your image to Amazon ECS or EKS.
Labels: End-to-End Guide: Pushing a Docker Image to AWS ECR from an EC2 Instance
0 Comments:
Post a Comment
Note: only a member of this blog may post a comment.
<< Home