Update deploy-ec2.yml #23
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
name: Update and Deploy Node.js App as Container | ||
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: Setup Node.js | ||
uses: actions/setup-node@v3 | ||
with: | ||
node-version: '18' | ||
- name: Install npm dependencies | ||
run: npm ci | ||
- name: Build Docker image | ||
run: docker build -t takalezi6/node-app:${{ github.sha }} . | ||
- name: Log in to Docker Hub | ||
uses: docker/login-action@v2 | ||
with: | ||
username: ${{ secrets.DOCKER_USERNAME }} | ||
password: ${{ secrets.DOCKER_PASSWORD }} | ||
- name: Push Docker image | ||
run: docker push takalezi6/node-app:${{ github.sha }} | ||
deploy_to_ec2: | ||
runs-on: ubuntu-latest | ||
needs: build_and_push | ||
steps: | ||
- name: Deploy image to EC2 from DockerHub | ||
uses: appleboy/[email protected] | ||
with: | ||
host: ${{ secrets.HOST_DNS }} | ||
username: ${{ secrets.USERNAME }} | ||
key: ${{ secrets.EC2_SSH_KEY }} | ||
port: 22 | ||
script: | | ||
cd ~/my-node-app | ||
sudo docker pull takalezi6/node-app:${{ github.sha }} | ||
#Stop and remove existing container named node-app if it exists | ||
if [ "$(sudo docker ps -q -f name=node-app)" ]; then | ||
sudo docker stop node-app | ||
sudo docker rm node-app | ||
fi | ||
# Run the newly pulled Docker image with a specific tag (github.sha) | ||
sudo docker run -d -p 3000:3000 --name node-app takalezi6/node-app:${{ github.sha }} |