I'm new to Docker and I'm trying to get a Django app working in a Docker container. This app needs a PostgreSQL database (and redis).
In order to try that, I created an image (Dockerfile) for my app, and used the basic postgres
image for the database server. My docker-compose file looks like:
version: '3.7'
services:
db:
image: postgres
redis:
image: redis
api:
build: .
command: python3 manage.py runserver 0.0.0.0:8000
environment:
- DJANGO_SETTINGS_MODULE=api.settings.docker_settings
volumes:
- ./api:/code/api
ports:
- "8000:8000"
depends_on:
- db
- redis
As my docker-compose file does not define any volume for the database, I expected the database data to be lost when the container is stopped, but it's not! That is, if I run docker-compose up
, add data to the db, stop docker-compose and start it again, the data is still there!
Is a volume automatically created by Docker? (I noticed a VOLUME
command in the Dockerfile of the postgres
image, see here).
Now I would like to add a volume to docker-compose to store the database somewhere I can control. How can I do that? I thought I should change the docker-compose file to
...
db:
image: postgres
volumes:
- ./postgres_data:/var/lib/postgresql/data
...
but how can I tell Docker to not use the previous data that has been automatically persisted?
You should distinguish between container's stop and container's removal.
First occurs when main process in container stops execution (probably because you manually sent stop signal). In this case container is still available and could be restarted with all data persisted in it. This is what happens in your example.
Second occurs when you explicitly remove the container. It can be done with special command or with removal argument (like docker run --rm ...
) applied on start. In this case container's data is lost.
docker-compose
by default does not delete containers and restarts them. To change the behavior, simply use docker-compose up --force-recreate ...
and you will get virgin containers on each startup.