Install and connect PostgreSQL with Docker container

Consider installing Docker and running PostgreSql from a docker container. PostgreSql is an object-relational database management system. It has gotten a lot of use lately. As always Docker helps us out and we have a ready instance of the desired Datebase in a couple of minutes.

Docker documentation. PostgreSql documentation.


Docker PostgreSQL Mac OS

It is necessary to execute:
– Installing Docker on MacOs;
– Deploying a PostgreSQL image;
– Create Database/Tables/Test records;
– Establish a connection to the database;

Installation and the first steps of Docker described earlier: here. In short, you need to have an account at Docker Hub, download and install the app: Docker Desktop, log in through the terminal.

When Docker is installed and ready to go, prepare a PostgreSql image.

To save data when restarting the container with our database image, it is necessary to create a volume

docker volume create --name vol_1
docker volume ls
CAB-WSM-0001037:~ ttt$ docker volume ls
local               d67ec8a59da03121046c25a5fd7454417f3d2009d2125a39e4eae1106a7bdcc5
local               vol_1

create – create a new volume
–name – key “volume name”

ls – returns all Docker volumes

docker run --rm --name postgresql-save -e POSTGRES_PASSWORD=mypassword 
-d -p 5400:5432 -v vol_1:/var/lib/postgresql/data postgres
docker container ls
CONTAINER ID        IMAGE                COMMAND                  CREATED             STATUS              PORTS                    NAMES
51a711b63bfd        postgres             "docker-entrypoint.s…"   About an hour ago   Up About an hour>5432/tcp   postgresql-save
d755f0eb4ba2        thajeztah/pgadmin4   "python ./usr/local/…"   About an hour ago   Up About an hour>5050/tcp   dreamy_lamarr

run – running a Docker container
–rm – automatically removes the container if it already exists
–name postgresql-save – set up name
-e POSTGRES_PASSWORD=mypassword – password for DB
-d – backgraound process without locking the command line in the terminal
-p 5400:5432 – set up out port
-v vol_1:/var/lib/postgresql/data – storage of data during content restarts
postgres – the name of the Docker image. You can specify the version

Stop the container

docker container stop postgresql-save

To connect and work with PostgreSql, you can install the pgAdmin graphical client directly from Docker:

docker run --rm -p 5050:5050 thajeztah/pgadmin4
NOTE: Configuring authentication for DESKTOP mode.
pgAdmin 4 - Application Initialisation
Starting pgAdmin 4. Please navigate to in your browser.

IP on MacOs terminal:

ipconfig getifaddr en0

You can now connect to PostgreSql.


PyCharm with Database plugin

Now, after stopping the content, just start again. All data will be saved.

docker container stop postgresql-save
docker run --rm --name postgresql-save -e POSTGRES_PASSWORD=mypassword 
-d -p 5400:5432 -v vol_1:/var/lib/postgresql/data postgres

Releated Post