π³ 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
- What is AWS EC2?
- Prerequisites
- Step 1: Launch an EC2 Instance
- Step 2: Connect to Your EC2 Instance
- Step 3: Install Docker on EC2
- Step 4: Deploy Your Dockerized Project
- Example Project Deployment
- Managing Docker Services
- Security Best Practices
- Conclusion
- 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
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.
3. Connect via SSH π
π 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 π¦
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 π
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 π³
6. Verify Docker Installation β
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.
- Create Docker Group π Ά
- Add Your User to Docker Group π§βπ€βπ§
- Apply New Group Membership π
- Test Docker Without Sudo π«π
π 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
b. Install Dependencies
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
3. Deploying the Application
a. Clone the Project (If Applicable)
If your project is hosted on GitHub or another repository:
b. Run Docker Compose
--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:
π¦ 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.
2. In docker-compose.yml
Pass variables in the docker-compose.yml
:
3. Using .env
File
Create a .env
file and Docker will automatically pick it up.
.env
docker-compose.yml
π 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 π‘οΈ
2. Use Non-Root Users in Docker Containers π€
Modify your Dockerfile
to use a non-root user.
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.
6. Monitor and Log Activity π
Use AWS CloudWatch and Docker logs to monitor and log activities.
β Conclusion
Congratulations! π You've successfully:
- Launched an EC2 Instance: Set up a virtual server in AWS.
- Connected to the Instance: Secured access via SSH.
- Installed Docker: Prepared the environment for containerization.
- Deployed a Dockerized Application: Ran a sample Node.js app using Docker Compose.
- Managed Docker Services: Utilized essential Docker commands for effective management.
- 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
- Docker Official Documentation
- AWS EC2 Documentation
- Docker Compose Documentation
- AWS Getting Started Guide
- Express.js Official Website
- Mermaid Diagrams Documentation
- Security Best Practices for Docker
- AWS Security Best Practices
s