Docker + django + gunicorn 连接宿主系统的Nginx

Docker + django + gunicorn connect to Nginx of the host system

在 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]'
...

当 运行ning 容器执行此命令时:

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

我还使用 Let's encrypt using this tutorial https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04

对其进行了保护

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

在 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(.*)  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