Automating Postgres and pgvector Setup with Docker

pgvector adds vector similarity search to PostgreSQL, so you can keep embeddings next to the rest of your application data and query both with ordinary SQL. Running it in Docker gives you the same database on every machine, with nothing to compile and nothing to install on your laptop beyond Docker itself.

This guide sets up PostgreSQL 18 with pgvector 0.8 using Docker Compose, creates a table and an HNSW index automatically on first start, and shows a working similarity search from SQL and from Python. Every file and command below was tested end to end.

Why pgvector instead of a separate vector database?

  • One database to run. Embeddings live in the same tables as your users, products or documents, so there’s no second system to deploy, back up and keep in sync.
  • Plain SQL. You can filter, join and paginate vector results with the SQL you already know, inside normal transactions.
  • Good enough for most projects. With an HNSW index, pgvector handles millions of vectors comfortably. A dedicated vector database starts to pay off mainly at very large scale or with very high query rates.

What you need

Docker with the Compose plugin (Docker Desktop includes both), and optionally Python 3 if you want to try the client example. The project is three files:

pgvector-demo/
├── compose.yaml
├── .env
└── init/
    └── 01-vector.sql

Step 1: the Compose file

The pgvector project publishes official images with the extension already built in, so there’s no need for your own Dockerfile. Create compose.yaml:

services:
  db:
    image: pgvector/pgvector:0.8.7-pg18
    container_name: pgvector-db
    environment:
      POSTGRES_USER: ${POSTGRES_USER:-app}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?set POSTGRES_PASSWORD in .env}
      POSTGRES_DB: ${POSTGRES_DB:-vectors}
    ports:
      - "127.0.0.1:5454:5432"
    volumes:
      - pgdata:/var/lib/postgresql
      - ./init:/docker-entrypoint-initdb.d:ro
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER} -d $${POSTGRES_DB}"]
      interval: 5s
      timeout: 3s
      retries: 10
    restart: unless-stopped

volumes:
  pgdata:

A few choices here are deliberate:

  • A pinned image tag. 0.8.7-pg18 fixes both the pgvector and PostgreSQL versions, so a rebuild next month gives you the same database. Tags such as pg17 or pg16 are available if you need to match an existing server.
  • The port is bound to 127.0.0.1. The database is reachable from your machine on port 5454 but not from the rest of your network. Using 5454 rather than 5432 avoids clashing with a PostgreSQL you may already have installed.
  • The volume is mounted at /var/lib/postgresql. From PostgreSQL 18, the official images keep data in a version-specific folder under this path. Older guides mount /var/lib/postgresql/data, which is right for PostgreSQL 17 and earlier but not for 18.
  • A health check. It lets docker compose up --wait (and any app containers that depend on the database) wait until PostgreSQL is actually accepting connections. The doubled $$ stops Compose from substituting the variables itself, so the shell inside the container does it.
  • The password is required. The :? syntax makes Compose stop with a clear message if POSTGRES_PASSWORD isn’t set, instead of starting with an empty one.

Step 2: the environment file

Compose reads .env from the same folder automatically. Put your local credentials there and add .env to .gitignore so they never reach your repository:

POSTGRES_USER=app
POSTGRES_PASSWORD=change-me-locally
POSTGRES_DB=vectors

Step 3: enable the extension on first start

Installing pgvector in the image isn’t quite enough: each database has to enable it with CREATE EXTENSION. The PostgreSQL image runs any .sql files in /docker-entrypoint-initdb.d, in name order, the first time it creates the database. Create init/01-vector.sql:

CREATE EXTENSION IF NOT EXISTS vector;

CREATE TABLE IF NOT EXISTS documents (
    id        bigserial PRIMARY KEY,
    content   text NOT NULL,
    embedding vector(3) NOT NULL
);

CREATE INDEX IF NOT EXISTS documents_embedding_idx
    ON documents USING hnsw (embedding vector_cosine_ops);

The vector(3) column holds three-dimensional vectors to keep the example readable. In a real project, use the size your embedding model produces, for example vector(1536) for OpenAI’s text-embedding-3-small or vector(768) for Nomic Embed. The index uses vector_cosine_ops because most text embedding models are compared by cosine distance.

pgvector doesn’t need to be added to shared_preload_libraries. CREATE EXTENSION is all it takes.

Step 4: start the database and check it

docker compose up -d --wait

--wait returns once the health check passes. Then confirm the extension is enabled:

docker compose exec db psql -U app -d vectors -c "SELECT extversion FROM pg_extension WHERE extname = 'vector';"
 extversion
------------
 0.8.7
(1 row)

To connect from a GUI client such as DBeaver, TablePlus or pgAdmin, use host localhost, port 5454 and the user, password and database from .env.

Step 5: store and search vectors in SQL

Open a SQL session with docker compose exec db psql -U app -d vectors, add three rows and ask for the two nearest to a query vector:

INSERT INTO documents (content, embedding) VALUES
    ('cats are small pets',      '[0.9, 0.1, 0.0]'),
    ('dogs love long walks',     '[0.8, 0.3, 0.1]'),
    ('stock markets fell today', '[0.0, 0.2, 0.9]');

SELECT content,
       round((embedding <=> '[0.85, 0.2, 0.05]')::numeric, 4) AS cosine_distance
FROM documents
ORDER BY embedding <=> '[0.85, 0.2, 0.05]'
LIMIT 2;
       content        | cosine_distance
----------------------+-----------------
 cats are small pets  |          0.0089
 dogs love long walks |          0.0098
(2 rows)

The two pet sentences come back and the finance one doesn’t, because their vectors point in a similar direction to the query. pgvector’s main distance operators are:

OperatorDistanceIndex operator class
<->Euclidean (L2)vector_l2_ops
<=>Cosinevector_cosine_ops
<#>Negative inner productvector_ip_ops

Use the same distance in your queries as in your index, otherwise PostgreSQL can’t use the index. You can check with EXPLAIN: the plan should show Index Scan using documents_embedding_idx. On a table this small PostgreSQL will prefer a plain scan anyway, which is expected; the index matters once you have thousands of rows.

Step 6: query from Python

The pgvector Python package adds vector support to the common PostgreSQL drivers. With psycopg 3:

pip install "psycopg[binary]" pgvector numpy
import os

import numpy as np
import psycopg
from pgvector.psycopg import register_vector

conn = psycopg.connect(
    host="localhost",
    port=5454,
    dbname="vectors",
    user="app",
    password=os.environ["POSTGRES_PASSWORD"],
)
register_vector(conn)

query = np.array([0.85, 0.2, 0.05])
rows = conn.execute(
    "SELECT content, embedding <=> %s AS distance "
    "FROM documents ORDER BY distance LIMIT 2",
    (query,),
).fetchall()

for content, distance in rows:
    print(f"{distance:.4f}  {content}")
0.0089  cats are small pets
0.0098  dogs love long walks

register_vector teaches the driver to send NumPy arrays as vectors and read vectors back as arrays. In a real application the query vector comes from the same embedding model you used for the stored rows.

HNSW or IVFFlat?

Without an index, pgvector compares the query with every row: exact, but slow on big tables. Its two approximate indexes trade a little accuracy for a lot of speed:

HNSWIVFFlat
Query speed and recallBetterGood, depends on tuning
Build time and memorySlower, uses more memoryFaster, uses less memory
Can be created on an empty tableYesNo: build it after loading data, because it learns clusters from existing rows
Main tuning settinghnsw.ef_searchivfflat.probes

HNSW is the sensible default, which is why the init script creates one. Consider IVFFlat when you load a large, mostly static dataset in one go and index build time or memory is the constraint.

Do you still need a custom Dockerfile?

Earlier versions of this guide built pgvector from source on top of the official PostgreSQL image. That still works, but it means installing a compiler, cloning the repository and keeping the build in step with your PostgreSQL version. The pgvector/pgvector images do that for you. Build your own image only if you need other extensions in the same container; in that case, start FROM pgvector/pgvector:0.8.7-pg18 and add what you need.

Troubleshooting

  • The init script didn’t run. Scripts in /docker-entrypoint-initdb.d only run when the data volume is empty. If you change them later, apply the change by hand with psql, or recreate the database as described below.
  • The port is already in use. Change the left-hand port in 127.0.0.1:5454:5432 to any free port and connect to that instead.
  • The container exits after upgrading to a PostgreSQL 18 image. Check the volume path. PostgreSQL 18 images expect the volume at /var/lib/postgresql. Data from an older major version can’t be opened by a newer one either: upgrade it with pg_dump and restore, or with pg_upgrade.
  • “expected N dimensions” errors. Every vector in a column must have the size declared in vector(N). If you switch embedding models, create a new column or table with the new size and re-embed your data.

Stopping and resetting

docker compose stop       # stop, keep the data
docker compose down       # remove the container, keep the data
docker compose down -v    # remove the container AND delete the data volume

Use down -v only when you really want a fresh database, for example to rerun the init scripts. It permanently deletes everything stored in it.

Next steps

With the database running, the next step is producing real embeddings to store in it. My comparison of Nomic and OpenAI embeddings covers choosing a model, and EmbeddingGemma 2 is a small open model you can run locally.

Further reading

Leave A comment

Are you human? Please solve:Captcha