Skip to content

container for the fast-api #8

container for the fast-api

container for the fast-api #8

Workflow file for this run

name: Build and Push Docker Image
on:
push:
branches:
- main
env:
DOCKER_USERNAME: ${{ secrets.DOCKER_USERNAME }}
DOCKER_PASSWORD: ${{ secrets.DOCKER_PASSWORD }}
EC2_HOST: ${{ secrets.EC2_HOST }}
EC2_KEY: ${{ secrets.EC2_KEY }}
jobs:
deploy-backend:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2
- name: Debug environment variables
run: |
echo "DOCKER_USERNAME=${DOCKER_USERNAME}"
echo "DOCKER_PASSWORD=${DOCKER_PASSWORD}"
echo "EC2_HOST=${EC2_HOST}"
echo "EC2_KEY=${EC2_KEY}"
- name: Decode and save EC2 private key
run: |
echo "${{ secrets.EC2_KEY }}" | base64 --decode > ec2-private-key.pem
chmod 600 ec2-private-key.pem
- name: SSH into EC2 instance and deploy
run: |
ssh -o StrictHostKeyChecking=no -i ./ec2-private-key.pem ec2-user@${EC2_HOST} << 'EOF'
cd /home/ec2-user/fastapi-todos
# Pull latest code
git pull origin main
# Build Docker image
sudo docker build -t fastapi-to-dos .
# Stop and remove previous Docker container (if running)
CONTAINER_ID=$(sudo docker ps -aqf "name=fastapi-to-dos")
if [ -n "$CONTAINER_ID" ]; then
sudo docker stop $CONTAINER_ID
sudo docker rm $CONTAINER_ID
fi
# Free up port 8000 if it's already in use
PORT_IN_USE=$(sudo lsof -t -i:8000)
if [ -n "$PORT_IN_USE" ]; then
echo "Port 8000 is in use by PID $PORT_IN_USE, killing it."
sudo kill -9 $PORT_IN_USE
else
echo "Port 8000 is not in use."
fi
# Verify port 8000 is freed
sleep 2
PORT_IN_USE_AFTER=$(sudo lsof -t -i:8000)
if [ -n "$PORT_IN_USE_AFTER" ]; then
echo "Port 8000 is still in use by PID $PORT_IN_USE_AFTER, exiting."
exit 1
else
echo "Port 8000 is free."
fi
# Run new Docker container
sudo docker run -p 8000:8000 fastapi-to-dos
EOF