【问题标题】:Docker + django + gunicorn connect to Nginx of the host systemDocker + django + gunicorn 连接宿主系统的Nginx
【发布时间】:2021-02-24 03:48:02
【问题描述】:

在 ubuntu 服务器 18.04
我用 Django 3.1 和 Gunicorn 运行一个 docker 容器 它连接到本地安装的 Postgres。

我已经在没有 docker 的同一台服务器上拥有另一个带有 Nginx 和 Gunicorn 的 Django 项目。

问题是:如何在容器中为 Gunicorn 设置套接字文件并将此容器连接到现有的外部 Nginx,以便我可以从外部访问容器化的 django 应用程序?

docker-compose.prod.yml

version: '3'

services:
  app:
   build:
     context: .
   ports:
     - "8001:8001"
   volumes:
     - ./app:/app
   env_file:
     - .env.prod
   command: >
     sh -c "gunicorn app.wsgi:application --bind 0.0.0.0:8001"

我这样运行容器:

docker-compose -f docker-compose.prod.yml up

.env.prod

...
DJANGO_ALLOWED_HOSTS='111.111.111.111 .mysitename.com localhost 172.18.0.1 127.0.0.1 [::1]'
...

运行容器时执行此命令:

curl 'http://127.0.0.1:8001/admin/login/?next=/admin/'

给我管理页面的html代码,没关系。

现有的 Nginx 设置如这些数字海洋教程中所示:

https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04

我还使用本教程 https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04 加密来保护它

【问题讨论】:

    标签: django docker ubuntu nginx gunicorn


    【解决方案1】:

    一切都比我想象的要简单。

    在 Nginx 配置文件中

    /etc/nginx/sites-available/ 像这样编辑

    server {
        server_name 111.111.111.111 domainname.com www.domainname.com *.domainname.com;
    
        location = /favicon.ico { access_log off; log_not_found off; }
        location /static/ {
            root /home/user/<my-previous-project-installed-locally>/project-app;
        }
    
        location / {
            include proxy_params;
            proxy_pass http://unix:/run/gunicorn.sock;
       }
    
       # Added for the NEW application
    ###############################################
        location  /MY-NEW-PATH/ {
            rewrite ^/MY-NEW-PATH(.*) $1 break;
            proxy_pass http://127.0.0.1:8001;
        }
    ###############################################
    
        listen 443 ssl; # managed by Certbot
        ssl_certificate /etc/letsencrypt/live/domainname.com/fullchain.pem; # managed by Certbot
        ssl_certificate_key /etc/letsencrypt/live/domainname.com/privkey.pem; # managed by Certbot
        include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
        ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
    
    }
    
    server {
        if ($host = www.domainname.com) {
            return 301 https://$host$request_uri;
        } # managed by Certbot
    
    

    【讨论】:

      猜你喜欢
      • 2019-01-04
      • 2021-01-02
      • 2019-03-22
      • 2021-09-23
      • 1970-01-01
      • 2017-09-26
      • 2016-02-23
      • 2015-03-02
      • 2021-12-12
      相关资源
      最近更新 更多