Skip to content

🐳 Setup Docker on AWS EC2

Deploying Docker containers on Amazon EC2 (Elastic Compute Cloud) provides a scalable and flexible environment for your applications. This tutorial will guide you through the entire process, from understanding EC2 to deploying a sample Dockerized application.


πŸ“‘ Table of Contents

  1. What is AWS EC2?
  2. Prerequisites
  3. Step 1: Launch an EC2 Instance
  4. Step 2: Connect to Your EC2 Instance
  5. Step 3: Install Docker on EC2
  6. Step 4: Deploy Your Dockerized Project
  7. Example Project Deployment
  8. Managing Docker Services
  9. Security Best Practices
  10. Conclusion
  11. Additional Resources

🌐 What is AWS EC2?

Amazon Elastic Compute Cloud (EC2) is a web service that provides secure, resizable compute capacity in the cloud. It is designed to make web-scale cloud computing easier for developers.

πŸ“Š Key Features of AWS EC2

Feature Description
Scalability Easily scale compute resources up or down based on demand.
Variety of Instances Wide range of instance types optimized for different tasks (e.g., compute, memory).
Elastic IPs Static IP addresses that can be reassigned to instances as needed.
Security Groups Virtual firewalls controlling inbound and outbound traffic to instances.
Integration Seamlessly integrates with other AWS services like S3, RDS, and IAM.

πŸ–ΌοΈ EC2 Instance Lifecycle

graph LR
    A[Launch Instance] --> B[Run]
    B --> C[Stop]
    C --> B
    B --> D[Terminate]

Figure 1: EC2 Instance Lifecycle


βš™οΈ Prerequisites

Before you begin, ensure you have the following:

  • AWS Account: Sign up here if you don't have one.
  • SSH Key Pair: For secure access to your EC2 instance.
  • Basic Linux Knowledge: Familiarity with terminal operations.
  • Docker Fundamentals: Basic understanding of Docker concepts.

πŸš€ Step 1: Launch an EC2 Instance

1. Log in to AWS Management Console πŸ–₯️

Navigate to the AWS Management Console and sign in with your credentials.

2. Navigate to EC2 Dashboard πŸ›‚

From the Services menu, select EC2 under the "Compute" category.

3. Launch Instance βž•

Click on the "Launch Instance" button to start the setup process.

4. Configure Instance Details πŸ“‹

a. Choose an Amazon Machine Image (AMI) πŸ–₯️

  • Recommendation: Ubuntu Server 20.04 LTS – Reliable and widely supported.

b. Choose an Instance Type πŸ–±οΈ

Instance Type vCPUs Memory (GB) Use Case
t2.micro 1 1 Low traffic websites
t2.medium 2 4 Small databases and apps
m5.large 2 8 Medium-sized applications
  • t2.micro: Eligible for the free tier, suitable for testing and small applications.

c. Configure Instance Details πŸ› οΈ

  • Number of Instances: 1
  • Network Settings: Default VPC is usually sufficient.
  • IAM Role: Leave as default unless specific permissions are needed.

5. Add Storage πŸ’Ύ

  • Default: 8 GB (General Purpose SSD)
  • Recommendation: Increase based on your application's needs.

6. Configure Security Group πŸ”’

Security Groups act as virtual firewalls. Configure the following inbound rules:

Type Protocol Port Range Source Description
SSH TCP 22 Your IP (x.x.x.x/32) Secure SSH access
HTTP TCP 80 Anywhere (0.0.0.0/0) Allow web traffic
HTTPS TCP 443 Anywhere (0.0.0.0/0) Allow secure web traffic

7. Review and Launch πŸš€

  • Review: Ensure all settings are correct.
  • Launch: Click "Launch" and select your SSH key pair.
  • Key Pair: Choose an existing key or create a new one. Download the .pem file and store it securely.

8. Access Your Instance πŸ”‘

Once launched, note the Public IPv4 address or Public DNS of your instance.


πŸ”— Step 2: Connect to Your EC2 Instance

1. Open Terminal πŸ–₯️

2. Set Permissions for Your SSH Key πŸ”

Ensure your .pem file has the correct permissions.

chmod 400 /path/to/your-key-pair.pem

3. Connect via SSH πŸ‘‹

ssh -i /path/to/your-key-pair.pem ubuntu@your-ec2-public-dns

πŸ“Œ Note: Replace ubuntu with the appropriate username if you're using a different AMI (e.g., ec2-user for Amazon Linux).

πŸ“Š Connection Summary

Action Command Description
Change permissions chmod 400 key-pair.pem Secure your key pair file
Connect via SSH ssh -i key-pair.pem user@ec2-dns Access your EC2 instance

πŸ‹ Step 3: Install Docker on EC2

With your EC2 instance up and running, the next step is to install Docker.

1. Update Package Information πŸ“¦

sudo apt-get update

2. Install Prerequisite Packages πŸ› οΈ

These packages allow apt to use repositories over HTTPS.

sudo apt-get install -y \
    apt-transport-https \
    ca-certificates \
    curl \
    gnupg-agent \
    software-properties-common

3. Add Docker’s Official GPG Key πŸ”‘

curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -

4. Set Up the Docker Repository πŸ“‚

sudo add-apt-repository \
   "deb [arch=amd64] https://download.docker.com/linux/ubuntu \
   $(lsb_release -cs) \
   stable"

5. Install Docker Engine 🐳

sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io

6. Verify Docker Installation βœ…

sudo docker run hello-world

You should see a message confirming that Docker is installed correctly.

7. Manage Docker as a Non-Root User πŸ‘€

Running Docker commands without sudo enhances security and convenience.

  1. Create Docker Group πŸ…Ά
sudo groupadd docker
  1. Add Your User to Docker Group πŸ§‘β€πŸ€β€πŸ§‘
sudo usermod -aG docker $USER
  1. Apply New Group Membership πŸ”„
newgrp docker
  1. Test Docker Without Sudo πŸš«πŸ”
docker run hello-world

πŸ“Œ Note: If you encounter permission issues, ensure you've logged out and back in.

πŸ“Š Docker Installation Summary

| Step | Command | Description | | -------- | --------------------------------------- | ----------------------------- | -------------------- | | 1 | sudo apt-get update | Update package lists | | 2 | sudo apt-get install -y ... | Install prerequisite packages | | 3 | curl -fsSL ... | sudo apt-key add - | Add Docker’s GPG key | | 4 | sudo add-apt-repository ... | Set up Docker repository | | 5 | sudo apt-get install -y docker-ce ... | Install Docker Engine | | 6 | sudo docker run hello-world | Verify Docker installation | | 7 | sudo groupadd docker | Create Docker group | | | sudo usermod -aG docker $USER | Add user to Docker group | | | newgrp docker | Apply group membership | | | docker run hello-world | Test Docker without sudo |


πŸ› οΈ Step 4: Deploy Your Dockerized Project

Now that Docker is installed, let's deploy a sample Node.js application using Docker Compose.

πŸ§‘β€πŸ’» Example: Deploying a Node.js App

1. Project Structure

example-app/
β”œβ”€β”€ docker-compose.yml
β”œβ”€β”€ Dockerfile
β”œβ”€β”€ src/
β”‚   └── app.js
β”œβ”€β”€ package.json
└── package-lock.json

2. Creating the Project Files

a. Initialize the Project
mkdir example-app
cd example-app
npm init -y
b. Install Dependencies
npm install express
c. Create app.js
// src/app.js
const express = require("express");
const app = express();
const port = 3000;

app.get("/", (req, res) => {
  res.send("Hello from Docker on AWS EC2!");
});

app.listen(port, () => {
  console.log(`App running on port ${port}`);
});
d. Create Dockerfile
# Dockerfile
FROM node:14

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package*.json ./
RUN npm install

# Bundle app source
COPY . .

# Expose port
EXPOSE 3000

# Start the app
CMD [ "node", "src/app.js" ]
e. Create docker-compose.yml
version: "3"
services:
  web:
    build: .
    ports:
      - "80:3000"
    environment:
      NODE_ENV: production

3. Deploying the Application

a. Clone the Project (If Applicable)

If your project is hosted on GitHub or another repository:

git clone https://github.com/your-repo/example-app.git
cd example-app
b. Run Docker Compose
docker-compose up --build -d
  • --build: Builds the image before starting containers.
  • -d: Runs containers in detached mode.
c. Verify Deployment

Open your web browser and navigate to http://your-ec2-public-ip. You should see:

Hello from Docker on AWS EC2!

πŸ“¦ Using Environment Variables with Docker

Environment variables allow you to configure your application without hardcoding values.

1. In Dockerfile

Define environment variables directly in the Dockerfile.

ENV NODE_ENV=production

2. In docker-compose.yml

Pass variables in the docker-compose.yml:

environment:
  - NODE_ENV=production
  - PORT=3000

3. Using .env File

Create a .env file and Docker will automatically pick it up.

.env

NODE_ENV=production
PORT=3000

docker-compose.yml

environment:
  - NODE_ENV=${NODE_ENV}
  - PORT=${PORT}

πŸ“Š Environment Variable Usage Table

Method How to Define Where to Use
Dockerfile ENV VAR_NAME=value Directly in Dockerfile
docker-compose environment: VAR_NAME=value Docker Compose files
.env File VAR_NAME=value Automatic loading

πŸ”§ Managing Docker Services

Efficiently managing your Docker containers ensures smooth operation and maintenance.

πŸ“ Common Docker Commands

Action Command Description
Start Containers docker-compose up Starts all services defined in docker-compose.yml
Start Containers in Background docker-compose up -d Runs containers in detached mode
Stop Containers docker-compose down Stops and removes containers
View Running Containers docker ps Lists all active Docker containers
Rebuild Containers docker-compose up --build Rebuilds images before starting containers
View Logs docker-compose logs Displays logs from containers
Execute Command in Container docker exec -it <container_name> bash Access the container's shell

πŸ“ˆ Docker Compose Workflow Diagram

graph TD
    A[Write Dockerfile] --> B[Define Services in docker-compose.yml]
    B --> C[Run docker-compose up]
    C --> D[Containers Running]
    D --> E[Manage with Docker Commands]

Figure 2: Docker Compose Workflow


πŸ” Security Best Practices

Ensuring the security of your Docker containers and EC2 instances is paramount.

1. Update Packages Regularly πŸ›‘οΈ

sudo apt-get update && sudo apt-get upgrade -y

2. Use Non-Root Users in Docker Containers πŸ‘€

Modify your Dockerfile to use a non-root user.

# Add user
RUN useradd -ms /bin/bash appuser

# Set user
USER appuser

3. Restrict SSH Access by IP Address πŸ”’

Limit SSH access in your Security Groups to specific IP addresses.

4. Use Strong SSH Keys πŸ”‘

Generate strong SSH key pairs and protect your private keys.

5. Enable Docker Content Trust πŸ›‘οΈ

Ensure the integrity of Docker images by enabling Docker Content Trust.

export DOCKER_CONTENT_TRUST=1

6. Monitor and Log Activity πŸ“œ

Use AWS CloudWatch and Docker logs to monitor and log activities.


βœ… Conclusion

Congratulations! πŸŽ‰ You've successfully:

  1. Launched an EC2 Instance: Set up a virtual server in AWS.
  2. Connected to the Instance: Secured access via SSH.
  3. Installed Docker: Prepared the environment for containerization.
  4. Deployed a Dockerized Application: Ran a sample Node.js app using Docker Compose.
  5. Managed Docker Services: Utilized essential Docker commands for effective management.
  6. Implemented Security Best Practices: Ensured your setup is secure and robust.

Docker on AWS EC2 offers a powerful combination for deploying scalable and reliable applications. Whether you're working on personal projects or enterprise solutions, this setup provides the flexibility and control needed for modern development workflows.


πŸ“š Additional Resources


s