Creating a postgres Docker container with Extensions
In my previous post i outlined how to run Docker in rootless mode on Ubuntu. Once we have that out of the way and we have Docker installed, in this post I’ll show you how to create a container with the latest postgresql version (At the time of writing postgres 18) running with a few extensions installed.
Postgresql Official images for Docker
The steps outlined below, composes a new local docker image from the latest postgres image available in the docker hub, and runs a container based on the new image.
First I create a directory to hold my Docker compose files. All of the following steps are run as the non-root user we installed Docker with.
mkdir ~/Apps/docker/pg/pg1
cd ~/Apps/docker/pg/pg1
Create a file Named Dockerfile and add the following lines to it. Here we are specifying that docker use the image tagged postgres:latest (This will be the latest generally available version of postgres which is 18 at the time of writing), and install the packages postgresql-contrib (Gets you all the extensions that are contrib modules) and pgvector.
FROM postgres:latest
# Update package lists
RUN apt-get update
# Install PostgreSQL extensions
RUN apt-get install -y --no-install-recommends \
postgresql-contrib \
postgresql-18-pgvector
Create a file named docker-compose.yml and add the following lines to it.Here we give the container a name postgres_db and specify postgres startup parameter that set the extension names that will be preloaded upon postgres startup.
services:
postgres:
container_name: postgres_db
# Build a custom image from the local Dockerfile
build: .
ports:
- "5432:5432"
# Preload required libraries at startup (comma-separated if multiple)
command: >
postgres
-c shared_preload_libraries='pg_stat_statements,vector'
Run the following command to compose the new image from the base image postgres:latest. This simply builds a new image and does not create a container or start it.
docker compose build
Run the following command to list the image we just created and note down the imageid (We will use it in the next step to run the container using this image)
docker image ls -a
Run the following command to run a container based on the image we just built. Replace the username, password and database name in the command below with your choices. Replace 27e3aca52506 with the image id we gathered up from the previous step.
docker run -d -p 5432:5432 --name pg1local -e POSTGRES_PASSWORD=pg1pwd -e POSTGRES_USER=pg1user -e POSTGRES_DB=pg1db 27e3aca52506 -c shared_preload_libraries='pg_stat_statements,vector'
Now you can go ahead and access the database using psql. Once you login create the extensions.
psql -h localhost -d pg1db -U pg1user
psql> create extension pg_stat_statements;
psql> create extension vector;