[英]Python script to add data to postgres docker container runs multiple times
I'm trying to find a good way to populate a database with initial data for a simple application. 我正在尝试寻找一种很好的方法来用简单应用程序的初始数据填充数据库。 I'm using a tutorial from realpython.com as a starting point. 我使用realpython.com的教程作为起点。 I then run a simple python script after the database is created to add a single entry, but when I do this the data is added multiple times even though I only call the script once. 然后,在创建数据库以添加单个条目之后,我运行一个简单的python脚本,但是当我这样做时,即使我只调用一次脚本 ,数据也会被多次添加。 result 结果
population script (test.py): 填充脚本(test.py):
from app import db
from models import *
t = Post("Hello 3")
db.session.add(t)
db.session.commit()
edit: 编辑:
Here is the docker-compose file which i use to build the project: 这是我用来构建项目的docker-compose文件:
web:
restart: always
build: ./web
expose:
- "8000"
links:
- postgres:postgres
volumes:
- /usr/src/app/static
env_file: .env
command: /usr/local/bin/gunicorn -w 2 -b :8000 app:app
nginx:
restart: always
build: ./nginx/
ports:
- "80:80"
volumes:
- /www/static
volumes_from:
- web
links:
- web:web
data:
restart: always
image: postgres:latest
volumes:
- /var/lib/postgresql
command: "true"
postgres:
restart: always
image: postgres:latest
volumes_from:
- data
ports:
- "5432:5432"
it references two different Dockerfiles: 它引用了两个不同的Dockerfile:
Dockerfile #1 which builds the App container and is 1 line: Dockerfile#1构建App容器,为1行:
FROM python:3.4-onbuild
Dockerfile #2 is used to build the nginx container Dockerfile#2用于构建Nginx容器
FROM tutum/nginx
RUN rm /etc/nginx/sites-enabled/default
ADD sites-enabled/ /etc/nginx/sites-enabled
edit2: EDIT2:
Some people have suggested that the data was persisting over several runs, and that was my initial thought as well. 有人建议数据在多个运行中都存在,这也是我最初的想法。 This is not the case, as I remove all active docker containers via docker rm before testing. 情况并非如此,因为我在测试之前通过docker rm删除了所有活动的Docker容器。 Also the number of "extra" data is not consistent, ranging randomly from 3-6 in the few tests that I have run so far. 同样,“额外”数据的数量也不一致,到目前为止,在我进行的一些测试中,随机数据的范围是3-6。
It turns out this is a bug related to using the run command on containers with the "restart: always" instruction in the docker-compose/Dockerfile. 事实证明,这是与在docker-compose / Dockerfile中使用“ restart:always”指令对容器使用run命令有关的错误。 In order to resolve this issue without a bug fix I removed the "restart: always" from the web container. 为了解决此问题而没有错误修复,我从Web容器中删除了“重新启动:始终”。
related issue: https://github.com/docker/compose/issues/1013 相关问题: https : //github.com/docker/compose/issues/1013
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.