albertyw/albertyw.com

View on GitHub
bin/deploy.sh

Summary

Maintainability
Test Coverage
#!/bin/bash

# This script will build and deploy a new docker image

set -exuo pipefail
IFS=$'\n\t'

DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null && pwd )"
cd "$DIR"/.. || exit

CONTAINER="albertyw"
PORT="5000"
NETWORK="$CONTAINER"_net
DEPLOY_BRANCH="${1:-}"
BRANCH="$(git rev-parse --abbrev-ref HEAD)"
set +x  # Do not print contents of .env
source .env
set -x

if [ -n "$DEPLOY_BRANCH" ]; then
    # Update repository
    git checkout "$DEPLOY_BRANCH"
    git fetch -tp
    git pull
fi

# Download resume
rm -rf resume
git clone git@github.com:albertyw/resume
mv resume/resume.pdf static/gen/resume.pdf
rm -rf resume

# Build container and network
docker build --pull -t "$CONTAINER:$BRANCH" .
docker network inspect "$NETWORK" &>/dev/null ||
    docker network create --driver bridge "$NETWORK"

# Start container
docker stop "$CONTAINER" || true
docker container rm "$CONTAINER" || true
docker run \
    --detach \
    --restart=always \
    --publish="127.0.0.1:$PORT:5000" \
    --network="$NETWORK" \
    --mount type=bind,source="$(pwd)"/static/mount,target=/var/www/app/static/mount \
    --mount type=bind,source="$(pwd)"/logs,target=/var/www/app/logs \
    --name="$CONTAINER" "$CONTAINER:$BRANCH"

if [ "$ENV" = "production" ]; then
    if [ "$BRANCH" = "master" ]; then
        # Cleanup docker
        docker system prune --force --filter "until=168h"
        docker volume prune --force
    fi

    # Update nginx
    sudo cp "/home/albertyw/albertyw.com/config/nginx/app" "/etc/nginx/sites-enabled/albertyw.com-app"
    docker exec nginx /etc/init.d/nginx reload
fi