Get server URL in django docker

柔情痞子 提交于 2021-01-25 07:18:45

问题


I am running Django project in docker. I have 3 docker container.

  1. For Django App
  2. For Postgres
  3. For Nginx

My docker-compose.yml file is as follow

version: "3"
services:
  db:
    restart: always
    container_name: tts-db
    image: postgres:9.6
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=postgres
      - POSTGRES_DB=tts
    expose:
      - "5432"

  nginx:
    image: nginx:latest
    container_name: tts-nginx
    ports:
      - "8000:8000"
    volumes:
      - ./nginx/site-enabled:/etc/nginx/conf.d
    depends_on:
      - web

  web:
    build: .
    container_name: tts-app
    environment:
      - DATABASE=db
      - DEBUG=False
      - STATICFILES_STORAGE=whitenoise.storage.CompressedManifestStaticFilesStorage
    depends_on:
      - db
    expose:
      - "8888"
    entrypoint: ./entry_point.sh
    command: gunicorn urdu_tts.wsgi:application -w 2 -b :8888
    restart: always

In my django app, I need to access host address. I used request.get_host() which works in localhost. When I run this in Docker, I get url like http://web/media/voice/voice.wav. My nginx configuration is as follow.

upstream web {
  ip_hash;
  server web:8888;
}

server {

    location ^/static/ {
        autoindex on;
        alias /static/;
    }

    location ~ ^/media/?(.*)$ {
        try_files /media/$1 /mediafiles/$1 =404;
    }

    location / {
        proxy_pass http://web;
        client_max_body_size 20m;
    }
    listen 8000;
    server_name localhost;
}

How can I get server url in Docker?


回答1:


Using following configuration in Nginx configuration works for me.

proxy_set_header Host $http_host; # Define host as http_host.

Now my nginx configuration looks like this:

upstream web {
  ip_hash;
  server web:8888;
}

server {

    location ^/static/ {
        autoindex on;
        alias /static/;
    }

    location ~ ^/media/?(.*)$ {
        try_files /media/$1 /mediafiles/$1 =404;
    }

    location / {
        proxy_pass http://web;
        client_max_body_size 20m;
        proxy_set_header Host $http_host;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Protocol "";
        proxy_set_header X-Forwarded-Ssl "";
    }
    listen 8000;
    server_name localhost;
}


来源:https://stackoverflow.com/questions/48251925/get-server-url-in-django-docker

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!