Install PostgreSQL server using Docker

In this tutorial, I will show you how to install PostgreSQL server using Docker!

We will use the docker run command to run a PostgreSQL Docker Image on Docker Hub https://hub.docker.com/_/postgres as follows:

Inside:

  • — name <container_name> is the Docker container name that you want to set to the PostgreSQL server’s container.
  • -e POSTGRES_USER=<postgre_user> declares the environment variable POSTGRES_USER, which is the username we will use to log into the PostgreSQL server. This parameter is optional, if you do not declare it, by default, the user with the username “postgres” will be used.
  • -e POSTGRES_PASSWORD=<postgre_password> is the password to login with the username above. This parameter is mandatory.
  • -v <mount_folder>:/var/lib/postgresql/data helps us mount a directory on the running Docker machine (host) with the /var/lib/postgresql/data directory of the PostgreSQL server in Docker container, allowing us to synchronize the data of the PostgreSQL server in the container to the running Docker machine (host), in case our Docker Container has any problem, we can run it again without losing data.
  • -d is the parameter that helps us run the command in the background, so we can continue the container when shutting down Terminal or Ctrl+C.
  • postgres:<tag> is the Docker Image tag of the PostgreSQL server you want to run.

You can define an environment variable POSTGRES_DB to define the default database name that will be created when the container runs. By default, this database name will have the same value as the login user’s name.

For example, I run the command as follows:

The result is as follows:

Install PostgreSQL server using Docker

Check the Docker container is running, you will see the following results:

Install PostgreSQL server using Docker

Now you can use pgAdmin or a PostgreSQL client tool to connect to this PostgreSQL server and use it.

Add Comment