如何使用Docker清除Django的缓存?

时间:2019-03-07 14:37:04

标签: python django docker docker-compose memcached

我有一个与memcached和Docker一起使用的Django项目。在开发中使用sudo docker-compose up时,我希望清除整个缓存。除了在开发模式下禁用批量批发缓存之外,还有一种方法可以在cache.clear()的每次重新运行上运行this question中所述的sudo docker-compose up

我不确定是否应该输入:

  1. docker-entrypoint.sh
  2. Dockerfile
  3. docker-compose.yml
  4. 还有其他地方吗?

docker-compose.yml:

version: "3"
services:
  redis:
    image: "redis:alpine"
    command: "redis-server --requirepass ${REDISPASS} --bind 0.0.0.0"
    ports:
      - '6379:6379'
  memcached:
    image: "memcached:latest"
    ports:
      - '11211:11211'
  nginx:
      image: nginx:latest
      volumes:
        - ./configuration/nginx/conf.d/:/etc/nginx/conf.d
        - ./configuration/nginx/realtime:/etc/nginx/realtime
        - ./static_cdn/static_root/static:/static
      ports:
        - 80:80
        - 443:443      
      depends_on:
        - app_main
        - app_async_app1
        - app_async_app2
  app_main:
      command: "djangoAppName.settings.prod ${SECRET_KEY} 1 ${DB_PASS}     ${REDISPASS}"      
      image: "django_image_name"
      ports:
        - 0003:0003
      volumes:
        - ./static_cdn/static_root/:/static_cdn/
      depends_on:
        - redis
        - memcached
 app_async_app2:
      command: "djangoAppName.settings.prod ${SECRET_KEY} 2 ${DB_PASS} ${REDISPASS}"      
      image: "django_image_name"
      ports:
        - 0002:0002
      depends_on:
        - redis
        - memcached
        - app_main
  app_async_app1:
      command: "djangoAppName.settings.prod ${SECRET_KEY} 3 ${DB_PASS} ${REDISPASS}"    
      image: "django_image_name"
      depends_on:
        - redis
        - memcached
        - app_main
      ports:
        - 0001:0001
  react:
      command: "npm run"
      image: "django_image_name"
      volumes:
        - ./static_cdn/static_root/:/static_cdn/
      depends_on:
        - memcached
        - app_main

1 个答案:

答案 0 :(得分:2)

根据this answer,您可以添加在清除缓存的内存缓存服务之前执行的服务。看起来您正在使用Linux Alpine,可以将此服务添加到docker-compose.yml

clearcache:
    command: [sh, -c, "python manage.py clear_cache"] 

,然后添加到memcached

memcached:
    ...
    depends_on:
     - clearcache

还有一个示例,该示例在同一命令中执行此操作,而不依赖于单独的服务(尽管我个人不喜欢这样做)。

对于缓存清除命令,this answer有一些有用的讨论和帖子。

clear_cache.py:

from django.core.management.base import BaseCommand
from django.core.cache import cache

class Command(BaseCommand):
    def handle(self, *args, **kwargs):
        cache.clear()
        self.stdout.write('Cleared cache\n')