Update deploy-ec2.yml #9
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: | |
update_repository: | |
runs-on: ubuntu-latest | |
services: | |
docker: | |
image: docker:latest | |
options: --privileged # Enable privileged mode for the Docker service | |
steps: | |
# Checkout the repository | |
- name: Checkout Code | |
uses: actions/checkout@v3 | |
# Setup Node.js environment and install dependencies | |
- name: Setup Node.js | |
uses: actions/setup-node@v3 | |
with: | |
node-version: '16' | |
# Install npm dependencies | |
- name: Install npm dependencies | |
run: npm ci | |
# Build the Docker image | |
- name: Build Docker image | |
run: docker build -t node-app:latest -f my-node-app/Dockerfile . | |
#Verify docker image exists | |
- name: Verify Docker image | |
run: docker images | |
deploy_to_ec2: | |
runs-on: ubuntu-latest | |
needs: update_repository | |
steps: | |
# Deploy to EC2 using SSH | |
- name: Deploy to EC2 | |
uses: easingthemes/ssh-deploy@main | |
env: | |
SSH_PRIVATE_KEY: ${{ secrets.EC2_SSH_KEY }} | |
REMOTE_HOST: ${{ secrets.HOST_DNS }} | |
REMOTE_USER: ${{ secrets.USERNAME }} | |
TARGET: ~/my-node-app # Deploying to the specified app directory | |
SOURCE: ./my-node-app # Path of the files you want to deploy | |
# Run the new Docker container | |
- name: Run Docker container | |
uses: appleboy/[email protected] | |
with: | |
host: ${{ secrets.HOST_DNS }} | |
username: ${{ secrets.USERNAME }} | |
key: ${{ secrets.EC2_SSH_KEY }} | |
port: 22 | |
script: | | |
# Stop and remove all running containers if they exist | |
if [ "$(sudo docker ps -q)" ]; then | |
sudo docker stop $(docker ps -q) | |
fi | |
if [ "$(sudo docker ps -aq)" ]; then | |
sudo docker rm $(docker ps -aq) | |
fi | |
# Run the new Docker image | |
docker run -d -p 3000:3000 --name node-app my-new-image:latest |