Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Persistent Django's PostgreSQL database in Docker

I am learning Django by trying to create the polling app described on the Django's website. At the same time, I am using Docker for the first time and I have encountered problems trying to make PostgreSQL database, used by this app, persistent.

Following the tips on using Docker with Django, found on the Docker website, I am running two services with docker-compose: one handling the database and the other the app itself (at least that's how I understand it). I have tried mounting a volume at the /var/lib directory inside the database container, where I found PostgreSQL directory. Although this directory became persistent, which I checked by creating some dummy files, migrations done via the web service are being erased every time I restart those containers.

Below are my docker-copmpose.yml file and Django's settings.py. What should I do to make this database persistent?

#docker-compose.yml
version: '3'

services:
  db:
    image: postgres
    environment:
      - POSTGRES_DB=postgres
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
    volumes:
      - .:/code
      - .:/var/lib
  web:
    build: .
    command: python manage.py runserver 0.0.0.0:8000
    volumes:
      - .:/code
    ports:
      - "8000:8000"
    depends_on:
      - db
#(...)
# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql',
        'NAME': 'postgres',
        'USER': 'postgres',
        'PASSWORD': 'postgres',
        'HOST': 'db',
        'PORT': 5432,
    }
}
#(...)
like image 661
TheRlee Avatar asked Jan 28 '26 20:01

TheRlee


1 Answers

The data persistance in docker can be tricky but here are 2 possible solutions :

  1. Don't worry, docker will handle it. In your case, since you are usinng a compose file, as long as you do not clean your volumes and that you stop your docker compose with a 'docker-compose down' there should be no issues. Once you will use a 'docker-compose up' your data should still be on the database.
  2. You want more control (and maybe share easely the data). In that case you can choose to manualy mount a file in which your data will be stored. For that you can learn more here (at the bottom of the page). Tips :volumes: - /my/own/datadir:/var/lib/postgresql/data

I hope that aswer your question :)

like image 151
Pacifuras Avatar answered Jan 31 '26 13:01

Pacifuras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!