Prerequisites

  1. A VM (EC2, Hostinger VM, or DigitalOcean Droplet)
  2. Docker + Docker Compose installed on the VM
  3. An app/project running on the same VM that will use this database

1) Create the Docker Compose file

Create a file named docker-compose.yml in the root of your project.

services:
  postgres:
    image: postgres:16-alpine
    container_name: elitecron_postgres_db # change this if you want
    restart: unless-stopped

    env_file:
      - .env

    environment:
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
      POSTGRES_DB: ${POSTGRES_DB}
      PGDATA: /var/lib/postgresql/data/pgdata

    # Bind to localhost only so it isn't exposed to the public internet
    ports:
      - "127.0.0.1:${POSTGRES_PORT:-5432}:5432"

    volumes:
      - elitecron_postgres_data:/var/lib/postgresql/data/pgdata
      - ./backups:/backups

    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  elitecron_postgres_data:
    driver: local

What this docker-compose.yml does

2) Create the .env file

Create a file named .env next to your compose file.

# Docker Postgres
POSTGRES_USER=elitedev
POSTGRES_PASSWORD=CHANGE_ME
POSTGRES_DB=elite_cron
POSTGRES_PORT=5432

# App connection string (app runs on the same VM)
DATABASE_URL=postgresql://elitedev:[email protected]:5432/elite_cron

3) Start Postgres