Local Postgres Database, using Docker April 18, 2019
Installation
Run the following docker command:
docker run --name postgresDb -e POSTGRES_PASSWORD=postgres -d -p 5432:5432 -v postgresDbData:/var/lib/postgresql/data postgres
Where:
--namewill name the containerpostgresDb-pwill expose port5432to the host machine-vwill create a volume namedpostgresDbData, so the database data will persist between uses
For more information, read docker run --help
Usage
The Docker container running the database can be used the same way as any other instance of a Postgres database. This means you can connect to it using PgAdmin or any other database access tool, such as DBeaver.
Postgres connection strings are formatted like so: jdbc:postgresql://<host>:<port>/<database>. The driver's class name is org.postgresql.Driver. The table below contains the default connection information.
| Parameter | Value |
|---|---|
| Connection string | jdbc:postgresql://localhost:5432/postgres |
| Host | localhost |
| Port | 5432 |
| Database | postgres |
| User | postgres |
| Password | postgres |
Maintenance
Connecting using psql
To connect using psql, simply run the following docker command:
> docker exec -ti postgresDb psql -U postgres
psql (11.2 (Debian 11.2-1.pgdg90+1))
Type "help" for help.
postgres=# ...
postgres=# exit
Where:
-tiallows to type in an interactive shell-Uprovides the user using psql
For more information, read docker exec --help
Adding a new user and database
To add a new user and database, start by connecting to the container using psql, then simply run the following commands:
postgres=# create user <user> with password '<password>';
postgres=# create database <database> owner <user>;
postgres=# exit
Tailing the logs
To tail the logs, simply run the following docker command:
docker logs -f postgresDb --tail 500
Where:
-fwill keep following the logs in real time--tailwill show the last 500 lines of log
For more information, read docker logs --help
Docker Cheatsheet
Last updated on August 7, 2019
— Etienne Lamoureux