PostgreSQL Tutorial: Install PostgreSQL using Docker

October 19, 2026

Summary: in this tutorial, you will learn how to install PostgreSQL on Linux using Docker.

Table of Contents

Install PostgreSQL using Docker

To run PostgreSQL using Docker, pull the official PostgreSQL image from Docker Hub and start a container with environment variables set for access credentials.

Pull the Official PostgreSQL Image

Fetch the latest official PostgreSQL image (or specify a version tag like postgres:18 or postgres:18.6-trixie):

docker pull postgres

Run the PostgreSQL Container

Start the container using docker run. You must set the mandatory POSTGRES_PASSWORD environment variable.

docker run --name my-postgres \
  -e POSTGRES_PASSWORD=mysecretpassword \
  -p 5432:5432 \
  -d postgres
  • --name my-postgres: Names the container.
  • -e POSTGRES_PASSWORD=...: Sets the default superuser password for the postgres user.
  • -p 5432:5432: Maps host port 5432 to container port 5432.
  • -d: Runs the container in detached (background) mode.

Verify PostgreSQL status

Check the status of your container:

docker ps -a

You can also view the database logs to verify it is ready to accept connections:

docker logs my-postgres

Connect to PostgreSQL

Access the database prompt inside the running container via psql:

docker exec -it my-postgres psql -U postgres

Alternatively, connect using any external database client (like psql, DBeaver, or pgAdmin) pointing to localhost:5432 with user postgres and password mysecretpassword.

Persistent Data Storage

By default, data written inside a Docker container is deleted if the container is removed. To keep your database storage persistent across container restarts or removals, you can attach a Docker volume.

Create a Docker volume:

docker volume create pgdata

Start a container using the Docker volume:

docker run --name my-postgres \
  -e POSTGRES_PASSWORD=mysecretpassword \
  -v pgdata:/var/lib/postgresql \
  -p 5432:5432 \
  -d postgres

Using Docker Compose

For local development environments, create a docker-compose.yml file:

version: '3.8'

services:
  postgres:
    image: postgres:18
    container_name: postgres-db
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: mysecretpassword
      POSTGRES_DB: mydatabase
    ports:
      - "5432:5432"
    volumes:
      - pgdata:/var/lib/postgresql
    restart: always

volumes:
  pgdata:

Start the service with:

docker compose up -d

Stopping the container

If using Docker CLI, to stop the container:

docker stop my-postgres

If using Docker Compose, to stop the container:

docker compose down

Conclusion

By following these steps, you have set up a robust local development environment for PostgreSQL using Docker. This setup ensures data persistence and provides a flexible, isolated, and consistent environment for all of your development needs.