Home / Resource / Docker Run Postgres: Practical Setup, Persistence, and Production Notes

Docker Run Postgres: Practical Setup, Persistence, and Production Notes

Installing PostgreSQL on a laptop used to mean packages, service accounts, configuration files, and a cleanup job nobody enjoyed when the project ended. Containers changed that. Today a developer can have a working PostgreSQL server in seconds, throw it away after a test, and start a fresh one just as fast.

The command most people reach for is docker run postgres, and it really is that simple to begin. The details that matter come right after: keeping your data when the container goes away, setting passwords safely, picking the right image version, and knowing where a container stops being a good idea. This guide covers the setup, persistence, and production notes you need to use PostgreSQL in Docker properly.

Key Takeaways

  • One command to start: docker run --name pg -e POSTGRES_PASSWORD=... -d postgres gives you a running PostgreSQL server.
  • Data needs a volume: without one, your databases disappear when the container is removed.
  • PostgreSQL 18 changed the data path: mount volumes at /var/lib/postgresql for 18 and later, and at /var/lib/postgresql/data for 17 and earlier.
  • Pin your version: use a tag such as postgres:18 instead of latest, because major upgrades need a proper migration.

The Quickest Way to Start PostgreSQL in Docker

Run the official image with a container name and a superuser password. The example from the official postgres image documentation looks like this:

docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres

That’s enough to get a server running inside the container. To reach it from your machine, publish the port as well, and pin a version while you’re at it:

docker run --name pg-dev \
  -e POSTGRES_PASSWORD=change-me \
  -p 5432:5432 \
  -d postgres:18

Here’s what each part does:

Part of the commandWhat it does
--name pg-devGives the container a name, so you can refer to it in later commands
-e POSTGRES_PASSWORD=...Sets the superuser password, which the image requires
-p 5432:5432Maps port 5432 on your machine to PostgreSQL’s port inside the container
-dRuns the container in the background
postgres:18Uses the official image, pinned to the PostgreSQL 18 major version

Connecting to the Database

You can connect from inside the container or from your own machine. From inside, use the psql client that ships with the image:

docker exec -it pg-dev psql -U postgres

From your machine, any PostgreSQL client works with host localhost, port 5432, user postgres, and the password you set. If you’re new to the database itself, our overview of what PostgreSQL is used for is a good primer.

Building something serious on PostgreSQL?

RalanTech’s PostgreSQL consultants help with architecture, performance, migrations, and production readiness, from container to cluster.

Explore PostgreSQL Consulting →

Environment Variables That Shape the Container

The official image is configured through environment variables. Only one is required. The others let you change the default user, database, and initialization settings.

VariableWhat it controlsDefault
POSTGRES_PASSWORDPassword for the superuser; it must not be emptyRequired
POSTGRES_USERName of the superuser to createpostgres
POSTGRES_DBName of the default databaseSame as POSTGRES_USER
POSTGRES_INITDB_ARGSExtra arguments passed to initdb, such as --data-checksumsNone
POSTGRES_HOST_AUTH_METHODAuthentication method for host connectionsscram-sha-256 on PostgreSQL 14 and later
PGDATALocation of the data directory inside the containerVersion-specific from PostgreSQL 18

Two habits keep this safe. Don’t set POSTGRES_HOST_AUTH_METHOD to trust, which the image documentation advises against, because it allows connections without a password. And for anything beyond a laptop, use the _FILE variants, such as POSTGRES_PASSWORD_FILE=/run/secrets/postgres-passwd, so the password comes from a secret rather than your command history.

Keeping Your Data With Volumes

A container’s own file system disappears when you remove the container. If your data lives there, docker rm deletes your databases with it. A volume stores the data outside the container, so you can stop, remove, and recreate the container without losing anything. Docker’s volumes documentation recommends volumes as the preferred way to persist container data.

Where you mount the volume depends on the PostgreSQL version, and this changed recently. The image documentation explains that from PostgreSQL 18, the defined volume moved to /var/lib/postgresql and the data directory became version-specific. For PostgreSQL 17 and earlier, you should still mount at /var/lib/postgresql/data.

# PostgreSQL 18 and later
docker run --name pg18 -e POSTGRES_PASSWORD=change-me \
  -v pgdata18:/var/lib/postgresql \
  -p 5432:5432 -d postgres:18

# PostgreSQL 17 and earlier
docker run --name pg17 -e POSTGRES_PASSWORD=change-me \
  -v pgdata17:/var/lib/postgresql/data \
  -p 5433:5432 -d postgres:17

Getting this path wrong is one of the most common reasons data “disappears”. The container starts fine, you create tables, and then a rebuild brings back an empty database because the data was never written to the volume.

docker run postgres volume setup
docker run postgres volume setup

Named Volumes vs Bind Mounts

You’ve got two ways to store the data outside the container:

  • Named volumes, like pgdata18 above, are managed by Docker. They’re the simplest choice and avoid most file permission problems.
  • Bind mounts map a folder on your machine, such as -v /srv/pg:/var/lib/postgresql. They make the files easy to see and back up, but ownership and permissions on the host folder need care.

Example: The Disappearing Test Database

Here’s an illustrative case. A developer starts postgres:18 without a volume, loads a week of test data, and then runs docker rm -f to change a port. The new container starts with an empty server, and the test data is gone.

Adding -v pgdata18:/var/lib/postgresql from the start fixes it. The next time the container is replaced, PostgreSQL finds its existing data directory in the volume and carries on where it left off.

Running Setup Scripts Automatically

The image runs scripts from /docker-entrypoint-initdb.d when it creates a new database. That’s handy for creating schemas, roles, or sample data. It runs *.sql files and executable *.sh scripts, and sources shell scripts that aren’t executable.

docker run --name pg-dev -e POSTGRES_PASSWORD=change-me \
  -v pgdata18:/var/lib/postgresql \
  -v "$(pwd)/init":/docker-entrypoint-initdb.d \
  -p 5432:5432 -d postgres:18

There’s one catch that confuses almost everyone once. These scripts only run when the container starts with an empty data directory. If your volume already holds a database, the scripts are skipped. To rerun them during development, remove the volume first, accepting that its data goes with it.

A Docker Compose Version

For anything you’ll start more than a few times, Docker Compose keeps the settings in one file. This version adds a named volume, a health check, and a larger shared memory size, which the official image’s own Compose example also sets.

services:
  db:
    image: postgres:18
    restart: unless-stopped
    shm_size: 256mb
    environment:
      POSTGRES_USER: app
      POSTGRES_DB: appdb
      POSTGRES_PASSWORD_FILE: /run/secrets/pg_password
    secrets:
      - pg_password
    volumes:
      - pgdata:/var/lib/postgresql
      - ./init:/docker-entrypoint-initdb.d
    ports:
      - "127.0.0.1:5432:5432"
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U app -d appdb"]
      interval: 10s
      retries: 5

secrets:
  pg_password:
    file: ./pg_password.txt

volumes:
  pgdata:

Start it with docker compose up -d. Binding the port to 127.0.0.1 means only your own machine can connect, which is a sensible default for development.

Choosing and Pinning an Image Tag

Always pin at least the major version. The latest tag moves to each new major release, and PostgreSQL can’t simply open a data directory created by an older major version.

At the time of writing, the official image offers PostgreSQL 14 through 18, with 18 as latest, in Debian and Alpine variants. Debian-based tags are the safer default for most teams. Alpine images are smaller, but some extensions and locale behavior can differ.

When you do move to a new major version, treat it as a migration. The PostgreSQL project’s guide to upgrading a PostgreSQL cluster covers the two main routes: dump and restore, or pg_upgrade. In containers, dump and restore into a new container with a new volume is usually the easiest.

Production Notes: Should You Run PostgreSQL in Docker?

You can, and many teams do. But the container is the easy part. Running a database in production still needs the same discipline it always did, plus a few container-specific checks:

  • Storage: put the data on reliable, fast persistent storage, and know exactly where the volume lives and how it’s backed up.
  • Backups and recovery: schedule regular backups, test restores, and decide how you’ll fail over. Container restarts aren’t a high availability plan, which is where business continuity planning comes in.
  • Security: never publish port 5432 to the internet, use secrets for passwords, keep the image patched, and create application users instead of sharing the superuser.
  • Resources and monitoring: set memory and CPU limits deliberately, raise shared memory if queries fail, and watch the database itself, not just the container. A database monitoring service catches slow queries and growing tables before users do.

For a lot of production workloads, the honest answer is a managed PostgreSQL service or a carefully run cluster, with containers kept for development, testing, and CI. Our guide to PostgreSQL cloud migration walks through those options.

Backing Up and Restoring a Container Database

You can run PostgreSQL’s own backup tools through docker exec:

# Back up one database to a file on your machine
docker exec -t pg-dev pg_dump -U postgres -d appdb -Fc > appdb.dump

# Restore it into another container where appdb already exists
docker exec -i pg-new pg_restore -U postgres -d appdb < appdb.dump

The custom format (-Fc) is compressed and lets pg_restore restore selected objects. Test a restore regularly, because a backup you’ve never restored is only a hope.

Running PostgreSQL in production?

RalanTech’s PostgreSQL support team handles monitoring, backups, upgrades, and performance, so your database keeps up with your application.

Get PostgreSQL Support →

Common Problems and How to Fix Them

Most first-run problems come from a handful of causes.

What you seeLikely causeFix
The container exits with “Database is uninitialized and superuser password is not specified”POSTGRES_PASSWORD wasn’t setAdd -e POSTGRES_PASSWORD=... or use POSTGRES_PASSWORD_FILE
“Port is already allocated”Another PostgreSQL server or container already uses port 5432Stop the other service, or map a different host port such as -p 5433:5432
Data is gone after recreating the containerNo volume, or a volume mounted at the wrong path for your versionMount at /var/lib/postgresql for 18 and later, or /var/lib/postgresql/data for 17 and earlier
Init scripts didn’t runThe volume already contained a databaseStart with an empty volume, or run the script manually with psql
Queries fail with “could not resize shared memory segment”Docker’s default shared memory is too small for the workloadIncrease it with --shm-size or shm_size in Compose
The new major version won’t start on old dataThe data directory was created by an earlier major versionDump and restore, or use pg_upgrade, into a fresh volume

If containers are part of a bigger move away from a commercial database, our Oracle vs PostgreSQL comparison covers the licensing and feature differences to plan around. Once the database is live, our PostgreSQL performance tuning tips help keep it fast as data grows.

Frequently Asked Questions

What is the basic docker run command for PostgreSQL?

docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgres. Add -p 5432:5432 to connect from your machine and a volume to keep your data.

Where does PostgreSQL store data in the Docker image?

For PostgreSQL 18 and later, mount your volume at /var/lib/postgresql, because the data directory is version-specific. For 17 and earlier, mount at /var/lib/postgresql/data.

Is POSTGRES_PASSWORD required?

Yes. The official image won’t initialize a new database without it, unless you deliberately change the authentication method, which isn’t recommended.

Why don’t my scripts in /docker-entrypoint-initdb.d run?

They only run when the container starts with an empty data directory. If the volume already contains a database, they’re skipped.

Can I upgrade PostgreSQL by changing the image tag?

Only within the same major version, such as 18.5 to 18.6. Moving between major versions, such as 17 to 18, needs a dump and restore or pg_upgrade.

Is it safe to run PostgreSQL in Docker in production?

It can be, with persistent storage, tested backups, security controls, monitoring, and a high availability plan. Many teams use containers for development and testing, and managed services or dedicated clusters for production.

Conclusion

With docker run postgres, starting a database takes one command. Running it well takes a few more decisions: a volume at the right path for your version, a pinned image tag, passwords kept in secrets, and a clear plan for backups and upgrades.

Get those right and containers become a fast, repeatable way to give every developer and every test run its own database. For production, treat the container as packaging, and keep the same care for storage, recovery, and monitoring that any important database deserves.

Taking PostgreSQL from container to production?

Talk to RalanTech’s database experts about architecture, high availability, and day-to-day support for PostgreSQL.

Schedule a Free Consultation →

Pros & Cons

Conclusion

Picture of Raju Chidambaram

Raju Chidambaram

Raju Chidambaram is a seasoned technology executive with over 30 years of global leadership in enterprise IT, cloud architecture, and secure data operations. As the Co-Founder and Chief Technology Officer at RalanTech, Raju is the strategic force behind high-performance technology platforms that drive business transformation for Fortune 1000 companies and emerging growth companies. With deep expertise rooted in enterprise data center management and mission-critical database systems, Raju brings unparalleled depth in cloud strategy, database modernization, and multi-cloud migration. He has architected scalable, resilient, and secure data platforms across hybrid and public cloud environments, ensuring performance, compliance, and business continuity for over 200+ enterprise clients.

About RalanTech

RalanTech is specialized in database managed services. We are passionate about leveraging cutting-edge solutions to drive innovation, efficiency, and growth for our clients.

Related Posts

Be the First to Know What’s Shaping Your Industry.

Join thousands of professionals who rely on our newsletter for insights that drive real growth. Signup now and stay informed, inspired, and ahead.