prod-api-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: prod-api-deployment | |
on: | |
workflow_dispatch: | |
env: | |
CONTAINER_IMAGE: platform-api | |
CONTAINER_NAME: api | |
CONTAINER_PORT: 8000 | |
jobs: | |
build: | |
runs-on: ubuntu-latest | |
steps: | |
- name: Checkout | |
uses: actions/checkout@v3 | |
- name: Login to Docker Hub | |
uses: docker/login-action@v2 | |
with: | |
username: ${{ secrets.DOCKERHUB_USERNAME }} | |
password: ${{ secrets.DOCKERHUB_TOKEN }} | |
- name: Set up Docker Buildx | |
uses: docker/setup-buildx-action@v2 | |
- id: get_version | |
name: get API version from package.json | |
run: | | |
version=`cat ./apps/api/package.json | jq -r '.version'` | |
# end of optional handling for multi line json | |
echo "version=$version" >> $GITHUB_OUTPUT | |
- name: Build and push | |
id: build_and_push | |
uses: docker/build-push-action@v4 | |
with: | |
context: . | |
file: ./apps/api/Dockerfile | |
push: true | |
tags: ${{ secrets.DOCKERHUB_USERNAME }}/${{env.CONTAINER_IMAGE}}:latest, ${{ secrets.DOCKERHUB_USERNAME }}/${{env.CONTAINER_IMAGE}}:v${{steps.get_version.outputs.version}} | |
outputs: | |
container_tag: v${{steps.get_version.outputs.version}} | |
deploy: | |
runs-on: ubuntu-latest | |
needs: build | |
env: | |
CONTAINER_TAG: ${{needs.build.outputs.container_tag}} | |
steps: | |
- name: deploy via ssh | |
uses: appleboy/[email protected] | |
with: | |
host: ${{ secrets.PROD_SSH_HOST }} | |
username: ${{ secrets.PROD_SSH_USERNAME }} | |
key: ${{ secrets.PROD_SSH_KEY }} | |
envs: CONTAINER_NAME,CONTAINER_PORT,CONTAINER_TAG,CONTAINER_IMAGE | |
passphrase: ${{ secrets.PROD_SSH_PASSPHRASE }} | |
script: | | |
# pull image | |
docker pull ${{ secrets.DOCKERHUB_USERNAME }}/$(echo $CONTAINER_IMAGE):$(echo $CONTAINER_TAG) | |
# stop existing one | |
docker stop $(echo $CONTAINER_NAME) || echo 'no container to stop' | |
# Remove old container | |
docker rm $(echo $CONTAINER_NAME) || echo 'no container to remove' | |
# Run a new container from a new image | |
docker run -d --restart always --name $(echo $CONTAINER_NAME) -p $(echo $CONTAINER_PORT):8000 --env-file ~/.env.$(echo $CONTAINER_NAME) ${{ secrets.DOCKERHUB_USERNAME }}/$(echo $CONTAINER_IMAGE):$(echo $CONTAINER_TAG) |