How to install PostgreSQL with docker

We pull the latest version of PostgreSQL :

sudo docker pull postgres

We run PostgreSQL :

sudo docker run --name pg-docker -e POSTGRES_PASSWORD=postgres1+ -d postgres

And we verify if everything goes well :

$ sudo docker ps

gives

CONTAINER ID   IMAGE     COMMAND                  CREATED             STATUS             PORTS     NAMES
00ab12a6f24d   postgres  "docker-entrypoint.s…"   About an hour ago   Up About an hour   5432/tcp  pg-docker

and

$ sudo docker images

gives

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
postgres            latest              f9b577fb1ed6        3 weeks ago         311MB
hello-world         latest              4ab4c602aa5e        3 months ago        1.84kB

and now we connect to PostgreSQL with psql :

sudo docker run -it --rm --link pg-docker:postgres postgres psql -h postgres -U postgres

and we obtain :

Password for user postgres: 
psql (11.1 (Debian 11.1-1.pgdg90+1))
Type "help" for help.

postgres=# 

It works !

That’s lovely but… If we insert data in the database, they will be lost when the container will be stopped. To implement persistence, we will use volumes.

We can now remove the image of hello-world

 $ sudo docker rmi hello-world -f

and then

sudo docker images

gives

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
postgres            latest              f9b577fb1ed6        3 weeks ago         311MB