Sure! I'll provide you with a comprehensive step-by-step guide to host your backend project on AWS EC2 using the latest technologies and versions, incorporating all the tools and requirements you've specified. This guide will cover everything from setting up your AWS environment to deploying your application with Kubernetes, Kong, and Konga, ensuring that your application is securely exposed to the internet with health checks and load balancing in place.
Prerequisites
Before we begin, make sure you have the following:
- AWS Account: Access to AWS Management Console.
- Domain Name: A domain that you own and can configure DNS settings for.
- GitHub Repository: Your backend project's source code hosted on GitHub.
- Docker Hub Account: For storing your Docker images.
- MongoDB Atlas Account: With a cluster set up.
- Local Machine Setup: SSH client, AWS CLI, kubectl, and Helm installed.
Overview
We'll follow these main steps:
- Set Up AWS EC2 Instances
- Install Docker and Docker Compose
- Install Kubernetes on EC2 Instances
- Configure Kubernetes Cluster
- Create Docker Image of Your Application
- Set Up GitHub Actions for CI/CD
- Push Docker Image to Docker Hub
- Deploy Application to Kubernetes
- Install and Configure Kong and Konga
- Expose Application via Kong with Load Balancing
- Set Up Health Checks in Kubernetes
- Secure Application with SSL/TLS
- Configure DNS for Static Route
- Ensure Secure Connection from Mobile App
Step-by-Step Guide
1. Set Up AWS EC2 Instances
a. Launch EC2 Instances
-
Master Node
- AMI: Ubuntu Server 22.04 LTS (HVM), SSD Volume Type
- Instance Type: t3.medium (or larger)
- Network: Default VPC. Assign a public IP.
- Security Group: Allow inbound SSH (port 22), HTTP (port 80), HTTPS (port 443), and Kubernetes ports (6443, 6444, etc.).
-
Worker Nodes
- Repeat the above steps to create at least two worker nodes.
b. Allocate Elastic IPs
- For static public IPs, allocate Elastic IPs for instances that need to be accessible externally (e.g., the master node or the node running Kong).
c. Update Security Groups
- Ensure all necessary ports are open between master and worker nodes (ports 6443, 10250, etc.).
2. Install Docker and Docker Compose
SSH into Each Instance and Run:
# Update packages
sudo apt update && sudo apt upgrade -y
# Install prerequisites
sudo apt install -y apt-transport-https ca-certificates curl gnupg lsb-release
# Add Docker’s official GPG key and set up the stable repository
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] \
https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | \
sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
# Install Docker Engine
sudo apt update
sudo apt install -y docker-ce docker-ce-cli containerd.io
# Add your user to the docker group
sudo usermod -aG docker $USER
# Log out and log back in to apply the group change
# Install Docker Compose (Latest Version)
DOCKER_COMPOSE_VERSION=$(curl -s https://api.github.com/repos/docker/compose/releases/latest | grep '"tag_name":' | sed -E 's/.*"v([^"]+)".*/\1/')
sudo curl -L "https://github.com/docker/compose/releases/download/v$DOCKER_COMPOSE_VERSION/docker-compose-$(uname -s)-$(uname -m)" \
-o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
# Verify installation
docker --version
docker-compose --version
3. Install Kubernetes on EC2 Instances
On All Nodes:
# Disable swap
sudo swapoff -a
sudo sed -i '/ swap / s/^/#/' /etc/fstab
# Install Kubernetes packages
sudo apt update
sudo apt install -y apt-transport-https curl
# Add Kubernetes GPG key and repository
sudo curl -fsSLo /usr/share/keyrings/kubernetes-archive-keyring.gpg \
https://packages.cloud.google.com/apt/doc/apt-key.gpg
echo "deb [signed-by=/usr/share/keyrings/kubernetes-archive-keyring.gpg] \
https://apt.kubernetes.io/ kubernetes-xenial main" | \
sudo tee /etc/apt/sources.list.d/kubernetes.list
sudo apt update
# Install kubeadm, kubelet, and kubectl
sudo apt install -y kubelet kubeadm kubectl
sudo apt-mark hold kubelet kubeadm kubectl
Configure sysctl:
cat <<EOF | sudo tee /etc/modules-load.d/k8s.conf
br_netfilter
overlay
EOF
sudo modprobe br_netfilter
sudo modprobe overlay
cat <<EOF | sudo tee /etc/sysctl.d/k8s.conf
net.bridge.bridge-nf-call-iptables=1
net.ipv4.ip_forward=1
net.bridge.bridge-nf-call-ip6tables=1
EOF
sudo sysctl --system
4. Configure Kubernetes Cluster
On Master Node:
# Initialize the Kubernetes cluster
sudo kubeadm init --pod-network-cidr=10.244.0.0/16
# Configure kubectl for the ubuntu user
mkdir -p $HOME/.kube
sudo cp -i /etc/kubernetes/admin.conf $HOME/.kube/config
sudo chown $(id -u):$(id -g) $HOME/.kube/config
Install Pod Network Add-on (Flannel):
kubectl apply -f https://raw.githubusercontent.com/coreos/flannel/master/Documentation/kube-flannel.yml
On Worker Nodes:
- Join the cluster using the command provided at the end of
kubeadm init output on the master node. It will look like:
sudo kubeadm join <master-node-ip>:6443 --token <token> --discovery-token-ca-cert-hash sha256:<hash>
Verify Cluster Nodes:
kubectl get nodes
5. Create Docker Image of Your Application
In Your Local Development Environment:
a. Create a Dockerfile
# Use the latest Node.js LTS version
FROM node:20-alpine
# Set the working directory
WORKDIR /app
# Copy package.json and pnpm-lock.yaml
COPY package.json pnpm-lock.yaml ./
# Install pnpm
RUN npm install -g pnpm
# Install dependencies
RUN pnpm install
# Copy the rest of your application code
COPY . .
# Build the application if needed
RUN pnpm build
# Expose the application port
EXPOSE 3000
# Start the application
CMD ["pnpm", "start"]
b. Build the Docker Image
docker build -t your-dockerhub-username/your-app-name:latest .
6. Set Up GitHub Actions for CI/CD
Create a GitHub Actions Workflow File:
- In your GitHub repository, create
.github/workflows/docker-image.yml
name: Build and Push Docker Image
on:
push:
branches: [ main ]
pull_request:
branches: [ main ]
jobs:
build_and_push:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3
- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: '20'
- name: Install pnpm
run: npm install -g pnpm
- name: Install dependencies
run: pnpm install
- name: Build application
run: pnpm build
- name: Log in to Docker Hub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
- name: Build and push Docker image
uses: docker/build-push-action@v4
with:
context: .
push: true
tags: your-dockerhub-username/your-app-name:latest
Add GitHub Secrets:
- In your GitHub repository, go to Settings > Secrets and variables > Actions
- Add the following secrets:
DOCKERHUB_USERNAME
DOCKERHUB_TOKEN (You can generate a token in Docker Hub for increased security)
7. Push Docker Image to Docker Hub
From Local Machine:
# Log in to Docker Hub
docker login
# Push the image
docker push your-dockerhub-username/your-app-name:latest
8. Deploy Application to Kubernetes
Create Kubernetes Deployment and Service Files
deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: backend
spec:
replicas: 3
selector:
matchLabels:
app: backend
template:
metadata:
labels:
app: backend
spec:
containers:
- name: backend
image: your-dockerhub-username/your-app-name:latest
ports:
- containerPort: 3000
livenessProbe:
httpGet:
path: /_health
port: 3000
initialDelaySeconds: 10
periodSeconds: 10
service.yaml
apiVersion: v1
kind: Service
metadata:
name: backend-service
spec:
selector:
app: backend
ports:
- protocol: TCP
port: 80
targetPort: 3000
type: ClusterIP
Apply the Configuration
kubectl apply -f deployment.yaml
kubectl apply -f service.yaml
9. Install and Configure Kong and Konga
a. Install Kong Ingress Controller Using Helm
# Add the Kong charts repository
helm repo add kong https://charts.konghq.com
helm repo update
# Install Kong with Ingress Controller
helm install kong kong/kong --set ingressController.installCRDs=false \
--set ingressController.enabled=true --set proxy.type=LoadBalancer \
--set admin.enabled=false --set env.database=off \
--set proxy.annotations."service\.beta\.kubernetes\.io/aws-load-balancer-type"="nlb" \
--set replicaCount=2
b. Verify Kong Installation
kubectl get services
- Note the External IP of the
kong-kong-proxy service.
c. Install Konga
Create a Deployment and Service for Konga
konga-deployment.yaml
apiVersion: apps/v1
kind: Deployment
metadata:
name: konga
spec:
replicas: 1
selector:
matchLabels:
app: konga
template:
metadata:
labels:
app: konga
spec:
containers:
- name: konga
image: pantsel/konga
ports:
- containerPort: 1337
konga-service.yaml
apiVersion: v1
kind: Service
metadata:
name: konga
spec:
selector:
app: konga
type: LoadBalancer
ports:
- protocol: TCP
port: 80
targetPort: 1337
Apply Konga Configuration
kubectl apply -f konga-deployment.yaml
kubectl apply -f konga-service.yaml
d. Access Konga
- Use the external IP of the
konga service to access the Konga UI.
- Set up Konga to connect to your Kong instance.
10. Expose Application via Kong with Load Balancing
a. Create an Ingress Resource
ingress.yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: backend-ingress
annotations:
kubernetes.io/ingress.class: "kong"
spec:
rules:
- host: api.your-domain.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: backend-service
port:
number: 80
Apply the Ingress
kubectl apply -f ingress.yaml
b. Configure Kong via Konga
- In Konga, you can manage Kong routes, services, and upstreams.
- Verify that Kong routes traffic to your backend service and balances the load among replicas.
11. Set Up Health Checks in Kubernetes
- Already configured in your
deployment.yaml with livenessProbe.
- Kubernetes will check the
/_health endpoint every 10 seconds and restart pods if necessary.
12. Secure Application with SSL/TLS
a. Install Cert-Manager for Automatic SSL Certificates
kubectl apply --validate=false -f \
https://github.com/jetstack/cert-manager/releases/latest/download/cert-manager.yaml
b. Create a ClusterIssuer
cluster-issuer.yaml
apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
name: letsencrypt-production
spec:
acme:
email: your-email@example.com
server: https://acme-v02.api.letsencrypt.org/directory
privateKeySecretRef:
name: letsencrypt-production
solvers:
- http01:
ingress:
class: kong
Apply the ClusterIssuer
kubectl apply -f cluster-issuer.yaml
c. Modify Ingress Resource to Use TLS
Update ingress.yaml:
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
name: backend-ingress
annotations:
kubernetes.io/ingress.class: "kong"
cert-manager.io/cluster-issuer: "letsencrypt-production"
spec:
tls:
- hosts:
- api.your-domain.com
secretName: api-tls
rules:
- host: api.your-domain.com
http:
paths:
- path: /
pathType: Prefix
backend:
service:
name: backend-service
port:
number: 80
Apply the Updated Ingress
kubectl apply -f ingress.yaml
d. Verify SSL Certificate
- Use
kubectl describe certificate api-tls to check the status.
- Once issued, your application will be accessible over HTTPS.
13. Configure DNS for Static Route
a. Point Your Domain to Kong's External IP
- In your domain registrar's DNS settings, create an
A record:
- Host:
api.your-domain.com
- Value: External IP of the
kong-kong-proxy service.
b. Verify DNS Propagation
- Use
nslookup or dig to verify that api.your-domain.com resolves to the correct IP.
14. Ensure Secure Connection from Mobile App
- Your mobile app should communicate with
https://api.your-domain.com.
- Ensure that all API calls use HTTPS to prevent man-in-the-middle attacks.
- Implement JWT authentication or other security measures as required by your backend.
Note: Make sure to test your API endpoints thoroughly to ensure they are accessible and secure.
Additional Considerations
Testing and Verification
-
Access Your API:
- Open a browser and navigate to
https://api.your-domain.com.
- Test your API endpoints to ensure they are working as expected.
-
Verify SSL Certificate:
- Check that the SSL certificate is valid and issued by Let's Encrypt.
-
Simulate Health Check Failures:
- Induce a failure in one of your pods to see if Kubernetes restarts it.
-
Load Testing:
- Use tools like Apache JMeter or Locust to perform load testing and observe how Kong balances the load.
Conclusion
By following this guide, you've successfully:
- Deployed your TypeScript backend application on AWS EC2 instances.
- Containerized your application with Docker and managed deployments with Kubernetes.
- Implemented CI/CD pipelines with GitHub Actions.
- Configured load balancing with Kong and managed it with Konga.
- Set up health checks to monitor and restart unhealthy containers.
- Secured your application with SSL/TLS certificates from Let's Encrypt.
- Exposed your application on a static route for secure communication with your mobile application.
Remember to keep all your software versions updated and regularly maintain your infrastructure. Stay informed about best practices in security and DevOps to ensure your application remains robust and secure.
If you have any questions or need further assistance, feel free to ask!