Nginx error for Django application

Hi everyone,

I am trying to deploy a Django application in production by using nginx and gunicorn. However, nginx is throwing this error:

[emerg] 1#1: host not found in upstream “web:8000” in /etc/nginx/conf.d/nginx.conf:2
nginx_1 | nginx: [emerg] host not found in upstream “web:8000” in /etc/nginx/conf.d/nginx.conf:2

and I have no idea how to fix it. I have tried everything, but nothing worked. Here is my setup

setting.py


STATIC_URL = ‘/staticfiles/’

if not DEBUG:
    STATIC_ROOT =  os.path.join(BASE_DIR, "staticfiles")

STATICFILES_DIRS = []

MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'

Django App Dockerfile

#pull official base image
FROM python:3.7

#set work directory
WORKDIR /app
RUN mkdir /app/media

#set environment variables
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1

#install dependencies
RUN pip install --upgrade pip
COPY ./requirements.txt .
RUN pip install -r requirements.txt

#copy project
COPY . .

Nginx Dockerfile

FROM nginx:1.19.0-alpine

RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d

nginx.conf file

upstream webapp{
server web:8000;
}

server {

listen 80;

location / {
    proxy_pass http://web:8000;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $host;
    proxy_redirect off;
}

location /staticfiles/ {
    alias /app/staticfiles/;
}

location /media/ {
    alias /app/media/;
}

}

docker-compose.yml file

version: “3.7”

services:

web:
build: ./app2
container_name: web_app
restart: always
command: >
sh -c “python manage.py collectstatic --noinput &&
gunicorn webapp.wsgi:application --bind 0.0.0.0:8000”
volumes:
- ./app2:/app
- static_volume:/app/staticfiles
- media_volume:/app/media
expose:
- 8000
env_file:
- .env.prod
networks:
- dsa

cronjob:
build: ./cronjob
container_name: webapp_cronjob
restart: always
volumes:
- ./app2:/app
networks:
- dsa

nginx:
build: ./nginx
container_name: webapp_nginx
volumes:
- static_volume:/app/staticfiles
- media_volume:/app/media
ports:
- “20.0.0.3:8080:80”
depends_on:
- web

volumes:
static_volume:
media_volume:

networks:
dsa:
external: true

Can you confirm that docker shows that the web service is up and running and listening on port 8000?

Yes, when I run docker ps I can see my web docker container ports as 8000/tcp. I think I should mention that I have another app running at port 8000 in a different docker-compose file. Does this matter?

I think it would only be a problem if you used the same service name - you’d have two different services with the same dns name for that docker network.

We create an internal network for each docker-compose file, with aliases for the services, so that internal-to-the-compose-file communications are isolated from the external network.

They don’t have the same service name

add web to /etc/hosts

127.0.0.1 web