Optimized Guide: Hosting a Docker Container on AWS EC2
Introduction
Deploying Docker containers on AWS EC2 is a scalable and efficient solution for hosting applications. This guide provides a step-by-step process to set up and deploy a Docker container on an AWS EC2 instance, ensuring optimal performance and security.
Prerequisites
Before starting, ensure the following:
An active AWS account
Basic knowledge of Linux and Docker
AWS CLI installed on the local machine
Security group rules allowing necessary traffic
Step 1: Launch an EC2 Instance
Log in to the AWS Management Console.
Navigate to the EC2 Dashboard and click Launch Instance.
Choose an Amazon Machine Image (AMI) such as Amazon Linux 2 or Ubuntu.
Select an instance type (e.g., t2.micro for free-tier usage).
Configure security groups to allow inbound SSH (port 22) and application-specific ports.
Launch the instance and download the key pair for SSH access.
Step 2: Connect to the EC2 Instance
Open a terminal and navigate to the key pair’s location.
Connect via SSH:
ssh -i keyfile.pem ec2-user@your-ec2-instance-ip
Step 3: Install Docker on EC2
Update the package list:
sudo yum update -y # For Amazon Linux
sudo apt update -y # For Ubuntu
Install Docker:
sudo yum install docker -y # Amazon Linux
sudo apt install docker.io -y # Ubuntu
Start and enable Docker:
sudo systemctl start docker
sudo systemctl enable docker
Add the user to the Docker group (optional):
sudo usermod -aG docker ec2-user
Step 4: Pull and Run a Docker Container
Pull a Docker image (e.g., Nginx):
docker pull nginx
Run the Docker container:
docker run -d -p 80:80 nginx
Verify the running container:
docker ps
Step 5: Configure Security Group for HTTP Access
In the AWS EC2 dashboard, locate the instance’s security group.
Edit inbound rules to allow HTTP traffic (port 80).
Save changes and test the setup by entering the EC2 instance’s public IP in a browser.
Step 6: Automate Deployment with Docker Compose (Optional)
Install Docker Compose:
sudo curl -L "https://github.com/docker/compose/releases/latest/download/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
Create a docker-compose.yml file:
version: '3'
services:
web:
image: nginx
ports:
- "80:80"
Deploy the container using:
docker-compose up -d
Conclusion
Hosting Docker containers on AWS EC2 provides flexibility and scalability for application deployment. By following this guide, users can efficiently deploy and manage Dockerized applications on AWS infrastructure.

Comments
Post a Comment