How to set Postgres admin password during a Docker container build

We have a web app using postgresql DB, being deployed to tomcat on CentOS7 env. We are using docker (and docker-compose), and running on an Azure visual machine.

We cannot pre-set the admin user ‘postgres’ password (e.g. mysecret) during the docker/docker-compoase build process.

We have tried to use the environments: setting from the docker-compose.yml file, also the ENV in the ./portgres Dockerfile file. Neither works.

I had to manually use ‘docker exec -it /bin/bash’ to run the psql command to set the password. We like to avoid the manual step.

$ cat docker-compose.yml

version: '0.2'
services: 
  app-web: 
     build: ./tomcat
     ports:
     -  "80:80"
     links:
     - app-db

  app-db:
    build: ./postgres
    environment:
      - "POSTGRES_PASSWORD=password"
      - "PGPASSWORD=password"
    expose:
      - "5432"

$ cat postgres/Dockerfile

FROM centos:7
RUN yum -y install https://download.postgresql.org/pub/repos/yum/9.6/redhat/rhel-6-x86_64/pgdg-centos96-9.6-3.noarch.rpm
RUN yum -y install postgresql96 postgresql96-server postgresql96-libs postgresql96-contrib postgresql96-devel

RUN yum -y install initscripts
USER postgres
ENV POSTGRES_PASSWORD=mysecret
ENV PGPASSWORD=mysecret
RUN /usr/pgsql-9.6/bin/initdb /var/lib/pgsql/9.6/data

RUN echo "listen_addresses = '*'" >> /var/lib/pgsql/9.6/data/postgresql.conf
RUN echo "PORT = 5432" >> /var/lib/pgsql/9.6/data/postgresql.conf
RUN echo "local   all             all                                     trust" > /var/lib/pgsql/9.6/data/pg_hba.conf
RUN echo "host    all             all             127.0.0.1/32            trust" >> /var/lib/pgsql/9.6/data/pg_hba.conf
RUN echo "host    all             all             ::1/128                 ident" >> /var/lib/pgsql/9.6/data/pg_hba.conf
RUN echo "host    all             all         0.0.0.0/0            md5" >> /var/lib/pgsql/9.6/data/pg_hba.conf

EXPOSE 5432
ENTRYPOINT ["/usr/pgsql-9.6/bin/postgres","-D","/var/lib/pgsql/9.6/data","-p","5432"]

Web app deployment fails, db authentication error with wrong password (the password ‘mysecret’ is defined in the web app JPA persistence.xml). Assuming the password was not properly set (default initdb does not set the password)
Then, manually change the password using the above mentioned docker exec command, everything works.

Like to set the password during the docker build time. Based on Postgres/Docker documentation and some threads, either environments: from docker-compose setting or ENV from the docker file would work. Neither works for us.

Source: StackOverflow