I was pleasantly surprised at how quickly I was able to set up a Postgres database, and wanted to share my steps.

Prerequisites

This assumes you have Docker Compose already installed. It comes with the official Docker Desktop software.

You can check by running docker-compose version in your terminal.

Setup

1. Create this YAML file somewhere on your computer.

File name matters! compose.yml is one of the names that is automatically recognized by Docker Compose.

compose.yml

version: '3.1'

services:
  db:
    image: postgres
    ports:
      - 5432:5432
    environment:
      POSTGRES_USER: postgres
      POSTGRES_PASSWORD: password

You can find more details on customizing this YAML file by looking at the official Postgres Docker page.

2. Make sure Docker is running in the background.

Look out for that cute whale icon in your system tray. 🐳

(If it’s not there, you can run the Docker Desktop software to start Docker.)

3. Start up the database with Docker Compose.

cd <your_folder_name> # Go to where the file is
docker-compose up

The first time you run this, the Postgres Docker container automatically calls some start-up scripts. But don’t be intimidated by the amount of logs - no further action is needed. The database should just start running in the background.

4. Connecting to Postgres

Now for the most exciting part - connecting to the database!

I was looking for a way to make this a bit easier, and decided to try out Beekeeper Studio. I like how it supports multiple SQL languages, and looked fairly modern. But that being said, I can’t speak to the experience of actually using it. Functionally, of course, it works.

Here’s a video of me connecting to the database and running a query.

Postgres runs on port 5432 by default, and you can use the username and password you specified in the YAML file. Once you’re connected, you can start running queries!

Sample Queries

Here are some sample queries to get you started.

-- Create a table
CREATE TABLE todo_list (
   id   INT  PRIMARY KEY  NOT NULL,
   task TEXT              NOT NULL
);

-- Insert data
INSERT INTO todo_list (id, task) 
VALUES 
(1, 'Live'), 
(2, 'Laugh'), 
(3, 'Love'), 
(4, 'Meme');

-- Retrieve data
SELECT * FROM todo_list;

Stopping Postgres

To stop running Postgres, you can press CTRL-C in the terminal window where you started the database.

Alternatively, run docker-compose down from a new terminal window. Same idea as step 3, just with a different command.

The actual data in the database should be preserved across starts/stops. (A good thing!)

Clean Install

If you do want a fresh Postgres database, without any of your current tables, you can always delete the corresponding Docker container.

Then the next time you run docker-compose up, you’ll get a brand new instance of Postgres.

Docker Desktop makes things a bit easier. You can see the stop and delete buttons on the right.

Final (Unrelated) Thoughts

It’s December 31st right now - have a great 2022 everyone :)