Deploy with Git + SSH (No CI/CD)

Mar. 12, 2022

This post is about how to deploy a git repository to a server using any fancy CI/CD tool.

I will be using just Git & SSH to deploy the repository to the server.

Step 1: Create a new SSH key

ssh-keygen -t rsa -b 4096 -C "your_email@example.com"

Step 2: Add the SSH key to the server

ssh-copy-id -i ~/.ssh/id_rsa.pub user@server

Step 3: Setup the server

#!/bin/bash

set -e

APP_NAME="myapp"
DEPLOY_DIR="/opt/$APP_NAME"
TMP_DIR="/tmp/$APP_NAME-tmp"
GIT_DIR="/home/user/repos/$APP_NAME.git"
BRANCH="main"

echo "[+] Deploying branch '$BRANCH' with docker-compose..."

# Clean old temp checkout
rm -rf "$TMP_DIR"
mkdir -p "$TMP_DIR"

# Checkout code to temp dir
GIT_WORK_TREE="$TMP_DIR" git --git-dir="$GIT_DIR" checkout -f $BRANCH

# rsync to deploy dir (safer than checking out directly)
mkdir -p "$DEPLOY_DIR"
rsync -a --delete "$TMP_DIR/" "$DEPLOY_DIR/"

# Go to the deployed dir
cd "$DEPLOY_DIR"

# Bring up the stack
docker-compose pull     # pull updated images if used
docker-compose build    # build if Dockerfiles changed
docker-compose up -d    # restart in detached mode

echo "[+] Docker Compose deployment done."

Step 4: Create a new repository

git init --bare

Step 5: Add the repository to the server

git remote add deploy ssh://user@server/opt/myapp.git

Step 6: Push the repository to the server

git push deploy main

Step 7: Test the deployment

ssh user@server
cd /opt/myapp
docker-compose up -d