skip to Main Content

I am trying to save the data of python app in redis but when I stop the docker-compose file the data is removed and when I again run the docker-compose file it starts from the start. I want to save the data of the container and whenever it starts it starts from where it left when the container exited. For example when I exited the container it shows Hello World! I have been seen b'6' times. and when i restart the container it should start from Hello World! I have been seen b'6' times.

version: "3.7"

services:
  nginx_app:
    image: nginx:latest
    depends_on:
      - flask_app
    volumes:
      - ./default.conf:/etc/nginx/conf.d/default.conf
    ports:
      - 8082:80
    networks:
      - my_project_network

  flask_app:
    build:
      context: .
      dockerfile: Dockerfile
    expose:
      - 5000
    depends_on:
      - redis_app
    networks:
      - my_project_network

  redis_app:
    image: redis:latest
    command: redis-server --requirepass 1234
    volumes:
      - ./redis-vol:/data
    expose:
      - 6379
    networks:
      - my_project_network

networks:
  my_project_network:
    external: true

python file:

from flask import Flask
from redis import Redis
app = Flask(__name__)
redis = Redis(host='redis_app', port=6379, password='123a')
@app.route('/')
def hello():
    redis.incr('hits')
    return 'Hello World! I have been seen %s times.' % redis.get('hits')
if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)

2

Answers


  1. You need to add a volume to your redis service.

    As I remember, the internal path for this redis image is /data. Just mount this volume in your docker-compose.

    Do not forget to add --appendonly yes to your redis command.

    Login or Signup to reply.
  2. If you read the documentation on "volumes", you will find:

    https://kubernetes.io/docs/concepts/storage/volumes/

    A Kubernetes volume, on the other hand, has an explicit lifetime – the same as the Pod that encloses it. Consequently, a volume outlives any Containers that run within the Pod, and data is preserved across Container restarts. Of course, when a Pod ceases to exist, the volume will cease to exist, too. Perhaps more importantly than this, Kubernetes supports many types of volumes, and a Pod can use any number of them simultaneously.

    https://kubernetes.io/docs/concepts/storage/persistent-volumes/

    IN short, you need to change to persistent volumes.

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