Skip to content

Instantly share code, notes, and snippets.

@jensmeindertsma
Last active May 1, 2025 07:31
Show Gist options
  • Save jensmeindertsma/7d42b85a5828479537e11196d121e33b to your computer and use it in GitHub Desktop.
Save jensmeindertsma/7d42b85a5828479537e11196d121e33b to your computer and use it in GitHub Desktop.
Make sure `github` user has sudo permissions: `github ALL=(ALL) NOPASSWD: /bin/bash /home/github/redeploy.sh*`.
name: deploy
on:
push:
branches: main
jobs:
push:
runs-on: ubuntu-latest
steps:
- name: Check out repository
uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Build Docker image
uses: docker/build-push-action@v6
env:
DOCKER_BUILD_SUMMARY: false
with:
load: true
tags: myapp:latest
- name: Prepare SSH key
run: |
mkdir -p ~/.ssh
echo "${{ secrets.SSH_KEY }}" | tr -d '\r' > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
- name: Add SSH host to known_hosts
run: |
ssh-keyscan -H "${{ secrets.SSH_HOST }}" >> ~/.ssh/known_hosts
- name: Save image
run: docker save myapp:latest | gzip | ssh ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }} docker load
- name: Run redeploy script
run: ssh ${{ secrets.SSH_USER }}@${{ secrets.SSH_HOST }} sudo /bin/bash /home/github/redeploy.sh myapp
#!/bin/bash
# Ensure script receives an argument for container name
if [ -z "$1" ]; then
echo "Usage: $0 <container_name>"
exit 1
fi
CONTAINER_NAME=$1
APP_DIR="/var/lib/applications/$CONTAINER_NAME"
DATA_DIR="$APP_DIR/data"
PORT_FILE="$APP_DIR/port"
ENV_FILE="$APP_DIR/environment"
# Ensure the necessary files and directories exist
if [ ! -d "$APP_DIR" ]; then
echo "Error: Directory $APP_DIR does not exist."
exit 1
fi
if [ ! -f "$PORT_FILE" ]; then
echo "Error: Port file $PORT_FILE does not exist."
exit 1
fi
if [ ! -f "$ENV_FILE" ]; then
echo "Error: Environment file $ENV_FILE does not exist."
exit 1
fi
# Stop the existing container if it is running
echo "Stopping existing container: $CONTAINER_NAME"
docker stop "$CONTAINER_NAME" && docker rm "$CONTAINER_NAME"
# Read the port from the port file
PORT=$(cat "$PORT_FILE")
if [ -z "$PORT" ]; then
echo "Error: Port is not specified in $PORT_FILE."
exit 1
fi
# Read environment variables from the environment file
ENV_VARS=""
while IFS= read -r line; do
ENV_VARS="$ENV_VARS -e $line"
done < "$ENV_FILE"
ENV_VARS="$ENV_VARS -e PORT=$PORT"
# Run the new container with the same name, exposing the port, and mounting the data volume
echo "Starting new container: $CONTAINER_NAME"
docker run --detach \
--name "$CONTAINER_NAME" \
--restart always \
--publish "$PORT:$PORT" \
--volume "$DATA_DIR:/data" \
$ENV_VARS \
"$CONTAINER_NAME:latest"
echo "Deployment complete: $CONTAINER_NAME is now running on port $PORT."
docker image prune --force
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment