How to setup Nginx as a reverse proxy for Django in Docker?
I'm trying to setup nginx as a reverse proxy for Django in docker so I can password prompt users that don't have a specific IP. However I can't get it to work.
I have a Django app with a postgreSQL database all set up and working in Docker. I also have a Nginx container I just can't see to get the two connected? I haven't used Nginx before.
The closest I have got is seeing the welcome to Nginx page at localhost:1337 and seeing the Django admin at localhost:1337/admin but I get a CSRF error when I actually try and login.
Any help would be much appreciated!
I have tried setting up Nginx in Docker using the following files:
Here's my docker-compose.yml file:
services:
web:
build: .
command: gunicorn config.wsgi -b 0.0.0.0:8000
environment:
- SECRET_KEY=django-insecure-^+v=tpcw8e+aq1zc(j-1qf5%w*z^a-5*zfjeb!jxy(t=zv*bdg
- ENVIRONMENT=development
- DEBUG=True
volumes:
- .:/code
- static_volume:/code/staticfiles
expose:
- 8000
depends_on:
- db
networks:
- my-test-network
db:
image: postgres
volumes:
- postgres_data:/var/lib/postgresql/data/
nginx:
build: ./nginx
ports:
- "1337:80"
volumes:
- static_volume:/code/staticfiles
depends_on:
- web
networks:
- my-test-network
volumes:
postgres_data:
static_volume:
networks:
my-test-network:
driver: bridge
Here's my dockerfile for Nginx:
FROM nginx:1.25
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d
Here's my Nginx config file:
upstream hello_django {
server pk-portal-web-1:8000;
}
server {
listen 80;
location / {
proxy_pass http://hello_django;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
}
location /static/ {
alias /code/staticfiles/;
}
}
Here's my main dockerfile for the rest of the application as well:
# Pull base image
FROM python:3.10
# Set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
# Set work directory
WORKDIR /code
# Install dependencies
COPY Pipfile Pipfile.lock /code/
RUN pip install pipenv && pipenv install --system
# Copy project
COPY . /code/
CSRF error
This error occurs when the settings related to the proxy are not done correctly and for this reason the requests sent to Django are marked as unauthorized requests. To fix this problem, you need to enter the following code in the settings.py file
USE_X_FORWARDED_HOST = True
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
ALLOWED_HOSTS = ['*']
Connecting Nginx and Django
In the nginx.conf file, you have set the Django service name as pk-portal-web-1. But this service name must exactly match the Django service name in docker-compose.yml.
Setting up a reverse proxy
Make sure Nginx is properly configured to forward requests to Django. Also make sure the static routes are set correctly