Self-Hosted PostgreSQL for Docker Apps: Production Setup, Backups, Upgrades, and Connection Pooling
PostgreSQLDockerDocker ComposeDatabase BackupsDevOpsSelf-Hosting

Self-Hosted PostgreSQL for Docker Apps: Production Setup, Backups, Upgrades, and Connection Pooling

sselfhosting.cloud Editorial Team
2026-11-13
7 min read

A practical PostgreSQL Docker checklist covering secure Compose setup, backups, recovery tests, upgrades, roles, and connection pooling.

This practical self-hosted PostgreSQL Docker guide gives you a repeatable production setup, including persistent storage, private networking, application roles, health checks, backups, recovery tests, upgrades, and connection pooling. Use it as a checklist whenever you add a Docker application or change your database infrastructure.

Overview

PostgreSQL is a strong default database for many self-hosted applications, but running it in Docker does not remove the responsibilities of database administration. A container can be recreated; your database data cannot. The important design decisions are therefore outside the container image: where data is stored, which networks can reach PostgreSQL, how credentials are managed, how backups are verified, and how a major-version upgrade will be performed.

For a small Docker Compose stack, keep PostgreSQL on a private application network and expose it only to the services that need it. Use a named volume or a deliberately managed host directory for the data directory. Pin the PostgreSQL image to a major version rather than using an unbounded tag, and plan image updates separately from major-version migrations. An image refresh and a PostgreSQL major upgrade are different operations.

This approach fits a VPS, home server, or homelab, but the recovery expectations should match the importance of the application. A personal test database may need a simple scheduled dump. A password manager, file-sharing service, or business application should also have off-host backups and documented restore tests. For broader stack planning, see Self-Hosted App Stack Planning.

PostgreSQL configuration reference

AreaRecommended baselineWhy it matters
ImagePin a supported PostgreSQL major versionPrevents an unexpected major upgrade during deployment.
StorageUse persistent storage with monitored capacityContainer replacement must not remove database files.
NetworkUse an internal Docker network where practicalReduces unnecessary exposure of the database port.
AuthenticationUse application-specific credentials and a secret store or protected environment fileLimits the impact of credential disclosure.
BackupsTake logical dumps and copy them away from the hostA local backup is not sufficient after disk or host failure.
ConnectionsSet a deliberate connection budget; add a pooler when neededMany application workers can exhaust PostgreSQL connections.
MonitoringWatch availability, disk usage, backup success, and restore resultsFailures become visible before they become data-loss events.

Checklist by scenario

Initial PostgreSQL Docker Compose setup

Create a dedicated directory for the stack and keep the Compose file, environment file, backup scripts, and runbook together. The following template is intentionally conservative. Replace the image tag with the PostgreSQL major version you have selected and tested.

services:
  db:
    image: postgres:<supported-major>
    restart: unless-stopped
    environment:
      POSTGRES_DB: ${POSTGRES_DB}
      POSTGRES_USER: ${POSTGRES_USER}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
    volumes:
      - postgres_data:/var/lib/postgresql/data
    networks:
      - app_private
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
      interval: 10s
      timeout: 5s
      retries: 5

volumes:
  postgres_data:

networks:
  app_private:
    internal: true

Store the variables in a protected environment file, restrict its permissions, and do not commit it to Git. The application should use the database service name, such as db, as its hostname. Do not use localhost from one container to reach another: inside a container, localhost refers to that same container.

Do not publish 5432 to the host unless you have a specific administrative requirement. If you need temporary access, prefer a controlled tunnel or an authenticated administrative path, then remove the exposure. A reverse proxy such as Traefik or Nginx Proxy Manager is for HTTP services, not a substitute for database network controls.

Adding an application database

  • Confirm the application supports the selected PostgreSQL major version and required extensions.
  • Create a separate database and role for each application where practical.
  • Give the application only the permissions it requires; avoid using the PostgreSQL superuser.
  • Set the application connection string without placing credentials in public Compose files.
  • Start PostgreSQL first and wait for the health check before running migrations.
  • Run migrations as a controlled deployment step, not on every container restart unless the application explicitly documents that behavior.
  • Record the database name, role, extension requirements, migration command, and restore procedure.

Backups and recovery

A Docker volume is persistence, not a backup. Schedule pg_dump or an equivalent PostgreSQL-aware backup tool, retain multiple restore points, and copy completed backups to storage that is independent of the Docker host. Protect backup files because logical dumps may contain application data and credentials stored by the application.

For a simple database, a compressed custom-format dump can be a useful starting point:

docker compose exec -T db pg_dump \
  -U "$POSTGRES_USER" \
  -d "$POSTGRES_DB" \
  -Fc > "backups/app-$(date +%Y-%m-%d_%H%M).dump"

Run scheduled jobs from a host scheduler or a dedicated backup system rather than assuming that a one-off command is a backup policy. Check the command's exit status, record its completion, prune old files according to your retention plan, and periodically restore a dump into a separate temporary PostgreSQL instance. A backup that has never been restored is an assumption, not a tested recovery path.

Connection pooling

Each application worker can consume a PostgreSQL connection, and several self-hosted apps sharing one server can collectively reach the database connection limit. First set a connection budget per application and configure its pool size conservatively. Then measure active connections before increasing limits.

If the application creates many short-lived connections or you run several services, consider a PostgreSQL-compatible pooler such as PgBouncer. Place it between applications and PostgreSQL, document whether it uses session or transaction pooling, and test prepared statements, session settings, long-running transactions, and migrations. Pooling improves connection management; it does not replace query tuning or adequate memory and storage planning.

What to double-check

  • Storage: Confirm where the volume resides, how much free space remains, and whether the host filesystem is suitable for database workloads. Alert before the disk is full.
  • Credentials: Rotate application passwords deliberately. Update the application and database role in an order that avoids an unnecessary outage, and remove obsolete roles after confirming they are unused.
  • Authentication: Review the image's authentication defaults and the generated pg_hba.conf behavior for your selected version. Never assume a copied configuration remains correct after an upgrade.
  • Extensions: List extensions used by each application and verify they are available in the replacement image before upgrading.
  • Health checks: A successful pg_isready check proves that PostgreSQL accepts connections; it does not prove that migrations, queries, backups, or the application are healthy.
  • Recovery: Confirm that backups are readable, located off-host, encrypted or access-controlled where appropriate, and accompanied by the required environment variables and application configuration.
  • Upgrade path: Test the application against the target major version using a copy of production-like data. Follow the PostgreSQL and application documentation for major-version migration rather than only changing the image tag.

Common mistakes

Using latest: An unpinned image makes the deployment less predictable. Pin a major version and update it intentionally.

Publishing port 5432 by default: Most Docker applications can connect through a private network. Avoid turning a private database into an internet-facing service.

Backing up only the volume: Copying live database files without a PostgreSQL-aware process can produce an unusable or inconsistent recovery artifact. Use logical dumps or a documented physical-backup method.

Sharing one superuser: A single administrative credential makes auditing and rotation harder. Use separate application roles and reserve administrative access for maintenance.

Ignoring migrations during restores: Restoring database data without the matching application version can cause schema or compatibility problems. Record the application release associated with each backup.

Adding a pooler without testing: Pooling can change session behavior. Test the application's migrations, prepared statements, transactions, and administrative commands before making it part of the normal path.

When to revisit

Revisit this checklist before adding an application, moving from a home server to a VPS, changing storage, rotating credentials, or exposing a service through a new network path. Also review it before seasonal planning cycles when you can schedule maintenance and recovery tests without pressure.

Use this upgrade runbook for a PostgreSQL major-version change:

  1. Read the PostgreSQL release notes and the application compatibility documentation.
  2. Inventory databases, roles, extensions, storage usage, connection settings, and backup locations.
  3. Take and verify a fresh backup, then record the rollback plan.
  4. Test the migration on a separate instance with representative data.
  5. Schedule a maintenance window and stop application writes before the final backup or migration step.
  6. Upgrade using the documented method, run application migrations, and verify critical queries and workflows.
  7. Monitor logs, connections, disk usage, and application errors after reopening traffic.
  8. Perform a restore test after the upgrade and update the runbook with what changed.

Finally, revisit the setup when PostgreSQL, the container image, Compose behavior, backup tooling, or an application's extension requirements change. Keeping the image tag, restore procedure, and connection budget current is more valuable than adding complexity prematurely.

Related Topics

#PostgreSQL#Docker#Docker Compose#Database Backups#DevOps#Self-Hosting
s

selfhosting.cloud Editorial Team

Senior SEO Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.