Update GitHub Actions workflow for automated deployment #2
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: Deploy Dockerized Service | |
on: | |
push: | |
branches: [ main ] | |
pull_request: | |
branches: [ main ] | |
env: | |
REGISTRY: ghcr.io | |
IMAGE_NAME: ${{ github.repository }} | |
jobs: | |
build-and-deploy: | |
runs-on: ubuntu-latest | |
permissions: | |
contents: read | |
packages: write | |
steps: | |
- name: Checkout repository | |
uses: actions/checkout@v2 | |
- name: Log in to the Container registry | |
uses: docker/login-action@v2 | |
with: | |
registry: ${{ env.REGISTRY }} | |
username: ${{ github.actor }} | |
password: ${{ secrets.GITHUB_TOKEN }} | |
- name: Extract metadata for Docker | |
id: meta | |
uses: docker/metadata-action@v4 | |
with: | |
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }} | |
tags: | | |
type=sha,format=long | |
type=ref,event=branch | |
latest | |
- name: Build and push Docker image | |
uses: docker/build-push-action@v4 | |
with: | |
context: ./app | |
push: true | |
tags: ${{ steps.meta.outputs.tags }} | |
labels: ${{ steps.meta.outputs.labels }} | |
- name: Deploy to Target Node | |
uses: appleboy/ssh-action@master | |
with: | |
host: ${{ secrets.TARGET_HOST }} | |
username: ubuntu | |
key: ${{ secrets.SSH_PRIVATE_KEY }} | |
script: | | |
# Login to GitHub Container Registry | |
echo ${{ secrets.GITHUB_TOKEN }} | docker login ghcr.io -u ${{ github.actor }} --password-stdin | |
# Pull the latest image | |
docker pull ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest | |
# Stop and remove existing container if it exists | |
docker stop dockerized-service || true | |
docker rm dockerized-service || true | |
# Run the new container | |
docker run -d \ | |
--name dockerized-service \ | |
--restart always \ | |
-p 3000:3000 \ | |
--env-file /opt/dockerized-service/.env \ | |
${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}:latest | |
# Clean up old images | |
docker image prune -f |