minnymauer
minnymauer

Reputation: 374

502 nginx can't connect to gunicorn server

I am so lost as to what is going wrong.

I have nginx & gunicorn running in separate docker containers. Nginx is running on port 80 forwarding to gunicorn on 8000. I get 502 errors from nginx. If I hit port 8000 I get a 200 response from my gunicorn server.

If I take down the nginx docker and start a nginx server on my laptop forwarding traffic to port 8000, everything works fine. Would could be going wrong with the dockerized nginx server setup?

docker-compose.yml

version: '3.3'
services:
  nginx:
    build: ./nginx
    ports:
      - '1337:80'
    depends_on:
      - django-api
  django-api:
    build:
      context: .
      dockerfile: Dockerfile
    command: gunicorn my_app.wsgi:application --log-level verbose --log-file=/var/log/guni --access-logfile=/var/log/gunia --bind 0.0.0.0:8000 --forwarded-allow-ips "*"
    ports:
      - '8000:8000'
    depends_on:
      - mysql
  mysql:
    image: mysql:5
    volumes:
      - type: bind
        source: ./db/docker-entrypoint-initdb.d
        target: /docker-entrypoint-initdb.d
      - type: volume
        source: mysql-data
        target: /var/lib/mysql
    environment:
        MYSQL_ROOT_PASSWORD: toor
    networks:
      - backend
    ports:
      - '3306:3306'
volumes:
  mysql-data:
  static_volume:
networks:
  backend:

gunicorn Dockerfile

FROM python:3
ENV PYTHONUNBUFFERED 1
ENV DJANGO_SETTINGS_MODULE dori.settings.dev
WORKDIR /app
COPY . /app
RUN pip install --upgrade pip
RUN pip install --no-cache-dir -r requirements.txt

# Port to expose
EXPOSE 8000

nginx.conf

upstream hello_django {
    server localhost:8000;
}

server {
    listen 80;
    location / {
        proxy_pass http://hello_django;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
}

Upvotes: 1

Views: 246

Answers (1)

ROOT
ROOT

Reputation: 11622

The issue is in your nginx config file. You are trying to forward request coming to nginx container to the container itself on port 8000, just change your nginx config file to this:

upstream hello_django {
    server django-api:8000;
}

server {
    listen 80;
    location / {
        proxy_pass http://hello_django;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }
}

django-api is the service name for you container in the network that docker-compose creates, and your other service can resolve it in the local network when trying to connect to it.

Upvotes: 3

Related Questions