Docker使った時にFlaskが動かない

ローカルで作成した次のコードは正常に動いて、ブラウザを開くと Hello World! と表示されるのに、同様のコードをDocker経由した途端、動かなくなった。

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
    return "Hello World!"

if __name__ == '__main__':
    app.run(port=80, debug=True)

動かないって表現は正確じゃなくて、正しくは localhost に接続しても このページは動作していません ってブラウザに怒られる状態に。

最初はDockerのポート指定間違えているのかな? と思ったが、調べてみたら次の記事に直面。

Flaskのサーバーはデフォルトだと公開されてない - Qiita

host='0.0.0.0' の指定が大事。
これがなければ、外部からアクセスすることができない。

引用元のリンクはドキュメントのバージョンが変わっていて切れていたので貼り直すと以下: Quickstart — Flask Documentation (2.0.x)

Externally Visible Server If you run the server you will notice that the server is only accessible from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer.

If you have the debugger disabled or trust the users on your network, you can make the server publicly available simply by adding --host=0.0.0.0 to the command line:

Oh...。Flaskサーバはデフォルトだと非公開設定なんですネ。
これなんて Flask初心者に対する初見殺し?(ちゃんと公式ドキュメント読んでない奴が悪(ry

そんなわけでコードを以下のように修正。

if __name__ == '__main__':
# before
#     app.run(port=80, debug=True)

# after
    app.run(host="0.0.0.0", port=80, debug=True)

ちゃんとDocker上でもFlaskが動くのを確認。おっけー。

Docker のポート指定間違えてるパターンもあるあるなので、Python側直しても動かない時はそちらも確認してみてくださいね。

ではでは〜ノシ