From 8857cf6fa5375cd6ea4128bd28f183d1d725dafd Mon Sep 17 00:00:00 2001
From: Adar Nimrod <nimrod@shore.co.il>
Date: Thu, 3 Mar 2022 22:32:00 +0200
Subject: [PATCH] Postgres image.

---
 .gitlab-ci.yml          | 16 ++++++++++++++++
 .pre-commit-config.yaml |  1 +
 postgres/Dockerfile     |  3 +++
 postgres/README.md      |  3 +++
 postgres/healthcheck    | 21 +++++++++++++++++++++
 5 files changed, 44 insertions(+)
 create mode 100644 postgres/Dockerfile
 create mode 100644 postgres/README.md
 create mode 100755 postgres/healthcheck

diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml
index aee9248..6ea181f 100644
--- a/.gitlab-ci.yml
+++ b/.gitlab-ci.yml
@@ -179,3 +179,19 @@ push-youtube-dl:
   needs:
     - job: build-youtube-dl
       artifacts: true
+
+# postgres image:
+
+build-postgres:
+  extends: .container-build
+  variables:
+    CONTEXT: postgres
+
+push-postgres:
+  extends: .container-push
+  variables:
+    CONTEXT: postgres
+    IMAGE: postgres
+  needs:
+    - job: build-postgres
+      artifacts: true
diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml
index ebe02f7..f7cd63f 100644
--- a/.pre-commit-config.yaml
+++ b/.pre-commit-config.yaml
@@ -66,6 +66,7 @@ repos:
     rev: v0.2.0
     hooks:
       - id: shell-validate
+        exclude: postgres/healthcheck
 
   - repo: https://github.com/AleksaC/hadolint-py.git
     rev: v2.8.0
diff --git a/postgres/Dockerfile b/postgres/Dockerfile
new file mode 100644
index 0000000..766559f
--- /dev/null
+++ b/postgres/Dockerfile
@@ -0,0 +1,3 @@
+FROM docker.io/postgres:14-alpine
+COPY --chown=root:root healthcheck /usr/local/bin/
+HEALTHCHECK --start-period=3m CMD healthcheck
diff --git a/postgres/README.md b/postgres/README.md
new file mode 100644
index 0000000..42e8063
--- /dev/null
+++ b/postgres/README.md
@@ -0,0 +1,3 @@
+# postgres
+
+Just the upstream image but with a healthcheck.
diff --git a/postgres/healthcheck b/postgres/healthcheck
new file mode 100755
index 0000000..19c1ed7
--- /dev/null
+++ b/postgres/healthcheck
@@ -0,0 +1,21 @@
+#!/usr/bin/env bash
+set -eo pipefail
+
+host="$(hostname -i || echo '127.0.0.1')"
+user="${POSTGRES_USER:-postgres}"
+db="${POSTGRES_DB:-$POSTGRES_USER}"
+export PGPASSWORD="${POSTGRES_PASSWORD:-}"
+
+args=(
+	# force postgres to not use the local unix socket (test "external" connectibility)
+	--host "$host"
+	--username "$user"
+	--dbname "$db"
+	--quiet --no-align --tuples-only
+)
+
+if select="$(echo 'SELECT 1' | psql "${args[@]}")" && [ "$select" = '1' ]; then
+	exit 0
+fi
+
+exit 1
-- 
GitLab