I just started using Docker and created an image and running container with Python3, Flask, UWSGI and nginx.
Now I want to use a postgresql database in Flask. I read the following page and linking containers seems logical to me. (https://hub.docker.com/_/postgres/)
I still have some question or maybe the principle of Docker isn't just clear enough for me. But if I create a postgresql image and running container, and link this to my Flask application, what happens if:
- I rebuild the image or restart the container, where does my database data go? Is it gone?
- I want to use my database in my Flask (Docker) application, what do I need to put in my config? (DATABASE_URI, NAME etc..)
- I want to back-up my database, or load data in it? Can I just connect to it?
As you may have noticed I am clearly a beginner of working with Docker, maybe I'm just misunderstanding the principle. Really appreciate it if someone could point me in the right direction!
I rebuild the image or restart the container, where does my database data go? Is it gone?
- No, the data is not gone. The only time data is removed is if you remove the container:
docker rm <my postgres container>
. The only time this isn't true is if you mount a volume to the container to expose the data volume: docker run -td -p 5432:5432 -v /mydata/volume:/var/lib/postgresql/data postgres:9.5.2
I want to use my database in my Flask (Docker) application, what do I need to put in my config? (DATABASE_URI, NAME etc..)
- This can be a subject of debate but I would use an environment variable that you set when you start the container:
docker run -td -p 80:5000 -e POSTGRES_URL=172.12.20.1 mycontainer/flask:latest
In your config you would go os.getenv('POSTGRES_URL', 'localhost')
. This allows you to default to localhost if the container is linked otherwise you can point it to another container running on another machine. This is better because it allows greater flexibility in your deployment.
I want to back-up my database, or load data in it? Can I just connect to it?
- Yes, just like anything else you can connect to Postgres on
IP:PORT
using the credentials you specified at container runtime.