> ## Documentation Index
> Fetch the complete documentation index at: https://docs.monk.io/llms.txt
> Use this file to discover all available pages before exploring further.

# PostgreSQL

> Production-ready PostgreSQL runnable you can run directly or inherit to integrate a relational database into your stack.

## Overview

This template provides a PostgreSQL runnable exposing port 5432 with a persistent data volume. Use it directly for quick starts, or inherit it in your app and wire credentials via Monk secrets.

## Quick start (run directly)

```bash theme={null}
monk load MANIFEST
monk run postgresql/db
```

Connect to `localhost:5432` with the default credentials from `postgres.yml`.

## Configuration

Key variables in `postgres.yml` (under `postgresql/db`):

```yaml theme={null}
variables:
  db_user: monk                 # env: POSTGRES_USER
  db_pass: adminpassword        # env: POSTGRES_PASSWORD
  db_name: monk                 # env: POSTGRES_DB
```

Note: When running the base template directly, values come from the template. For production, inherit and replace with Monk secrets.

## Inherit and use secrets (recommended)

```yaml theme={null}
namespace: myapp

db:
  defines: runnable
  inherits: postgresql/db

api:
  defines: runnable
  containers:
    api:
      image: myorg/api
  connections:
    database:
      runnable: db
      service: postgres
  variables:
    database-host:
      value: <- connection-hostname("database")
    database-user:
      value: <- secret("db_user")
    database-password:
      value: <- secret("db_pass")
    database-name:
      value: <- secret("db_name")
```

Set secrets once, then run:

```bash theme={null}
monk secrets add -g db_user="appuser"
monk secrets add -g db_pass="STRONG_PASSWORD"
monk secrets add -g db_name="appdb"

monk run myapp/api
```

## Ports and persistence

* Service: `postgres` on TCP `5432`
* Data path: `${monk-volume-path}/postgresql:/var/lib/postgresql/data`

## Credential updates

This template includes a custom entrypoint that automatically updates the database password when the `POSTGRES_PASSWORD` environment variable changes. Unlike the default PostgreSQL Docker image behavior (which only applies credentials on first initialization), this template ensures password changes take effect on existing databases.

When the container starts:

1. If an existing database is detected, the entrypoint updates the user password via `ALTER USER`
2. If it's a fresh initialization, credentials are applied normally by the PostgreSQL image

## Troubleshooting

* Ensure the host volume is writable by the container.
* Check container logs (`monk logs postgresql/db`) if credential updates fail.
