Running a Postgres server on Docker

Randy Payano
2 min readJun 10, 2021

Through this article, you will get a Postgres server in a Docker container up and running, expose that server to the outside World and use it from a Jupyter Notebook.

Before getting started, you need to download Docker for your OS, create an account and log in.

For this experiment, we will be using Visual Studio Code. You will need to open a new terminal window and work from there.

  1. To begin, we will pull your preferred Postgres image, and in this example we will use the latest available.

Docker pull postgres:latest

We can confirm our image has been downloaded by typing

Docker Images

2. Now it’s time to run our Postgres image. I will name it randydb-postgres, and for the password I will use “chosenpass.” Lastly, I want to expose my server to PORT 5432 in order to access it from outside the container.

Docker run — name randydb-postgres -e POSTGRES_PASSWORD=chosenpass -d -p 5432:5432 postgres

You can see our running images by typing the command

Docker ps

3. To go inside our container from our terminal use the following command:

Docker exec -it randydb-postgres bash

4. To directly access Postgres use this command:

psql -U postgres

You can get a list of all commands by typing \h

You can quit postgres by typing \q

5. We can finally create our Database and start querying it.

CREATE DATABASE chosen_dbname

To confirm the creation of our DB you can type \l and see a list of all databases.

6. Switch into your new database with the following command

\c chosen_dbname

You are now connected to database “chosen_dbname” as user “postgres”

From there you can change user credentials, make changes to your database, etc.

The last step is to connect from the outside such as a Jupyter Notebook.

I will be using the psycogpg2 library which you can install by running:

!pip install psycogpg2 in your Notebook

# Create a connection to your server

conn = psycopg2.connect(“host=127.0.0.1 dbname=chosen_dbname user=postgres password=chosenpass”)

# Get your cursor to the connection and query away!

cur = conn.cursor()

Congratulations, you just created your first dockerized server!

--

--