skip to Main Content

I am learning docker and postgresql and I have problem with persisting data between the re-runs of the app.

My docker-compose.yml:

version: '3.7'

services:
  web:
    build: .
    command: python3 /code/manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - 8000:8000
    depends_on:
      - db
  db:
    image: postgres:15
    volumes:
      - postgres_data:/var/lib/postgresql/data
    environment:
      POSTGRES_PASSWORD: postgres
    ports:
      - "5432:5432"

volumes:
  postgres_data:
    external: true

I run my project with docker-compose up -d go with docker-compose exec web python3 manage.py migrate but after I go docker-compose down and I run the containers I have to migrate again. It’s really bothersome. Can someone help, please?

2

Answers


  1. The issue you’re experiencing is due to the fact that your database data is not persisting between runs of your Docker containers. This is happening because the volume where PostgreSQL stores its data is deleted when you run the command docker-compose‍‍ down.

    The docker-compose down command stops and removes containers, networks, and, crucially, volumes defined in your docker-compose.yml file. Since your PostgreSQL data is stored in a volume, when you run docker-compose down, this data is deleted.

    To keep your PostgreSQL data between runs, you should use the docker-compose down command with the --volumes or -v flag. This will preserve your volumes, and thus your PostgreSQL data, between runs. Your command should look like this: docker-compose down --volumes.

    Alternatively, you should use the command docker-compose stop when you want to stop your Docker containers without deleting your volumes. When you’re ready to run your containers again, you can use the command docker-compose start.

    By either preserving your volumes with docker-compose down --volumes or stopping your containers with docker-compose stop, your PostgreSQL data will persist between runs, saving you from having to migrate your database every time you

    Login or Signup to reply.
  2. volumes:
      postgres_data:
        external: true
    

    Do you know what is does? As far as I know if you create a volume with command: docker volume create you can reference it in your compose. So if you don’t know its usage this is what causing the problem. As I guess you didn’t create a volume.
    So for it to work properly just remove line external: true and let docker do the management of your volume. And as long as you don’t use docker compose down --volumes your data persists.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search