How To Install and Run PostgreSQL using Docker ?
Tags: docker, postgres, psql, pgadmin
Published: 2020-09-14 06:33:21


Installing, running and managing postgres in local-machine for development is not difficult anymore. Here is a simple way to get all at one place easily installed and configured within seconds with the help of docker.

Now skip all complex steps in installing and configuring PSQL to get started with local development and GUI to manage the DB. It's now easy to kick-start development of postgres based applications in a few seconds. <br>
**NOTE**: This is to make the development process easy and however follow the [conventional method of installing PSQL](https://www.postgresql.org/download/) individually for production environment.

After following the instructions below, you will get the following installed in your machine:
1. Postgres server running as a docker-container (which can be accessed by CLI, GUI or other application for development).
2. Postgres container accessible through CLI.
3. PgAdmin4 browser version to access Postgres server from GUI.

**Prerequisite:**
1. Install [docker](https://docs.docker.com/get-docker/)
2. … nothing else  :)
 
## Install and Configure PSQL using Docker: ##
Run the below command in linux or windows or mac machine from the terminal or command-prompt to pull PSQL from docker-hub. <br>
`docker run --name postgresql-container -p 5432:5432 -e POSTGRES_PASSWORD=somePassword -d postgres` <br>
In the above command replace : <br>
* Optional - _postgresql-container_ with a preferable container name if necessary.
* _somePassword_ with a password to authenticate and connect to the postgres (in application with connection string as well as the PG-admin viewer).

Verify a new container created and running at 0.0.0.0:5432 with the below command.
`docker ps -a`

![psql_install](https://dev-to-uploads.s3.amazonaws.com/i/591edoh1j3a4w46r4fho.jpg)

The PostgresQL is ready to connect and use. <br>
**The postgres server is now running in the IP of your local machine in 5432.** <br>

## Install PG-admin using Docker: ##
Download the pgAdmin-4 browser version from docker-hub using the following command. <br>
`docker run --rm -p 5050:5050 thajeztah/pgadmin4` <br>

Now manage your postgres from the browser by launching http://localhost:5050 . <br>
![pg_admin_install](https://dev-to-uploads.s3.amazonaws.com/i/phdp5tcq1133yrroub35.jpg)

### To connect the PSQL server in pgAdmin: ###

![pg_admin_1](https://dev-to-uploads.s3.amazonaws.com/i/ve6sxo3tmrt8vmka5zj8.jpg)
<br>

Enter the credentials to save and manage PSQL via GUI.
**Host**  - The IP address of your machine
**Password** - Password used while creating the PSQL server with docker <br>

![pg_admin_cred](https://dev-to-uploads.s3.amazonaws.com/i/j2o3s9dso6zme6u8jo31.jpg)

## Connecting to the PSQL server via CLI : ##
The steps below are to connect to the psql server from CLI : <br>
1. Find the docker-container-id in which the postgres is running using the below command.  
 `docker ps -a` 
2. Run the below command to enter into the container (with the ID from step-1).  
 `docker exec -it <PSQL-Container-ID> bash`
3. Authenticate to start using as postgres user.  
 `psql -h localhost -p 5432 -U postgres -W`
4. Enter the password used while creating the PSQL server container.

![psql_cli](https://dev-to-uploads.s3.amazonaws.com/i/w1udkxuydja2qtdsu09l.jpg)

## Connecting to the PSQL server via application : ##
(example: JavaScript) 

```javascript
const { Client } = require('pg');

let client = new Client({
  connectionString: "postgresql://postgres:test1234@192.168.225.86:5432/postgres"
});

const connectDB = async () => {
  try {
    console.log('Connect to Postgres ...');
    client.connect();
    await new Promise((resol, rej) => {
      client.query('Select now() as run_at;', (err, res) => {
        if(err) {
          console.log(err);
          reject(err);
        } else {
          console.log(`Run at date-time : ${res.rows[0].run_at}`);
          resol(res.rows[0].run_at);
        }
      })
    });
    await client.end();
    console.log('Execution Completed ...');
  } catch (err) {
    console.log('Error while Connecting DB !')
  }
}

connectDB();
```