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

  1. Log in to the AWS Management Console.
  2. Navigate to the EC2 Dashboard and click Launch Instance.
  3. Choose an Amazon Machine Image (AMI) such as Amazon Linux 2 or Ubuntu.
  4. Select an instance type (e.g., t2.micro for free-tier usage).
  5. Configure security groups to allow inbound SSH (port 22) and application-specific ports.
  6. Launch the instance and download the key pair for SSH access.

Step 2: Connect to the EC2 Instance

  1. Open a terminal and navigate to the key pair’s location.
  2. Connect via SSH:

ssh -i keyfile.pem ec2-user@your-ec2-instance-ip

Step 3: Install Docker on EC2

  1. Update the package list:


sudo yum update -y   # For Amazon Linux

sudo apt update -y   # For Ubuntu

  1. Install Docker:


sudo yum install docker -y  # Amazon Linux

sudo apt install docker.io -y  # Ubuntu

  1. Start and enable Docker:


sudo systemctl start docker

sudo systemctl enable docker

  1. Add the user to the Docker group (optional):

sudo usermod -aG docker ec2-user

Step 4: Pull and Run a Docker Container

  1. Pull a Docker image (e.g., Nginx):

docker pull nginx

  1. Run the Docker container:

docker run -d -p 80:80 nginx

  1. Verify the running container:

docker ps

Step 5: Configure Security Group for HTTP Access

  1. In the AWS EC2 dashboard, locate the instance’s security group.
  2. Edit inbound rules to allow HTTP traffic (port 80).
  3. 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)

  1. 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

  1. Create a docker-compose.yml file:


version: ‘3’

services:

  web:

    image: nginx

    ports:

       “80:80”

  1. 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.