top of page

Automating Web Application Deployment on AWS EC2 with GitHub Actions

snatu5

Updated: Mar 21

Introduction


Deploying web applications manually can be time-consuming and error-prone. Automating the deployment process ensures consistency, reduces downtime, and improves efficiency. In this blog, we will explore how to automate web application deployment on AWS EC2 using GitHub Actions.

By the end of this guide, you will have a fully automated CI/CD pipeline that pushes code from a GitHub repository to an AWS EC2 instance, ensuring smooth and reliable deployments.


Seamless Deployment Workflow



Prerequisites


Before we begin, ensure you have the following:

  • An AWS account

  • An EC2 instance with SSH access

  • A GitHub repository containing your web application

  • A domain name (optional)

  • Basic knowledge of AWS, Linux, and GitHub Actions


Step 1: Set Up Your EC2 Instance


  1. Log in to your AWS account and navigate to the EC2 dashboard.

  2. Launch a new EC2 instance with your preferred operating system (Ubuntu recommended).

  3. Create a new security group and allow inbound SSH (port 22) and HTTP/HTTPS traffic (ports 80, 443).

  4. Connect to your EC2 instance using SSH:


ssh -i /path/to/your-key.pem ubuntu@your-ec2-ip

  1. Update the system and install necessary packages:


sudo apt update && sudo apt upgrade -y 
sudo apt install -y git nginx docker

  1. Ensure your application dependencies are installed.


Step 2: Configure SSH Access from GitHub Actions


To allow GitHub Actions to SSH into your EC2 instance and deploy the code:


  1. Generate a new SSH key on your local machine:

ssh-keygen -t rsa -b 4096 -C "github-actions"
  1. Copy the public key to your EC2 instance:

cat ~/.ssh/id_rsa.pub | ssh ubuntu@your-ec2-ip 'mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys'

  1. Store the private key as a GitHub Actions secret:


    1. Go to your repository on GitHub.

    2. Navigate to Settings > Secrets and variables > Actions.

    3. Add a new secret named EC2_SSH_PRIVATE_KEY and paste the private key.

    4. Also, add a secret named EC2_HOST with your EC2 public IP address.

    5. Add a secret named EC2_USER with the value ubuntu (or your EC2 username).


Step 3: Clone the Repository on EC2


  1. SSH into your EC2 instance:

ssh ubuntu@your-ec2-ip
  1. Navigate to the /var/www/html directory and clone your repository:

cd /var/www/html 
git clone https://github.com/your-username/your-repo.git myapp

Step 4: Configure Docker (If Using Docker)


  1. Navigate to the project directory:

cd myapp
  1. Create a docker-compose.yml file:

version: '3' 
services:   
	app:     
		image: myapp:latest     
		build: .     
		ports:       
			- "80:80"
  1. Run the application using Docker:

docker-compose up -d --build

Step 5: Create a GitHub Actions Workflow


  1. In your GitHub repository, create a new directory for workflows:

mkdir -p .github/workflows
  1. Create a new file named deploy.yml inside .github/workflows:

name: Deploy to AWS EC2  

on:   
	push:     
	branches:       
		- main  

jobs:   
	deploy:     
		runs-on: ubuntu-latest     
	steps:       
		- name: Checkout Code         
		uses: actions/checkout@v3        
	
	- name: Set up SSH         
		run: |           
			echo "${{ secrets.EC2_SSH_PRIVATE_KEY }}" > private_key.pem           						
			chmod 600 private_key.pem        

	- name: Deploy to EC2         
		run: |           
			ssh -o StrictHostKeyChecking=no -i private_key.pem ${{ secrets.EC2_USER }}@${{ secrets.EC2_HOST }} << 'EOF'             
				cd /var/www/html/myapp             
				git pull origin main             
				docker-compose down             
				docker-compose up -d --build             
				exit           
			EOF

Step 6: Test the CI/CD Pipeline


  1. Push some changes to the main branch of your repository.

  2. Navigate to Actions in your GitHub repository to see the workflow running.

  3. After the deployment completes, visit your EC2 instance's public IP in a browser.


Step 7: Configure Nginx as a Reverse Proxy (Optional)


  1. Install Nginx on your EC2 instance if not already installed:

sudo apt install nginx -y
  1. Create a new Nginx configuration file:

sudo nano /etc/nginx/sites-available/myapp
  1. Add the following configuration:

server {     
	listen 80;     
	server_name yourdomain.com;      

location / {         
		proxy_pass http://localhost:80;         
		proxy_set_header Host $host;         
		proxy_set_header X-Real-IP $remote_addr;     
	} 
}
  1. Enable the configuration and restart Nginx:

sudo ln -s /etc/nginx/sites-available/myapp /etc/nginx/sites-enabled/ sudo systemctl restart nginx

Step 8: Enable HTTPS with Let’s Encrypt (Optional)


  1. Install Certbot:

sudo apt install certbot python3-certbot-nginx -y
  1. Obtain an SSL certificate:

sudo certbot --nginx -d yourdomain.com -d www.yourdomain.com
  1. Verify SSL renewal:

sudo certbot renew --dry-run

Step 9: Set Up Auto-Restart for Services


  1. Ensure Docker services restart on reboot:

sudo systemctl enable docker
  1. If using a Node.js or Python application, use PM2 or Supervisor to keep it running.


Step 10: Implement Rollback Strategy


  1. Keep older versions of your application in a backup directory.

  2. In case of failure, manually switch to a previous version by checking out an older commit:

git checkout <commit-hash> docker-compose up -d --build

Conclusion


By following this guide, you have successfully automated the deployment of your web application on AWS EC2 using GitHub Actions. This setup ensures that every time you push code to the main branch, your application gets automatically updated on the server.


For further improvements, consider:

  • Adding rollback strategies for failed deployments.

  • Implementing automated tests before deployment.

  • Using AWS CodeDeploy for more complex deployment workflows



Comentarios


1st Floor, Kshitij Business Center, DG Dani Rd, opposite ILS College, Deccan Gymkhana, Pune, Maharashtra 411038

Subscribe to Our Newsletter

Thanks for submitting!

Follow Us On:

  • LinkedIn
  • Youtube

© 2024 by Whileone Techsoft Pvt Ltd.

bottom of page