Home >Backend Development >Python Tutorial >Why Can't I Access My Flask App After Deploying it in Docker?

Why Can't I Access My Flask App After Deploying it in Docker?

DDD
DDDOriginal
2024-12-24 07:17:16209browse

Why Can't I Access My Flask App After Deploying it in Docker?

Deploying Flask App in Docker: Resolving Server Connection Issues

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.

Problem Description

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.

Docker Configuration

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

Investigation

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

Solution

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn