Skip to content

Merge pull request #144 from The-Monitor-Dev/develop #153

Merge pull request #144 from The-Monitor-Dev/develop

Merge pull request #144 from The-Monitor-Dev/develop #153

Workflow file for this run

name: Deploy Spring Boot to EC2 with Docker Compose
on:
push:
branches:
- main
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Set up JDK 21
uses: actions/setup-java@v1
with:
java-version: '21'
- name: Set up Docker credentials
run: |
echo "DOCKER_USERNAME=${{ secrets.DOCKER_USERNAME }}" >> $GITHUB_ENV
echo "DOCKER_PASSWORD=${{ secrets.DOCKER_PASSWORD }}" >> $GITHUB_ENV
- name: Build JAR file
run: ./gradlew bootJar
- name: Build and push Docker image with JIB
run: ./gradlew jib -Pprod --image=${{ secrets.DOCKER_USERNAME }}/the_monitor:latest
deploy:
runs-on: ubuntu-latest
needs: build
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Copy nginx.conf to EC2
uses: appleboy/[email protected]
with:
host: ${{ secrets.EC2_HOST }}
username: ec2-user
key: ${{ secrets.EC2_PRIVATE_KEY }}
source: "./nginx.conf"
target: "/home/ec2-user/"
- name: Create .env file on EC2
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.EC2_HOST }}
username: ec2-user
key: ${{ secrets.EC2_PRIVATE_KEY }}
script: |
echo "${{ secrets.ENV }}" > /home/ec2-user/.env
- name: Copy docker-compose.yml to EC2
uses: appleboy/[email protected]
with:
host: ${{ secrets.EC2_HOST }}
username: ec2-user
key: ${{ secrets.EC2_PRIVATE_KEY }}
source: "./docker-compose.yml"
target: "/home/ec2-user/"
- name: Connect to EC2 and deploy
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.EC2_HOST }}
username: ec2-user
key: ${{ secrets.EC2_PRIVATE_KEY }}
script: |
# Install jq if not already installed
if ! command -v jq &> /dev/null
then
sudo yum install -y jq
fi
# Set up Docker Compose on EC2 if not installed
if ! command -v docker-compose &> /dev/null
then
sudo curl -L "https://github.com/docker/compose/releases/download/$(curl -s https://api.github.com/repos/docker/compose/releases/latest | jq -r '.tag_name')/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
fi
cd /home/ec2-user
# Remove all running containers and networks (forcefully)
docker-compose -f docker-compose.yml down --remove-orphans || true
docker rm -f $(docker ps -aq) || true
docker network prune -f || true
# Pull the latest Docker images
docker-compose -f docker-compose.yml pull
# Start containers with Docker Compose
docker-compose -f docker-compose.yml up -d