Skip to content

Instantly share code, notes, and snippets.

@chrisbrocklesby
Created October 17, 2022 21:54
Show Gist options
  • Save chrisbrocklesby/894fc0a61ad7b37aaf0a6b90e84d78f8 to your computer and use it in GitHub Desktop.
Save chrisbrocklesby/894fc0a61ad7b37aaf0a6b90e84d78f8 to your computer and use it in GitHub Desktop.
Docker & SSH Deploy GitHub Actions
name: Deploy Image to Container

on:
  push:
    branches:
      - "main"

env:
  CONTAINER_NAME: template-starter-container
  CONTAINER_PORT: 3000:3000
  SSH_USER: root
  SSH_HOST: server.app.chrisbrocklesby.com

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v2

      - name: Setup Remote SSH Connection
        run: |
          mkdir -p ~/.ssh/
          echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/remote.key
          chmod 600 ~/.ssh/remote.key
          cat >> ~/.ssh/config <<END
          Host remote
            HostName ${{ env.SSH_HOST }}
            User ${{ env.SSH_USER }}
            IdentityFile ~/.ssh/remote.key
            StrictHostKeyChecking no
          END

      - name: Build & copy image to remote host
        run: |
          docker build . --tag ${{ env.CONTAINER_NAME }}:latest
          docker save ${{ env.CONTAINER_NAME }}:latest | gzip | DOCKER_HOST=ssh://remote docker load

      - name: Create .env file
        run: echo "${{ secrets.ENV_FILE }}" >> .env

      - name: Deploy container image
        run: |
          export DOCKER_HOST="ssh://remote"
          docker rm -f ${{ env.CONTAINER_NAME }}

          docker run -d \
            --restart unless-stopped \
            --publish ${{ env.CONTAINER_PORT }}\
            --env-file .env \
            --name ${{ env.CONTAINER_NAME }} ${{ env.CONTAINER_NAME }}:latest

          docker image prune -f
          rm -rf .env
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment