I'm trying to create a simple docker application that saves data to a simple database
app.py
docker-compose.yml
Dockerfile
requirements.txt
db/
db.txt
tmp.txt
app.py
import datetime
import os
from flask import Flask
app = Flask(__name__)
BASE_FOLDER = os.path.dirname(os.path.abspath(__file__))
RESOURCE_DIR = os.path.join(BASE_FOLDER, "db")
@app.route("/")
def hello_world():
with open(os.path.join(RESOURCE_DIR, "db.txt"), "a ") as f:
date = datetime.datetime.now().strftime("%d.%m.%Y %H:%M:%S")
f.write(f" {date}\n")
data_f = f.read()
return {
"date": date,
"os": os.listdir(),
"os_db": os.listdir("./db"),
"db.txt": data_f,
"hmmm": "hmmm",
}
if __name__ == "__main__":
app.run(host="0.0.0.0", port=8080, debug=True)
docker-compose.yml
version: "3.9"
services:
web:
build: .
ports:
- "8080:8080"
volumes:
- db:/app/db
volumes:
db:
Dockerfile
FROM python:3.10.4
WORKDIR /app
COPY . .
RUN pip install --no-cache-dir -r requirements.txt
CMD ["python","app.py"]
requerements.txt
-i https://pypi.org/simple
click==8.1.3; python_version >= '3.7'
colorama==0.4.4; platform_system == 'Windows'
flask==2.1.2
itsdangerous==2.1.2; python_version >= '3.7'
jinja2==3.1.2; python_version >= '3.7'
markupsafe==2.1.1; python_version >= '3.7'
werkzeug==2.1.2; python_version >= '3.7'
db.txt have some data and I would like that docker-compose run added simple data in this db, but it don't work idk why .. what's I doing wrong?
abc abc 123
some dasdas
das aaa
CodePudding user response:
Change your volumes to: ./db:/app/db
, notice the ./
In your compose file db
is a named volumes, docker will create an empty volume somewhere and bind it. Using the ./
will tell docker that this is a relative path in the current directory, and mount your db
folder to /app/db
.
This should be sufficient for your use case.
Read more: