When deploying Flask applications in Docker, it's possible to encounter server connectivity issues despite the container appearing to be running. This article will investigate a common problem and provide a solution to ensure the application is accessible from outside the container.
Consider an app named "perfektimprezy" that runs on Flask, with the following source:
from flask import Flask app = Flask(__name__) app.debug = True @app.route('/') def main(): return 'hi' if __name__ == '__main__': app.run()
When deployed in a Docker container, the server seems to be running, but the application remains inaccessible from outside the container.
The Dockerfile used for the deployment is:
# Dockerfile FROM dreen/flask MAINTAINER dreen WORKDIR /srv # Get source RUN mkdir -p /srv COPY perfektimprezy.tar.gz /srv/perfektimprezy.tar.gz RUN tar x -f perfektimprezy.tar.gz RUN rm perfektimprezy.tar.gz # Run server EXPOSE 5000 CMD ["python", "index.py"]
The deployment steps involve building the image and running the container with port 5000 exposed:
>$ sudo docker build -t perfektimprezy . >$ sudo docker run -i -p 5000:5000 -d perfektimprezy
The container appears to be running as expected, with the Flask server listening on port 5000 within the container:
>$ sudo docker logs 1c50b67d45b1 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat
However, requests to the application from outside the container result in empty replies:
>$ curl 127.0.0.1:5000 -v * Empty reply from server
The issue lies in the binding of the Flask app to the localhost interface. To make the application accessible from outside the container, it should bind to the 0.0.0.0 address instead.
In the Flask app initialization, change:
if __name__ == '__main__': app.run()
to:
if __name__ == '__main__': app.run(host='0.0.0.0')
This modification will bind the app to all interfaces on the host, making it accessible from outside the container.
The above is the detailed content of Why Can't I Access My Flask App After Deploying it in Docker?. For more information, please follow other related articles on the PHP Chinese website!