PortGate

Blueprints · Docker & Databases

Production 15 min · Docker

UFW-safe Docker Compose for PostgreSQL and Redis

Publishes Postgres and Redis on the host loopback only. Both services drop privileges, keep a read-only root filesystem, and cap memory.

Why this should not be public

Postgres on 5432 and Redis on 6379 are two of the most-scanned ports on the internet. A public Postgres invites password guessing against the postgres role; a public Redis without a password lets anyone read every key and abuse CONFIG to write files on the host.

Live config

Baked-in protections

Step 1 · yaml

compose.yaml

/opt/data/compose.yaml

Redis listens on the container interface so the published loopback port can connect. It is not published on 0.0.0.0.

services:
  postgres:
    image: postgres:17
    environment:
      POSTGRES_DB: app
      POSTGRES_USER: app
      POSTGRES_PASSWORD: change-me
    ports:
      - "127.0.0.1:5432:5432"
    cap_drop:
      - ALL
    cap_add:
      - CHOWN
      - DAC_OVERRIDE
      - FOWNER
      - SETGID
      - SETUID
    read_only: true
    tmpfs:
      - /tmp
      - /run/postgresql
    volumes:
      - pgdata:/var/lib/postgresql/data
    mem_limit: 512m
    security_opt:
      - no-new-privileges:true
    restart: unless-stopped
  redis:
    image: redis:7
    command: ["redis-server", "--protected-mode", "yes", "--requirepass", "change-me"]
    ports:
      - "127.0.0.1:6379:6379"
    cap_drop:
      - ALL
    read_only: true
    tmpfs:
      - /tmp
    volumes:
      - redisdata:/data
    mem_limit: 256m
    security_opt:
      - no-new-privileges:true
    restart: unless-stopped
volumes:
  pgdata:
  redisdata:

Step 2 · bash

Start command

/opt/data/up.sh

Written, not run. Change both passwords before the first start.

#!/bin/sh
set -eu
if [ "change-me" = "change-me" ] || [ "change-me" = "change-me" ]; then
  echo "Set DB_PASSWORD and REDIS_PASSWORD before starting." >&2
  exit 1
fi
cd "/opt/data"
docker compose up -d