PostgreSQL
Container
PostgreSQL, also known as Postgres, is a free and open-source relational database management system emphasizing extensibility and SQL compliance.
Image details
Configuration
TypeContainerlinuxpostgres:latest5432:5432/tcp/var/lib/postgresql/data : /portainer/Files/AppData/Config/PostgreSQLPUID=1000PGID=1000POSTGRES_PASSWORD=rootpasswordTZ=America/New_Yorkunless-stoppedTemplate by novaspirit
Notes
Check our Github page: https://github.com/pi-hosted/pi-hosted
Official Webpage: https://www.postgresql.org/
Official Docker Documentation: https://hub.docker.com/_/postgres/
Standalone Install
Select an install method, to see config/commands for deploying PostgreSQL
Install on Portainer
Import all app templates into your Portainer instance, for easy 1-click deploys
- Ensure both Docker and Portainer are installed, and up-to-date
- Log into your Portainer web UI
- Under Settings → App Templates, paste the below URL
- Head to Home → App Templates, and the list of apps will show up
- Select PostgreSQL, fill in any config options, and hit Deploy
Template Import URL
https://raw.githubusercontent.com/Lissy93/portainer-templates/main/templates.json
Show Me
More install options in our documentation.
Quick reference
- Maintained by:
[the PostgreSQL Docker Community](https://github.com/docker-library/postgres)- Where to get help:
[the Docker Community Slack](https://dockr.ly/comm-slack), [Server Fault](https://serverfault.com/help/on-topic), [Unix & Linux](https://unix.stackexchange.com/help/on-topic), or [Stack Overflow](https://stackoverflow.com/help/on-topic)Supported tags and respective Dockerfile links
Quick reference (cont.)
- Where to file issues:
[https://github.com/docker-library/postgres/issues](https://github.com/docker-library/postgres/issues?q=)- Supported architectures: (more info)
[`amd64`](https://hub.docker.com/r/amd64/postgres/), [`arm32v5`](https://hub.docker.com/r/arm32v5/postgres/), [`arm32v6`](https://hub.docker.com/r/arm32v6/postgres/), [`arm32v7`](https://hub.docker.com/r/arm32v7/postgres/), [`arm64v8`](https://hub.docker.com/r/arm64v8/postgres/), [`i386`](https://hub.docker.com/r/i386/postgres/), [`ppc64le`](https://hub.docker.com/r/ppc64le/postgres/), [`riscv64`](https://hub.docker.com/r/riscv64/postgres/), [`s390x`](https://hub.docker.com/r/s390x/postgres/)- Published image artifact details:
[repo-info repo's `repos/postgres/` directory](https://github.com/docker-library/repo-info/blob/master/repos/postgres) ([history](https://github.com/docker-library/repo-info/commits/master/repos/postgres))
(image metadata, transfer size, etc)- Image updates:
[official-images repo's `library/postgres` label](https://github.com/docker-library/official-images/issues?q=label%3Alibrary%2Fpostgres)
[official-images repo's `library/postgres` file](https://github.com/docker-library/official-images/blob/master/library/postgres) ([history](https://github.com/docker-library/official-images/commits/master/library/postgres))- Source of this description:
[docs repo's `postgres/` directory](https://github.com/docker-library/docs/tree/master/postgres) ([history](https://github.com/docker-library/docs/commits/master/postgres))What is PostgreSQL?
PostgreSQL, often simply "Postgres", is an object-relational database management system (ORDBMS) with an emphasis on extensibility and standards-compliance. As a database server, its primary function is to store data, securely and supporting best practices, and retrieve it later, as requested by other software applications, be it those on the same computer or those running on another computer across a network (including the Internet). It can handle workloads ranging from small single-machine applications to large Internet-facing applications with many concurrent users. Recent versions also provide replication of the database itself for security and scalability.PostgreSQL implements the majority of the SQL:2011 standard, is ACID-compliant and transactional (including most DDL statements) avoiding locking issues using multiversion concurrency control (MVCC), provides immunity to dirty reads and full serializability; handles complex SQL queries using many indexing methods that are not available in other databases; has updateable views and materialized views, triggers, foreign keys; supports functions and stored procedures, and other expandability, and has a large number of extensions written by third parties. In addition to the possibility of working with the major proprietary and open source databases, PostgreSQL supports migration from them, by its extensive standard SQL support and available migration tools. And if proprietary extensions had been used, by its extensibility that can emulate many through some built-in and third-party open source compatibility extensions, such as for Oracle.
wikipedia.org/wiki/PostgreSQL

How to use this image
start a postgres instance
$ docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d postgresThe default
postgres user and database are created in the entrypoint with initdb.The postgres database is a default database meant for use by users, utilities and third party applications.
postgresql.org/docs
... or via psql
$ docker run -it --rm --network some-network postgres psql -h some-postgres -U postgres
psql (14.3)
Type "help" for help.
postgres=# SELECT 1;
?column?
----------
1
(1 row)... via docker compose
Example compose.yaml for postgres:# Use postgres/example user/password credentials
services:
db:
image: postgres
restart: always
# set shared memory limit when using docker compose
shm_size: 128mb
# or set shared memory limit when deploy via swarm stack
#volumes:
# - type: tmpfs
# target: /dev/shm
# tmpfs:
# size: 134217728 # 128*2^20 bytes = 128Mb
environment:
POSTGRES_PASSWORD: example
adminer:
image: adminer
restart: always
ports:
- 8080:8080Run
docker compose up, wait for it to initialize completely, and visit http://localhost:8080 or http://host-ip:8080 (as appropriate).How to extend this image
There are many ways to extend thepostgres image. Without trying to support every possible use case, here are just a few that we have found useful.Environment Variables
The PostgreSQL image uses several environment variables which are easy to miss. The only variable required isPOSTGRES_PASSWORD, the rest are optional.Warning: the Docker specific variables will only have an effect if you start the container with a data directory that is empty; any pre-existing database will be left untouched on container startup.
POSTGRES_PASSWORD
This environment variable is required for you to use the PostgreSQL image. It must not be empty or undefined. This environment variable sets the superuser password for PostgreSQL. The default superuser is defined by the POSTGRES_USER environment variable.Note 1: The PostgreSQL image sets up
trust authentication locally so you may notice a password is not required when connecting from localhost (inside the same container). However, a password will be required if connecting from a different host/container.Note 2: This variable defines the superuser password in the PostgreSQL instance, as set by the
initdb script during initial container startup. It has no effect on the PGPASSWORD environment variable that may be used by the psql client at runtime, as described at https://www.postgresql.org/docs/14/libpq-envars.html. PGPASSWORD, if used, will be specified as a separate environment variable.POSTGRES_USER
This optional environment variable is used in conjunction with POSTGRES_PASSWORD to set a user and its password. This variable will create the specified user with superuser power and a database with the same name. If it is not specified, then the default user of postgres will be used.Be aware that if this parameter is specified, PostgreSQL will still show
The files belonging to this database system will be owned by user "postgres" during initialization. This refers to the Linux system user (from /etc/passwd in the image) that the postgres daemon runs as, and as such is unrelated to the POSTGRES_USER option. See the section titled "Arbitrary --user Notes" for more details.POSTGRES_DB
This optional environment variable can be used to define a different name for the default database that is created when the image is first started. If it is not specified, then the value of POSTGRES_USER will be used.POSTGRES_INITDB_ARGS
This optional environment variable can be used to send arguments to postgres initdb. The value is a space separated string of arguments as postgres initdb would expect them. This is useful for adding functionality like data page checksums: -e POSTGRES_INITDB_ARGS="--data-checksums".POSTGRES_INITDB_WALDIR
This optional environment variable can be used to define another location for the Postgres transaction log. By default the transaction log is stored in a subdirectory of the main Postgres data folder (PGDATA). Sometimes it can be desireable to store the transaction log in a different directory which may be backed by storage with different performance or reliability characteristics.Note: on PostgreSQL 9.x, this variable is
POSTGRES_INITDB_XLOGDIR (reflecting the changed name of the --xlogdir flag to --waldir in PostgreSQL 10+).POSTGRES_HOST_AUTH_METHOD
This optional variable can be used to control the auth-method for host connections for all databases, all users, and all addresses. If unspecified then scram-sha-256 password authentication is used (in 14+; md5 in older releases). On an uninitialized database, this will populate pg_hba.conf via this approximate line:echo "host all all all $POSTGRES_HOST_AUTH_METHOD" >> pg_hba.confSee the PostgreSQL documentation on
pg_hba.conf for more information about possible values and their meanings.Note 1: It is not recommended to use
trust since it allows anyone to connect without a password, even if one is set (like via POSTGRES_PASSWORD). For more information see the PostgreSQL documentation on Trust Authentication.Note 2: If you set
POSTGRES_HOST_AUTH_METHOD to trust, then POSTGRES_PASSWORD is not required.Note 3: If you set this to an alternative value (such as
scram-sha-256), you might need additional POSTGRES_INITDB_ARGS for the database to initialize correctly (such as POSTGRES_INITDB_ARGS=--auth-host=scram-sha-256).PGDATA
Important Change: thePGDATAenvironment variable of the image was changed to be version specific in PostgreSQL 18 and above. For 18 it is/var/lib/postgresql/18/docker. Later versions will replace18with their respective major version (e.g.,/var/lib/postgresql/19/dockerfor PostgreSQL19.x). The definedVOLUMEwas changed in 18 and above to/var/lib/postgresql. Mounts and volumes should be targeted at the updated location. This will allow users upgrading between PostgreSQL major releases to use the faster--linkwhen runningpg_upgradeand mounting/var/lib/postgresql.
Users who wish to opt-in to this change on older releases can do so by setting
PGDATA explicitly (--env PGDATA=/var/lib/postgresql/17/docker --volume some-postgres:/var/lib/postgresql). To migrate pre-existing data, adjust the volume's folder structure appropriately first (moving all database files into a PG_MAJOR/docker subdirectory).Important Note: (for PostgreSQL 17 and below) Mount the data volume at/var/lib/postgresql/dataand not at/var/lib/postgresqlbecause mounts at the latter path WILL NOT PERSIST database data when the container is re-created. The Dockerfile that builds the image declares a volume at/var/lib/postgresql/dataand if no data volume is mounted at that path then the container runtime will automatically create an anonymous volume that is not reused across container re-creations. Data will be written to the anonymous volume rather than your intended data volume and won't persist when the container is deleted and re-created.
This (
PGDATA) is an environment variable that is not Docker specific. Because the variable is used by the postgres server binary (see the PostgreSQL docs), the entrypoint script takes it into account.Docker Secrets
As an alternative to passing sensitive information via environment variables,_FILE may be appended to some of the previously listed environment variables, causing the initialization script to load the values for those variables from files present in the container. In particular, this can be used to load passwords from Docker secrets stored in /run/secrets/<secret_name> files. For example:$ docker run --name some-postgres -e POSTGRES_PASSWORD_FILE=/run/secrets/postgres-passwd -d postgresCurrently, this is only supported for
POSTGRES_INITDB_ARGS, POSTGRES_PASSWORD, POSTGRES_USER, and POSTGRES_DB.Initialization scripts
If you would like to do additional initialization in an image derived from this one, add one or more*.sql, *.sql.gz, or *.sh scripts under /docker-entrypoint-initdb.d (creating the directory if necessary). After the entrypoint calls initdb to create the default postgres user and database, it will run any *.sql files, run any executable *.sh scripts, and source any non-executable *.sh scripts found in that directory to do further initialization before starting the service.Warning: scripts in
/docker-entrypoint-initdb.d are only run if you start the container with a data directory that is empty; any pre-existing database will be left untouched on container startup. One common problem is that if one of your /docker-entrypoint-initdb.d scripts fails (which will cause the entrypoint script to exit) and your orchestrator restarts the container with the already initialized data directory, it will not continue on with your scripts.For example, to add an additional user and database, add the following to
/docker-entrypoint-initdb.d/init-user-db.sh:#!/usr/bin/env bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
CREATE USER docker;
CREATE DATABASE docker;
GRANT ALL PRIVILEGES ON DATABASE docker TO docker;
EOSQLThese initialization files will be executed in sorted name order as defined by the current locale, which defaults to
en_US.utf8. Any *.sql files will be executed by POSTGRES_USER, which defaults to the postgres superuser. It is recommended that any psql commands that are run inside of a *.sh script be executed as POSTGRES_USER by using the --username "$POSTGRES_USER" flag. This user will be able to connect without a password due to the presence of trust authentication for Unix socket connections made inside the container.Additionally, as of docker-library/postgres#253, these initialization scripts are run as the
postgres user (or as the "semi-arbitrary user" specified with the --user flag to docker run; see the section titled "Arbitrary --user Notes" for more details). Also, as of docker-library/postgres#440, the temporary daemon started for these initialization scripts listens only on the Unix socket, so any psql usage should drop the hostname portion (see docker-library/postgres#474 (comment) for example).Database Configuration
There are many ways to set PostgreSQL server configuration. For information on what is available to configure, see the PostgreSQL docs for the specific version of PostgreSQL that you are running. Here are a few options for setting configuration:- Use a custom config file. Create a config file and get it into the container. If you need a starting place for your config file you can use the sample provided by PostgreSQL which is available in the container at
/usr/share/postgresql/postgresql.conf.sample(/usr/local/share/postgresql/postgresql.conf.samplein Alpine variants).
- **Important note:** you must set `listen_addresses = '*'`so that other containers will be able to access postgres.
```console
$ # get the default config
$ docker run -i --rm postgres cat /usr/share/postgresql/postgresql.conf.sample > my-postgres.conf
$ # customize the config
$ # run postgres with custom config
$ docker run -d --name some-postgres -v "$PWD/my-postgres.conf":/etc/postgresql/postgresql.conf -e POSTGRES_PASSWORD=mysecretpassword postgres -c 'config_file=/etc/postgresql/postgresql.conf'
```- Set options directly on the run line. The entrypoint script is made so that any options passed to the docker command will be passed along to the
postgresserver daemon. From the PostgreSQL docs we see that any option available in a.conffile can be set via-c.
```console
$ docker run -d --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword postgres -c shared_buffers=256MB -c max_connections=200
```Locale Customization
You can extend the Debian-based images with a simpleDockerfile to set a different locale. The following example will set the default locale to de_DE.utf8:FROM postgres:14.3
RUN localedef -i de_DE -c -f UTF-8 -A /usr/share/locale/locale.alias de_DE.UTF-8
ENV LANG de_DE.utf8Since database initialization only happens on container startup, this allows us to set the language before it is created.
Also of note, Alpine-based variants starting with Postgres 15 support ICU locales. Previous Postgres versions based on alpine do not support locales; see "Character sets and locale" in the musl documentation for more details.
You can set locales in the Alpine-based images with
POSTGRES_INITDB_ARGS to set a different locale. The following example will set the default locale for a newly initialized database to de_DE.utf8:$ docker run -d -e LANG=de_DE.utf8 -e POSTGRES_INITDB_ARGS="--locale-provider=icu --icu-locale=de-DE" -e POSTGRES_PASSWORD=mysecretpassword postgres:15-alpine Additional Extensions
When using the default (Debian-based) variants, installing additional extensions (such as PostGIS) should be as simple as installing the relevant packages (see github.com/postgis/docker-postgis for a concrete example).When using the Alpine variants, any postgres extension not listed in postgres-contrib will need to be compiled in your own image (again, see github.com/postgis/docker-postgis for a concrete example).
Arbitrary --user Notes
As of docker-library/postgres#253, this image supports running as a (mostly) arbitrary user via --user on docker run. As of docker-library/postgres#1018, this is also the case for the Alpine variants.The main caveat to note is that
postgres doesn't care what UID it runs as (as long as the owner of PGDATA matches), but initdb does care (and needs the user to exist in /etc/passwd):$ docker run -it --rm --user www-data -e POSTGRES_PASSWORD=mysecretpassword postgres
The files belonging to this database system will be owned by user "www-data".
...
$ docker run -it --rm --user 1000:1000 -e POSTGRES_PASSWORD=mysecretpassword postgres
initdb: could not look up effective user ID 1000: user does not existThe three easiest ways to get around this:
- allow the image to use the
nss_wrapperlibrary to "fake"/etc/passwdcontents for you (see docker-library/postgres#448 for more details)
...
Note: the description for this image is longer than the Hub length limit of 25000, so has been trimmed. The full description can be found at https://github.com/docker-library/docs/tree/master/postgres/README.md. See also docker/hub-feedback#238 and docker/roadmap#475.
Serve PostgreSQL on your own domain behind Caddy, Nginx or Traefik. Fill in your domain and copy the result. It's a starting point, some apps need their own base URL or extra headers set too.
Proxying postgresql.example.com to http://postgresql:5432
Add this to your Caddyfile
postgresql.example.com {
reverse_proxy http://postgresql:5432
}Check the logs first
Nine times out of ten the logs tell you exactly what went wrong.
- In Portainer, go to Containers, click the container, then Logs. Or run
docker logs postgresql - Exit codes help too:
137means killed, usually out of memory.126or127means the command inside the image is broken.
Port already in use
If deployment fails with "Bind for 0.0.0.0:5432 failed: port is already allocated", something else on your server is using that port.
- Find what's using it:
sudo ss -tlnp | grep :5432 - Stop the other service, or pick a different host port. In
5432:5432only the left number is yours to change, the right one belongs to the app.
Running but the page won't load
The container is up but nothing appears in your browser.
- Use your server's real IP:
http://your-server-ip:5432. The 0.0.0.0 link Portainer shows isn't a real address. - Give it a minute after first deploy, postgresql can take a while to initialise.
- Make sure your firewall allows the port, e.g.
sudo ufw allow 5432
Permission denied on volumes
If the logs show "permission denied", the app can't write to its data folder on the host.
- Fix the ownership:
sudo chown -R 1000:1000 /portainer/Files/AppData/Config/PostgreSQL - Or set the
PUIDandPGIDvariables (defaults 1000:1000) to match your own user, found withid $USER
Image won't pull
Test the pull directly on the host: docker pull postgres:latest
- "manifest unknown" means the tag no longer exists. This template uses
latest, so try pinning a specific version instead. - "toomanyrequests" is the Docker Hub rate limit. Log in with
docker loginto raise it. - "no space left on device" means a full disk. Reclaim space with
docker system prune
"exec format error"
This means the image was built for a different CPU architecture than your server.
- This image supports:
amd64, arm/v7, arm/v6, 386, ppc64le, s390x, riscv64, arm/v5, arm64/v8, mips64le - Check yours with
uname -m: x86_64 is amd64, aarch64 is arm64. Raspberry Pi and other ARM boards are the usual culprits.
Container keeps restarting
The unless-stopped restart policy relaunches the app after every crash, so the real error can scroll past.
- Check the logs right after a restart, the last few lines before it died are the useful ones.
- Get the exit code with
docker inspect postgresql --format '{{.State.ExitCode}}' - Still stuck? Redeploy once with the restart policy set to
noso the failure stays visible.
Raise an issue
Found something which isn't working as it should? Here's how to report it.
- Bug within the app: Open an issue within postgresql's repo
- Template not working: Open an issue on novaspirit/pi-hosted
- This website not working: Open an issue on lissy93/portainer-templates
A single container
PostgreSQL runs as one container, the simplest kind of app here. Just the one image to pull and nothing else wired up alongside it.
The app image
An image is the app packed up ready to go, everything PostgreSQL needs bundled into one download. This template pulls postgres:latest, which Docker fetches once (about 112 MB) and then starts your own copy from.
Where the image comes from
Docker pulls its images from registries, public libraries of ready-built apps. PostgreSQL's comes from Docker Hub as one of its official, curated images.
Version tags
The bit after the colon in the image name is the version tag. Here it's latest, which always points at the newest build, so a redeploy can bump you to a newer release without you asking. Newest right now is 17.11-alpine3.24. Pin a specific tag if you would rather stay on one version.
Which machines it runs on
Every image is built for particular CPU types. This one ships for amd64, arm/v7, arm/v6, 386, ppc64le, s390x, riscv64, arm/v5, arm64/v8, mips64le, so it runs on both regular x86 servers and ARM boards like a Raspberry Pi.
Ports
A port is the door the app answers on. A mapping like 5432:5432 means it's reachable on port 5432 of your server, where the left number is yours to change and the right one belongs to the app. It opens:
5432:5432
Volumes
A volume is where PostgreSQL keeps its files so they survive an update or a restart. Without one, anything it saves would sit inside the container and vanish the moment it's recreated. This template mounts:
/var/lib/postgresql/datafrom/portainer/Files/AppData/Config/PostgreSQLon the host
Environment variables
Environment variables are the settings you hand over when you deploy, things like a password or a timezone. PostgreSQL takes 4 of them, all with defaults you can leave alone or tweak:
PUID, defaults to1000PGID, defaults to1000POSTGRES_PASSWORD, defaults torootpasswordTZ, defaults toAmerica/New_York
Restart policy
The restart policy here is unless-stopped, so Docker restarts PostgreSQL after a crash or reboot, but leaves it off when you stop it on purpose. You can change this on the deploy screen. The choices are no (never restart), on-failure (only after a crash), unless-stopped (restart unless you stop it), and always (bring it back no matter what).
Users and permissions
The PUID and PGID settings tell it which user and group to act as on your host. Point them at your own account (find yours with id $USER) so the files it writes into your mounted folders come out owned by you rather than root.
Networking
Nothing custom is set, so PostgreSQL sits on Docker's default bridge network: its own private space that reaches the outside world only through the ports it publishes.
Container name
Once it's deployed, Portainer names the container postgresql. That's what you'll spot in the containers list and use in commands like docker logs postgresql.
Platform
The platform is linux, the kind of system the container is built to run on. Docker and Portainer handle this on a normal Linux server.
Portainer app templates
Zooming out, this whole page comes from a Portainer app template: a short recipe telling Portainer how to set PostgreSQL up. Add the template list to Portainer once, then deploying PostgreSQL is a click rather than a wall of config.