Skip to content

updated workflow with tag #28

updated workflow with tag

updated workflow with tag #28

Workflow file for this run

name: Build, Push, and Deploy Docker Image to EC2
on:
push:
#branches:
#- main
#- dev # Trigger the workflow on push to the dev branch
tags:
- 0.*
jobs:
build_and_deploy:
runs-on: ubuntu-latest
steps:
# Step 1: Checkout the code
- name: Checkout code
uses: actions/checkout@v3
# Step 2: Log in to DockerHub
- name: Log in to DockerHub
uses: docker/login-action@v2
with:
username: ${{ secrets.DOCKERHUB_USER_NAME }}
password: ${{ secrets.DOCKERHUB_TOEKN }}
- name: Get Git Tag
id: get_tag
run: |
echo "TAG=${GITHUB_REF#refs/tags/}" >> $GITHUB_ENV
# Step 3: Build the Docker image
- name: Build Docker image
run: |
docker build -t ${{ secrets.DOCKERHUB_USER_NAME }}/nextblog:${{ env.TAG }} .
# Step 4: Push Docker image to DockerHub
- name: Push Docker image
run: |
docker push ${{ secrets.DOCKERHUB_USER_NAME }}/nextblog:${{ env.TAG }}
# Step 5: SSH to EC2 and deploy the Docker container
- name: Deploy to EC2
uses: appleboy/ssh-action@v1.0.3
with:
host: ${{ secrets.EC2_HOST }}
username: ${{ secrets.EC2_USER_NAME }}
key: ${{ secrets.EC2_SSH }}
port: 22
script: |
# Pull the latest image
sudo docker pull ${{ secrets.DOCKERHUB_USER_NAME }}/nextblog:${{ env.TAG }}
# Check if the container is running and stop/remove it if it exists
if [ "$(sudo docker ps -a -q -f name=nextblog)" ]; then
echo "Stopping and removing existing container..."
sudo docker stop nextblog
sudo docker rm nextblog
fi
# creating env file from secret
cd /home/${{secrets.EC2_USER_NAME}}
echo "${{ secrets.APP_ENVS }}" > .env
# Run the container
echo "Starting a new container..."
sudo docker run -d --name nextblog --env-file .env -p 9000:5000 ${{ secrets.DOCKERHUB_USER_NAME }}/nextblog:${{ env.TAG }}