Docker/postgres – simplest solution to accessing psql without a password?

Solution for Docker/postgres – simplest solution to accessing psql without a password?
is Given Below:

I have a docker container that holds postgres with postgis and I am trying to set it up so i can use psql without passing a password everytime. I’ve set up docker-compose.yaml with a dockerfile and everything runs, but how would I modify this in order to allow me to execute psql commands without having to pass a password everytime?

docker-compose.yaml

version: '3'

services:
  
  pgclient:
    container_name: pg_client
    build: ./
    restart: always
    environment:
        POSTGRES_USER: docker
        POSTGRES_PASSWORD: docker
        POSTGRES_DB: test_db
    volumes:
        - ./data:/var/lib/postgresql/
        - ./raw_data:/raw_data
        - ./postgres_init:/postgres_init
    ports:
        - 5434:5434
    networks:
        - ch_ntw

networks:
  ch_ntw:
    driver: bridge
    ipam:
      config:
        - subnet: 10.222.1.0/24

Dockerfile

FROM postgres:12.4

RUN apt-get update 
    && apt-get install wget -y 
    && apt-get install postgresql-12-postgis-3 -y 
    && apt-get install postgis -y


COPY ./db.sql /docker-entrypoint-initdb.d/
COPY ./ /

ADD import_trips.sh /import_trips.sh
RUN chmod +x import_trips.sh

Once the container build I run:

docker exec -it pg_client bash

And then I run something like this:

psql --host=pg_client --dbname=test_db --username=docker -f postgres_init/create_schema.sql

And I have to pass the password. How can I grant superuser rights?

Two ways that come to mind right away –

  • create the passwordless user in your init script (db.sql) or
  • use POSTGRES_HOST_AUTH_METHOD: trust env key-value instead of POSTGRES_PASSWORD (but please do understand the implications).