我有一个Flask服务器通过端口5000运行,它很好。我可以在http://example.com:5000上访问它
但是是否可以通过http://example.com访问呢?我假设这意味着我必须将端口从5000更改为80。但是当我在Flask上尝试时,当我运行它时,我得到这个错误消息。
Traceback (most recent call last):
File "xxxxxx.py", line 31, in <module>
app.run(host="0.0.0.0", port=int("80"), debug=True)
File "/usr/local/lib/python2.6/dist-packages/flask/app.py", line 772, in run
run_simple(host, port, self, **options)
File "/usr/local/lib/python2.6/dist-packages/werkzeug/serving.py", line 706, in run_simple
test_socket.bind((hostname, port))
File "<string>", line 1, in bind
socket.error: [Errno 98] Address already in use
运行lsof -i:80返回
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
apache2 467 root 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 4413 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14346 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14570 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14571 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
apache2 14573 www-data 3u IPv4 92108840 0t0 TCP *:www (LISTEN)
我需要先终止这些进程吗?这样安全吗?或者有没有另一种方法来保持Flask在端口5000上运行,但有主网站域名以某种方式重定向?
它会抛出错误消息,因为apache2在端口80上运行。
如果这是为了开发,我只会让它保持在端口5000上。
如果是为了生产:
不推荐
首先停止apache2;
不建议,因为它在文档中写道:
您可以在开发期间使用内置服务器,但是您应该为生产应用程序使用完整的部署选项。(请勿在生产环境中使用内置开发服务器。)
推荐
代理HTTP流量通过apache2到Flask。
通过这种方式,apache2可以处理所有静态文件(这一点它非常擅长——比Flask内置的调试服务器好得多),并充当动态内容的反向代理,将这些请求传递给Flask。
这里有一个关于使用Apache + mod_wsgi设置Flask的官方文档链接。
编辑1 -澄清@Djack
通过apache2代理HTTP流量到Flask
当请求到达80端口(HTTP)或443端口(HTTPS)的服务器时,像Apache或Nginx这样的web服务器会处理请求的连接,并计算出如何处理它。在我们的例子中,接收到的请求应该配置为通过WSGI协议传递给Flask,并由Python代码处理。这就是“动态”部分。
动态内容的反向代理
像上面那样配置你的web服务器有一些优势;
SSL Termination - The web server will be optimized to handle HTTPS requests with only a little configuration. Don't "roll your own" in Python which is probably very insecure in comparison.
Security - Opening a port to the internet requires careful consideration of security. Flask's development server is not designed for this and could have open bugs or security issues in comparison to a web server designed for this purpose. Note that a badly configured web server can also be insecure!
Static File Handling - It is possible for the builtin Flask web server to handle static files however this is not recommended; Nginx/Apache are much more efficient at handling static files like images, CSS, Javascript files and will only pass "dynamic" requests (those where the content is often read from a database or the content changes) to be handled by the Python code.
+more. This is bordering on scope for this question. If you want more info do some research into this area.