skip to Main Content

I want to create two Docker volumes and have their data be persistent. I run sudo docker compose up -d, post some data to my website (text that is stores in a sqlite database and an image stored in the filesystem), then run sudo docker compose down. When I run sudo docker compose up -d again, all the data I posted is gone. With the following configs, I expect the data to still be present.

Dockerfile:

FROM python:3.9.16-buster

RUN pip install --upgrade pip

# The Debian/Buster default is to disable the password.
RUN adduser nonroot

RUN mkdir /home/site/ && chown -R nonroot:nonroot /home/site

RUN chown -R nonroot:nonroot /var/log/site

# two volumes created
VOLUME /home/site/db /home/site/static

WORKDIR /home/site
USER nonroot

# folders ./site/static and ./site/db exist in my host directory
COPY --chown=nonroot:nonroot . .

CMD ["python", "./site/main.py"]

compose.yaml:

services:
  site:
    build: flask
    restart: always
    ports: 
      - '8081:8081'
    volumes:
      - site_db:/home/site/db # same path as the volumes created in the Dockerfile
      - site_static:/home/site/static
    command: gunicorn -w 1 -t 3 -b 0.0.0.0:8081 --chdir ./site main:app
volumes:
  site_db: # I find it odd these volumes keys don't have values, but that's what I have see other people do
  site_static:

docker compose up and docker compose down delete my volumes.

docker compose start and docker compose stop do NOT delete my volumes.

2

Answers


  1. Chosen as BEST ANSWER

    Through the Flask app, check where you are uploading the files to, as well as where the sqlite3 db file is. If these paths do not align with the volumes paths, data will not persist.


  2. What worked for me is creating a volume that contains the database (sqlite3 in my case) so when you do compose down it does not get flushed, something like this should work:

    version: '3'
    
    services:
      app:
        build: ./app
        container_name: app
        volumes:
          - data_base:/app/
    
      nginx:
        container_name: nginx
        image: nginx:latest
        volumes:
          - ./nginx.conf:/etc/nginx/nginx.conf:ro
        depends_on:
          - app
        ports:
          - "xxxx:xxxx"
      
    volumes:
      data_base:
    

    In the example above we create a volume (data_base) at the directory where the db is contained.

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