DEV Community

pyderator
pyderator

Posted on

How to use POSTGRESQL image container in your next project ?

Using docker is a life saver for each and every developer out there, for development as well as production purpose. The main reason for this is that it scales and spins up in milliseconds.

PostgreSQL is one of the popular database out there. Many of the developers use it in daily purpose because of its efficiency and simplicity.

To create a container of PostgreSQL, first we must download its image from the docker hub ( official docker images repository ).

You can find the link for PostgreSQL here.

Here, we can use download the latest docker image by using the latest tag. You can checkout others too in the link above.

To install the image locally in our system, we use the following command:

docker pull postgres:latest
Enter fullscreen mode Exit fullscreen mode

After this, we can spin our PostgreSQL image and create a new container.

For this, we use the following command,

docker
docker run --name name_of_your_container -e POSTGRES_USER=username_for_the_container -e POSTGRES_PASSWORD=password_for_the_container -e _containerized -p 5432:5432 --mount type=volume,source=pgdata,destination=/var/lib/postgresql -d postgres
Enter fullscreen mode Exit fullscreen mode

😱 😱 Don't be panic, I will explain each and every line.

Here, docker run commands docker to create an container of the given name --name with some environment variables ( key and value pair "=" )-e. Currently we are using three of them, and there are more which you can use according to your need.

  1. POSTGRES_USER: Creates a postgres user of provided name for the container followed by POSTGRES_PASSWORD.
  2. POSTGRES_PASSWORD: Sets the password for the user.

As PostgreSQL runs on port 5432, the -p maps the port 5432 of the container to our local port 5432 so that we can access it easily.

To have persistent data we create a volume and map to it.
Here --mount type=volume,source=pgdata,destination=/var/lib/postgresql, we mounted our volume and mapped the data of PostgreSQL of our container with the volume we created i.e. pgdata.

At last, we now tell docker to run it in detach mode (-d) following by the name of image i.e postgres.

Top comments (0)