It seems to me that to this date this problem has not yet been solved!
The solution I found to not lose database data was to create a docker volume and add in the postgres image settings.
My docker-compose.yml:
version: '3'
services:
postgres:
container_name: postgres
restart: always
build:
context: ./postgres
dockerfile: Dockerfile
volumes:
- pgdata:/var/lib/postgresql/data
ports:
- "5432:5432"
environment:
- POSTGRES_USER=${POSTGRES_USER}
- POSTGRES_PASSWORD=${POSTGRES_PASS}
networks:
- code-network
networks:
code-network:
driver: bridge
volumes:
pgdata:
external: true
Before mounting the containers, you must create the volume manually:
docker volume create --name=pgdata