Spaces:
Running
Running
Add initial Docker setup with PostgREST and PostgreSQL configuration
Browse filesFiles changed (4)
- .env.exampleAdded+48
- DockerfileAdded+58
- init.sqlAdded+46
- start.shAdded+39
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748# ============================================================# PostgREST + PostgreSQL (Hugging Face Space) — env vars# Copy to `.env` and adjust. HF Spaces only allows PORT to be# set via the Space settings; everything else can live here.# ============================================================
# --- Server ---# Port PostgREST listens on. HF Spaces requires 7860.PORT=7860# Bind address (keep 0.0.0.0 for HF Spaces)PGRST_SERVER_HOST=0.0.0.0
# --- Database connection ---# Full connection URI. Inside this container Postgres runs on a# local unix socket, so the default below is usually fine.# For an external DB, use e.g.:# postgresql://authenticator:secret@db.example.com:5432/prodPGRST_DB_URI=postgresql://?host=/var/run/postgresql&port=5432&dbname=postgres
# Comma-separated schemas exposed by the APIPGRST_DB_SCHEMA=api
# Role used for unauthenticated (anonymous) requestsPGRST_DB_ANON_ROLE=web_anon
# Role used to apply schema changes / own objectsAUTHENTICATOR_PASSWORD=secret
# --- Auth (optional) ---# Secret used to sign/verify JWTs. Generate one with:# echo "secret" | openssl dgst -sha256 -hmac "your-key" -binary | base64# Leave empty to disable JWT auth (public API).PGRST_JWT_SECRET=# Claim that carries the DB role in the JWT (default: "role")PGRST_JWT_ROLE_CLAIM_KEY=role# Audience claim to require, if anyPGRST_JWT_AUDIENCE=
# --- API behavior (optional) ---# Max rows per request (Content-Range limiting)PGRST_MAX_ROWS=# Allow CORS from any origin (useful for browser clients)PGRST_CORS_ALLOWED_ORIGINS=*# Path prefix if served behind a proxy (usually empty on HF)PGRST_SERVER_PATH_PREFIX=
# --- PostgREST version pinned in the Dockerfile ---PGRST_VERSION=16.212345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758# PostgREST + PostgreSQL in a single container (Hugging Face Space)# Serves a fully RESTful API from a Postgres database on port 7860.
FROM debian:bookworm-slim
ENV DEBIAN_FRONTEND=noninteractive \ PGRST_VERSION=16.2 \ PORT=7860 \ PGRST_DB_SCHEMAS=api \ PGRST_DB_ANON_ROLE=web_anon \ PGRST_SERVER_HOST=0.0.0.0
# Debian's postgresql package installs binaries outside the default PATHENV PATH="/usr/lib/postgresql/15/bin:${PATH}"
# --- System dependencies: PostgreSQL server + tools ---RUN apt-get update && apt-get install -y --no-install-recommends \ ca-certificates \ curl \ xz-utils \ libpq5 \ postgresql \ postgresql-contrib \ postgresql-client \ sudo \ && rm -rf /var/lib/apt/lists/*
# --- PostgREST binary (static build from GitHub releases) ---RUN ARCH="$(dpkg --print-architecture)" \ && case "$ARCH" in \ amd64) PGRST_ARCH=x86-64 ;; \ arm64) PGRST_ARCH=aarch64 ;; \ *) echo "unsupported arch: $ARCH" && exit 1 ;; \ esac \ && curl -fsSL \ "https://github.com/PostgREST/postgrest/releases/download/v${PGRST_VERSION}/postgrest-v${PGRST_VERSION}-linux-static-${PGRST_ARCH}.tar.xz" \ -o /tmp/postgrest.tar.xz \ && tar -xJf /tmp/postgrest.tar.xz -C /usr/local/bin \ && chmod +x /usr/local/bin/postgrest \ && rm /tmp/postgrest.tar.xz \ && postgrest --version
# --- Non-root user (HF Spaces runs containers as a random UID) ---RUN useradd -m -u 10001 appuser \ && mkdir -p /var/lib/postgresql/data /var/run/postgresql \ && chown -R appuser:appuser /var/lib/postgresql /var/run/postgresql /usr/local/bin/postgrest
USER appuserWORKDIR /home/appuser
# --- Sample schema: a tiny "todos" API to demo PostgREST ---COPY --chown=appuser:appuser init.sql /docker-entrypoint-init.d/init.sqlCOPY --chown=appuser:appuser start.sh /usr/local/bin/start.shRUN chmod +x /usr/local/bin/start.sh
EXPOSE 7860
CMD ["start.sh"]12345678910111213141516171819202122232425262728293031323334353637383940414243444546-- Schema + roles for PostgREST, executed once at container startup.
-- Role PostgREST connects as (anonymous / public access)CREATE ROLE web_anon LOGIN NOINHERIT;
-- Role used to apply schema changesCREATE ROLE authenticator NOINHERIT LOGIN PASSWORD 'secret';GRANT web_anon TO authenticator;
CREATE SCHEMA api;GRANT USAGE ON SCHEMA api TO web_anon;
CREATE TABLE api.todos ( id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, done boolean NOT NULL DEFAULT false, task text NOT NULL, due timestamptz, created_at timestamptz NOT NULL DEFAULT now());
-- Change ownership BEFORE granting: ALTER TABLE ... OWNER TO drops-- privileges granted by the previous owner.ALTER TABLE api.todos OWNER TO authenticator;GRANT SELECT, INSERT, UPDATE, DELETE ON api.todos TO web_anon;GRANT USAGE, SELECT ON SEQUENCE api.todos_id_seq TO web_anon;
INSERT INTO api.todos (task, due) VALUES ('Try GET /todos', now() + interval '1 day'), ('Try POST /todos', now() + interval '2 days'), ('Try PATCH /todos?id=eq.1', now() + interval '3 days');
-- Expose row counts in Content-Range headersCREATE OR REPLACE FUNCTION api.todos_count()RETURNS bigintLANGUAGE sqlAS $$ SELECT count(*) FROM api.todos;$$;
-- OpenAPI description endpointCREATE OR REPLACE FUNCTION api.openapi_description()RETURNS textLANGUAGE sqlAS $$ SELECT 'A demo PostgREST API running on Hugging Face Spaces';$$;123456789101112131415161718192021222324252627282930313233343536373839#!/usr/bin/env bash# Start PostgreSQL, apply the schema, then launch PostgREST on $PORT.set -euo pipefail
# Load .env if present (local runs; HF Spaces injects vars itself)if [ -f .env ]; then set -a . ./.env set +afi
PGDATA=/var/lib/postgresql/dataSOCKET_DIR=/var/run/postgresqlINIT_SQL=/docker-entrypoint-init.d/init.sql
# --- Initialize and start PostgreSQL ---if [ ! -s "$PGDATA/PG_VERSION" ]; then initdb --username=appuser --pgdata="$PGDATA" --auth-local=trust --auth-host=trustfi
pg_ctl -D "$PGDATA" -o "-c listen_addresses=127.0.0.1 -c unix_socket_directories=$SOCKET_DIR -c port=5432" -w start
# Wait until the server accepts connectionsuntil pg_isready -h "$SOCKET_DIR" -p 5432 -q; do sleep 0.2done
# --- Apply schema once ---if ! psql -h "$SOCKET_DIR" -p 5432 -d postgres -Atqc "SELECT 1 FROM pg_roles WHERE rolname='web_anon'" | grep -q 1; then psql -v ON_ERROR_STOP=1 -h "$SOCKET_DIR" -p 5432 -d postgres -f "$INIT_SQL"fi
# --- Launch PostgREST ---export PGRST_DB_URI="postgresql://?host=$SOCKET_DIR&port=5432&dbname=postgres"export PGRST_DB_SCHEMA="${PGRST_DB_SCHEMA:-api}"export PGRST_DB_ANON_ROLE="${PGRST_DB_ANON_ROLE:-web_anon}"export PGRST_SERVER_PORT="${PORT:-7860}"
exec postgrest.env.exampleAdded+48
DockerfileAdded+58
init.sqlAdded+46
start.shAdded+39