Django app with docker-compose keep the data in media volume
Asked Answered
A

3

11

I'm using Django cookiecutter with docker and docker-compose.

On production I'm using dj-static to serve my media files.

Whenever I use 'docker-compose down' command everything that is in my media volume gets deleted. I think this is the expected outcome of that command but everything that is in 'postgreSQL' is kept.

How can I do that with the 'media' volume?

Ayannaaycock answered 11/7, 2017 at 13:2 Comment(0)
A
6

I've managed to make this work.

In the docker-compose.yml I've added:

volumes:
  media: {}

django:
  ....
  volumes:
    - media:/app/project-name/same-path-as-MEDIA_URL

In the compose/django Dockerfile I've added:

VOLUME /app/PROJECT_NAME/same-path-as-MEDIA_URL

After this changes I've run docker-compose build, docker-compose up and got a 500 error. To pass this (if you haven't modified django cookiecutter's default settings):

docker ps - here you'll get your django container id

docker exec -u root THE_CONTAINER_ID chown django:user PROJECT_NAME/same-path-as-MEDIA_URL
Ayannaaycock answered 12/7, 2017 at 10:3 Comment(0)
W
3

You should include additional volume to preserve your mediafiles folder:

- /path/to/store/on/host:/path/to/mediafiles
Whooper answered 11/7, 2017 at 14:24 Comment(2)
Where should that go? On the .yml file under 'django' service?Ayannaaycock
yes, in docker-compose.yml, in django/volumes sectionWhooper
R
2

Leaving a compose file here. I am persisting the DB, media and elastic search data. This should be useful for those who have a hard time figuring where to place what the current answers here give.

version: '3.3'

services:
  # elastic search service
  elasticsearch:
    image: elasticsearch:6.5.4
    ports:
      - '9400:9200'
    volumes:
      - elastic-data:/usr/share/elasticsearch/data
  # Postgres database service
  postgres:
    image: postgres:9.6-alpine
    environment:
      POSTGRES_DB: dilirena
      POSTGRES_USER: dilirenauser
      POSTGRES_PASSWORD: pa55w0rd
    ports:
      - '5435:5432'
    volumes:
      - postgres-data:/var/lib/postgresql/data

  # drf restful api service
  api:
    build: .
    command: python manage.py runserver 0.0.0.0:8081
    volumes:
      - .:/app
      - media:<media-path>
    ports:
      - '8081:8081'
    env_file:
      - ./.env
    links:
      - postgres
      - elasticsearch

    depends_on:
      - postgres
      - elasticsearch

volumes:
  elastic-data:
  postgres-data:
  media:

I am on mac, not sure if it makes a difference.

Rash answered 6/6, 2019 at 10:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.