简体   繁体   English

如何将Nginx与Docker一起用作反向代理

[英]How to use nginx with docker as a reverse proxy

I have a django app and running it with gunicorn on localhost:8000 I have configs for nginx to use it as a reverse proxy. 我有一个django应用,并在localhost:8000上与gunicorn一起运行。我为nginx配置了将其用作反向代理的功能。

    upstream django {
 #  fail_timeout=0 means we always retry an upstream even if it failed
 #  to return a good HTTP response (in case the Unicorn master nukes a
 #  single worker for timing out).

  server localhost:8000 fail_timeout=0;
}

I know how to expose 80 port and run nginx in container, but I don't understand how to connect gunicorn running on localhost and nginx in container. 我知道如何公开80端口并在容器中运行nginx,但是我不明白如何连接在本地主机上运行的gunicorn和容器中的nginx。

You'll need to utilize the IP of the bridge created by docker. 您需要利用docker创建的网桥的IP。 There is a good article on Docker explaining this: https://docs.docker.com/v1.6/articles/networking/ Docker上有一篇很好的文章对此进行了解释: https : //docs.docker.com/v1.6/articles/networking/

When Docker starts, it creates a virtual interface named docker0 on the host machine. Docker启动时,它将在主机上创建一个名为docker0的虚拟接口。 It randomly chooses an address and subnet from the private range defined by RFC 1918 that are not in use on the host machine, and assigns it to docker0. 它从RFC 1918定义的主机范围内未使用的私有范围中随机选择一个地址和子网,并将其分配给docker0。

If we take a look at the IP address assigned to docker0 ( sudo ip addr show docker0 ) we could use this as the IP address to communicate with the host from within a docker container. 如果我们查看分配给docker0的IP地址( sudo ip addr show docker0 ),我们可以将其用作与sudo ip addr show docker0容器中的主机进行通信的IP地址。

    upstream django {
 #  fail_timeout=0 means we always retry an upstream even if it failed
 #  to return a good HTTP response (in case the Unicorn master nukes a
 #  single worker for timing out).

  server IP_OF_DOCKER0:8000 fail_timeout=0;
}

I haven't tested the above but I believe it should work. 我尚未测试以上内容,但我认为它应该可以工作。 If not you may need to bind gunicorn to the docker0 IP as well. 如果没有,您可能还需要将gunicorn绑定到docker0 IP。

This answer has some good insight into this process as well... From inside of a Docker container, how do I connect to the localhost of the machine? 这个答案对这个过程也有一些深刻的了解... 从Docker容器内部,如何连接到计算机的本地主机?

A better approach might be "dokerize" the django application too, build a network between the dokerized nginx and the dockerized django application then expose the http port from the dockerized nginx to all interfaces. 更好的方法可能也是“ dkergo” django应用程序,在dokerized nginx和dockerized django应用程序之间建立网络,然后将dockerized nginx的http端口暴露给所有接口。

Here is a good post about this, maybe you can take some hints from it :) 这是一篇很好的文章 ,也许您可​​以从中得到一些提示:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM