My setup for dockerizing & serving the Django app is a bit different when it comes to Nginx so the solutions I found didn’t help.
I have dockerized the django app and its working fine except the media files. I am not using nginx inside the container but on the actual server. All the requests even static files are served perfectly except media files.
Here is settings for static and media:
STATIC_ROOT = os.path.join(BASE_DIR, 'static_cdn')
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media_cdn')
MEDIA_URL = '/media/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
Here is my docker-compose file:
version: "3"
services:
backend:
image: gitrepo:latest
#image: 731d5d7e9296
ports:
- 8400:8000
links:
- database
command: bash -c "python manage.py migrate
&& python manage.py collectstatic --noinput
&& python manage.py runserver 0.0.0.0:8000"
volumes:
- media-cdn-data:/app/media_cdn
deploy:
restart_policy:
condition: on-failure
tty: true
database:
image: "postgres:12" # use latest official postgres version
env_file:
- database.env # configure postgres
volumes:
- database-data:/var/lib/postgresql/data/ # persist data even if container shuts down
volumes:
database-data: # named volumes can be managed easier using docker-compose
media-cdn-data:
This is my nginx file:
server {
server_name app.platformname.com;
location /media/ {
proxy_pass http://127.0.0.1:8400/;
alias /app/media_cdn/;
}
location / {
proxy_pass http://127.0.0.1:8400/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_read_timeout 3600;
proxy_set_header Connection '';
# these two lines here
proxy_http_version 1.1;
}
}
Any help is appreciated,I have been struggling with it for the past 4 days 🙂
2
Answers
Also i don’t see you have any
nginx
block in your docker-compose file. YourYou have try this way both in your backend section and reverse proxy section
and in the nginx file add this:
Note: Please update your
docker-compose
file for nginx/reverse proxy similar to thisWhy do you have to map with local physical machine instead of the container? coz, you will get permission denied error if you don’t map with local machine to container
This is minimal example how to do this in few steps.
Configure your nginx.conf to serve media files directory such this:
Then you must configure your docker-compose.yml file to locate nginx to your project media directory path like so:
Now your nginx should see your media files directory.
E.g. your project contains files:
Supposing your Django project is configured right (in your settings.py and urls.py media files serving is enabled).
Now you should get your media file by media file URL.