Docker Compose for a Local Postgres with an Initial Database

The following shows a simple process for getting a PostgreSQL database server up and running with Docker Compose on a local system.
This uses an init script to create an initial database on startup.
This is a fast and convenient way of having an isolated Postgres instance locally.

Make sure the docker daemon is up and running. For example, on macOS, that is part of Docker Desktop.

The example uses an Alpine Linux image for a minimal operating system for the server.

Note that the volume for data storage needs to be declared in the volumes section first.

The Docker Compose file brings everything together; the additional required files are presented first.

The initial database creation is handled with the init script below.

init.sql:
-- On initial load of the Postgres container.
CREATE DATABASE local_db;

The script will be run automatically when the container starts. By design, the SQL script in the special directory /docker-entrypoint-initdb.d is read and executed.

The environment used is stored in .env in the current directory.

The env file looks like this:

POSTGRES_USER=postgres
POSTGRES_PASSWORD=password
POSTGRES_PORT=5432

These values will be read in the Docker Compose file and are referred to as, for example, “${POSTGRES_PASSWORD}”.
The values from the environment will be used when creating the database server.
Note that the port value is given a default of 5432 in the Docker Compose file.

The complete Docker Compose file is below:

docker-compose.yml:
version: "3.8"

volumes:
  pg_data:

services:
  local_postgres:
    image: postgres:18.0-alpine
    restart: always
    environment:
      POSTGRES_USER: "${POSTGRES_USER}"
      POSTGRES_PASSWORD: "${POSTGRES_PASSWORD}"
    volumes:
      - pg_data:/var/lib/postgresql/data
      - ./db/init.sql:/docker-entrypoint-initdb.d/init.sql
    ports:
      - "${POSTGRES_PORT}:5432"

Now we can run Docker Compose to create an image based on this file.

The flag “-d” means daemon, i.e. to run in the background and not block the terminal shell.

Start the server with:

$ docker-compose up -d
Creating network "local-dir_default" with the default driver
Creating local-dir_local_postgres_1 ... done

To see the server running, list running services with:

$ docker ps

This will show the Container ID and other details. The server should run on the default Postgres port of 5432.

We can access the server with the command line Postgres client as usual (or any other preferred database client):

$ psql -h localhost -U postgres

Confirm that the database local_db exists with \l (list databases).

We can shut down the server with:

$ docker-compose down

Note that this will only stop the server defined in this current Docker Compose file.

If another, different docker-compose file has started some other server, that file must be used to shut down that server.