I am using Django as a Web Framework. Azure NGINEX as WebServer. My Project is deployed with Docker Containers.
In my Django project root structure will be as follows:
root:
- app1
- app2
- media
whenever saving images, it will correctly save under media folder. But whenever doing "docker-compose up" it will replaces the source code, so that my media folder will be cleaned up everytime.
In my settings.py file, I have added as follows:
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = 'media/'
Kindly help me to maintain the media files with Docker based Environment
As mentioned in the previous answer, this isn't a best practice to handle media and static inside your project or app directory rather you can use a file or file storage server. But I am trying to give the answer to your question here.
Suppose you have a Django project directory named root
and inside this, you are managing the media
and static
folders. As you are using Docker
every time your container gets restarted, it wipes out the contents from both these folders. So what you have to do here is mount your media
and static
folders from inside of your container to your local storage i.e /var/lib/docker/volumes/{volume_name}/_data
to persist your media and static files in between restarts of your container.
I am describing here the docker-compose
version:
version: "3.8"
services:
app:
image: {your django project image}
#build: {direct build of your Dockerfile}
volumes:
- media:/src/media/
- static:/src/static/
volumes:
media:
static:
My goal here is to point out volume mount
, so in the above code, you have to define volumes this way, where /src
is the working directory defined in your Dockerfile
using the WORKDIR
directive. And in my case media and static
are the direct children of the src
folder. Now you can run docker volume ls
to see your volume names and using the name you can inspect your volumes using this command docker volume inspect {volume_name}
. Usually, you will find your volumes i.e media and static here -
/var/lib/docker/volumes/{{container_name]_media}/_data
/var/lib/docker/volumes/{{container_name]_static}/_data
Hope this clears the question.
You have to basically do 2 things:
docker-compose
configuration file to persist your media directory. You can find the detailed documentation on the way to configure volumes in docker-compose
here.If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With