Skip to content

Instantly share code, notes, and snippets.

@mtilson
Last active May 9, 2024 09:45
Show Gist options
  • Save mtilson/28e84706dc41d90c428a3d684f919cce to your computer and use it in GitHub Desktop.
Save mtilson/28e84706dc41d90c428a3d684f919cce to your computer and use it in GitHub Desktop.
how to rebuild your web app container on every commit with local 'docker-compose' and 'post-commit' git hook [docker] [docker-compose] [git]
APPNAME=myapp
APPVERSION=latest

A simple way to rebuild your web app container on every commit with local docker-compose and post-commit git hook

  1. Initialize your git repo with git init
  2. Place the attached post-commit file into .git/hooks/ directory and make it executable with chmod +x .git/hooks/post-commit
  3. Use the attached docker-compose.yaml and Dockerfile as examples to create and run container
  4. The .env file is not commited to VCS as it may contain secure configuration details. Put variables there like the following ones:
    • APPNAME=myapp
    • APPVERSION=latest
  5. post-commit working directory is the repo root, it is the same one where .git is located
  6. The post-commit script is Linux and MacOS compartible
  7. Logs for building and running container is available in /tmp/git-post-commit as APPNAME-YYYYMMDD-HHMMSS-XXX files
  8. Link to the Repo
version: '2.4'
services:
myservice:
container_name: ${APPNAME:-myapp}
image: ${APPNAME:-myapp}:${APPVERSION:-latest}
networks:
- commonnet
ports:
- "80:80"
networks:
commonnet:
name: common-network
FROM nginx
COPY index.html /usr/share/nginx/html/index.html
<!DOCTYPE html>
<html lang="en-us">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title> My site </title>
<meta name="viewport" content="width=device-width,minimum-scale=1">
</head>
<body>
<header>
<div>
<div> <h1> My site </h1> </div>
</div>
</header>
</body>
</html>
#!/usr/bin/env bash
set -o errexit
test -e .env && source .env || echo "$0: warn: no '.env' file in $(pwd): default values will be used"
readonly APPNAME="${APPNAME:-myapp}"
readonly APPVERSION="${APPVERSION:-latest}"
readonly TMPDIR="/tmp/git-post-commit"
test -d $TMPDIR || mkdir -p $TMPDIR
readonly LOGFILE=$(mktemp -q ${TMPDIR}/${APPNAME}-`date '+%Y%m%d-%H%M%S'`-XXX)
exec 1>$LOGFILE
exec 2>&1
docker build -t ${APPNAME}:${APPVERSION} -f Dockerfile .
docker-compose -f docker-compose.yaml up -d --no-deps --build
docker system prune -f
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment