python - 多 docker 容器 NGINX+FLASK:缺少通过 localhost 定义的上游应用程序
问题描述
编辑:我检查了一下,似乎 azure 提供了一个默认的网桥,然后 localhost 解决方案可以正常工作。
我运行两个容器 docker-compose NGINX + Gunicorn&Flask,我想将 NGINX 设置为应用程序的反向代理。我试图让它作为 CLI 在 AZURE 云上运行,但我的 Nginx 无法找到来自应用程序的上游。在我的本地机器上,我在 nginx 配置中获得了这个指定容器名称和相关的暴露端口,这在云上似乎不起作用。
我尝试将 proxy_pass 更改为 localhost(相同端口),但在这种情况下,即使在我的本地计算机上它也不起作用,返回 502 Bad Gateway 错误。无论如何,我都可以通过浏览器或任何其他方法向应用程序发送请求。Nginx 与 supervisord 一起运行。Gunicorn 使用 1 个工作线程 (gthread) 和 4 个不同的线程运行。
这是我的 nginx.conf (包含在内的那个):
server {
listen 80;
location / {
try_files $uri @proxy_to_app;
}
location @proxy_to_app {
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_redirect off;
proxy_pass http://mycontainer:5000;
# proxy_pass http://localhost:5000;
}
}
这里是主要的:
user nginx;
worker_processes 1;
error_log /app/logs/nginx_error.log warn;
pid /var/run/nginx.pid;
events {
worker_connections 1024;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
log_format main '$proxy_add_x_forwarded_for - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent "$http_referer" '
'"$http_user_agent"' ;
access_log /app/logs/nginx_access.log main;
sendfile on;
keepalive_timeout 65;
include /etc/nginx/conf.d/*.conf;
}
daemon off;
解决方案
如果 nginx 和应用程序都运行容器化,那么..
为了让您的容器(或服务)能够找到彼此,它们必须属于同一个网络。所以你需要打电话
docker network create -d DRIVER_NAME YOUR_NETWORK_NAME
根据您在做什么(独立容器或群服务),您必须在创建网络时在桥接或覆盖 网络驱动程序之间进行选择。
然后使用--network标志执行 docker run或docker service create并传递您的网络名称。
此外,nginx 配置应包含以下内容
server {
listen 80; # host port - used by proxy
server_name localhost;
resolver 127.0.0.11 valid=10s ipv6=off; # 127.0.0.11 the static IP address of the internal DNS server of the swarm
set $upstream YOUR_SERVICE_NAME; # mandatory when not using the upstream section
client_max_body_size 0; # disable any limits to avoid HTTP 413 for large image uploads
location / {
proxy_pass http://$upstream:YOUR_SERVICE_PORT;
proxy_read_timeout 900;
#proxy_redirect off; # do not re-write the Location and Refresh header fields of an upstream server
proxy_set_header Host $host; # required for docker
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header Referer $http_referer;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_cache_bypass $http_upgrade;
}
}
推荐阅读
- android - 如果每种颜色代表一个字符,如何显示一组颜色
- spring-boot - 普罗米修斯执行器的自定义路径
- android - 无法解决:firebase-iid-interop
- javascript - 使用 Ext.js 4.2 选择已选择的 Treenode(重新选择)
- shell - Shell 脚本输出 ISO8601
- apache - apache vhost 不工作,给出:“你的连接不是私有的”
- sql - SQL:如何在选择查询中添加基于另一列的 ID 列?
- javascript - 如果查询返回 0 个文档,则添加文档
- python - 在 python 中创建二维查找表
- c++ - 通过 Mmap-ed 共享内存传递可变长度 C 字符串