We’ve used in-memory databases in a few chapters, stating that nobody will ever use this kind of data storage in a real-world scenario for a few reasons: (1) when the server restarts, all data is lost, and (2) there are clever people out there dedicating time and energy to creating data storage systems and giving access to their work for free.
In this section, we’ll use the example from chapter 10, our gRPC habits tracker, to show the first steps of how to connect to a database. We’ll use PostgreSQL since it’s a popular choice.
G.1 Setup
Before we can connect to a database, it needs to be running and listening to requests. Rather than installing a database on our local machine, we can use a containerized version via Docker.
G.1.1 Starting a PostgreSQL database locally
Make sure that docker
is installed on your machine and that you have the proper rights to use it. Pull the latest image available for PostgresSQL:
> docker pull postgres
Then, run it with a handful of arguments.
Listing G.1 Starting a local PostgresSQL instance
> docker run \ --name postgres-habits \ -p 5455:5432 \ #1 -e POSTGRES_USER=user \ -e POSTGRES_PASSWORD=*** \ #2 -e POSTGRES_DB=habits-tracker \ -d \ #3 postgres
Using your favorite client (pgAdmin is a free UI-based tool, and psql
is a command-line tool) or even a plugin of your IDE if it has one, connect to your new instance using this URL: