Handy GitHub Action for Docker Compose Deploy to Server via SSH/Docker Hub
Chris Brocklesby
These are handy GitHub Action's for Docker Compose Deploy to Server via SSH Docker Context or SCP/SSH using the Docker Hub registry.
Docker Context SSH Method
name: "Deploy docker-compose.yml"
on: [push]
jobs:
deploy:
runs-on: ubuntu-latest
env:
DOCKER_USER: usernamehere
DOCKER_TOKEN: ${{ secrets.DOCKER_TOKEN }}
SSH_USER: docker
SSH_HOST: domainnamehere.com
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
ENV_FILE: ${{ secrets.ENV_FILE }}
steps:
- name: Configure SSH for Docker Host
run: |
mkdir -p ~/.ssh/
echo "$SSH_PRIVATE_KEY" > ~/.ssh/remote.key
chmod 600 ~/.ssh/remote.key
cat >>~/.ssh/config <<END
Host remote
HostName $SSH_HOST
User $SSH_USER
IdentityFile ~/.ssh/remote.key
StrictHostKeyChecking no
END
- name: Login to Docker Hub
run: echo "$DOCKER_TOKEN" | docker login --username $DOCKER_USER --password-stdin
- uses: actions/checkout@v3
- name: Setup Environmentals ENV
run: echo $ENV_FILE > .env
- name: Docker Context
run: |
docker context create docker-host --docker "host=ssh://remote"
docker context use docker-host
- name: Docker Compose PULL
run: docker compose pull --ignore-pull-failures
- name: Docker Compose UP
run: docker compose up -d
- name: Docker Compose PS
run: docker compose ps
- name: Clean up
run: |
docker image prune -f
docker container prune -f
rm -rf .env
SCP/SSH Method
name: Deploy to Development
on:
push:
branches:
- main
paths:
- "docker-compose.yml"
jobs:
deploy:
runs-on: ubuntu-22.04
env:
DOCKER_USER: dockeruser
DOCKER_TOKEN: ${{ secrets.DOCKER_TOKEN }}
DOCKER_COMPOSE_FILE: docker-compose.yml
SSH_USER: sshuser
SSH_HOST: ssh.host.ext
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
ENV_FILE: ${{ secrets.ENV_FILE }}
steps:
- uses: actions/checkout@v3
- name: Configure SSH for Docker Host
run: |
mkdir -p ~/.ssh/
echo "$SSH_PRIVATE_KEY" > ~/.ssh/remote.key
chmod 600 ~/.ssh/remote.key
cat >>~/.ssh/config <<END
Host remote
HostName $SSH_HOST
User $SSH_USER
IdentityFile ~/.ssh/remote.key
StrictHostKeyChecking no
END
- name: Copy Docker Compose File
run: scp $DOCKER_COMPOSE_FILE remote:~/$DOCKER_COMPOSE_FILE
- name: Create Environmentals File
run: ssh remote "echo $ENV_FILE > ~/.env"
- name: Docker Login
run: ssh remote "echo '$DOCKER_TOKEN' | docker login --username $DOCKER_USER --password-stdin"
- name: Docker Compose Pull
run: ssh remote "docker compose --file $DOCKER_COMPOSE_FILE pull"
- name: Docker Compose Up
run: ssh remote "docker compose --file $DOCKER_COMPOSE_FILE up -d"
- name: Docker Prune / Clean Up
run: ssh remote "docker image prune -f && docker container prune -f && rm /*env"