'docker-compose.yml for Postgres works either way, but not the expected one

I have the following docker-compose.yml for running Postgres with Docker:

version: '3.8'

services:
  postgres:
    image: postgres:14.2-alpine
    environment:
      POSTGRES_USER: ${POSTGRES_USER:-postgres}
      POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres}
      POSTGRES_DB: mydatabasename
      PGDATA: /data/mydatabasename
    volumes:
      - postgres:/data/postgres
    ports:
      - '5432:5432'
    networks:
      - postgres
    restart: unless-stopped

  pgadmin:
    ... placeholder

networks:
  postgres:
    driver: bridge

volumes:
  postgres:
  pgadmin:

It works. What I don't understand, is that these two combinations work:

      PGDATA: /data/mydatabasename
    volumes:
      - postgres:/data/postgres

and

      PGDATA: /data/postgres
    volumes:
      - postgres:/data/mydatabasename

But this does not work:

      PGDATA: /data/mydatabasename
    volumes:
      - postgres:/data/mydatabasename

I would just get: error: database "mydatabasename" does not exist.

The latter was my first attempt connecting everything though. So I am wondering, why do both fields not map to the actual database name? Thanks for your help!



Solution 1:[1]

Docker Compose File

version: '3'

services:
  postgres:
    image: postgres:alpine
    container_name: postgres
    restart: always
    posts:
      - 5432:5432
    volumes:
      - ./data_backup:/var/lib/postgresql/data #mount the data locally 
    env_file:
      - .env
    networks:
      - postgres-net 

  pgadmin:
    image: dpage/pgadmin4:6
    restart: always
    ports:
      - 8080:80
    volumes:
      - pgadmin:/var/lib/pgadmin
    env_file:
      - .env
    depends_on:
      - postgres  
    netwroks:
      - postgres-net  


networks:
  postgres-net:
  name: postgres-net

.env File

#postgres
POSTGRES_PASSWORD="secure_password"
POSTGRES_DB=your_db_name
POSTGRES_USER=db_user_name
#pgadmin
[email protected]
PGADMIN_DEFAULT_PASSWORD="secure_password"
PGADMIN_LISTEN_PORT=80

Since you may try to bind the database folder which was never created. Alternatively you can bind /var/lib/postgresql/data this path to store whatever database you created or about create in future.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Emi OB