Implementación de una aplicación flask mínima en problemas de conexión de docker - server


Tengo una aplicación cuya única dependencia es flask, que se ejecuta bien fuera de docker y se vincula al puerto predeterminado 5000. Aquí está la fuente completa:

from flask import Flask

app = Flask(__name__)
app.debug = True

@app.route('/')
def main():
    return 'hi'

if __name__ == '__main__':
    app.run()

El problema es que cuando despliego esto en docker, el servidor se está ejecutando pero es inalcanzable desde fuera del contenedor.

A continuación está mi archivo Dockerfile. La imagen es ubuntu con flask instalado. El tar solo contiene el index.py enumerado anteriormente;

# 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"]

Estos son los pasos que estoy haciendo para desplegar

$> sudo docker build -t perfektimprezy .

Por lo que sé, lo anterior funciona bien, la imagen tiene el contenido del tar en /srv. Ahora, vamos a iniciar el servidor en un contenedor:

$> sudo docker run -i -p 5000:5000 -d perfektimprezy
1c50b67d45b1a4feade72276394811c8399b1b95692e0914ee72b103ff54c769

¿Está funcionando realmente?

$> sudo docker ps
CONTAINER ID        IMAGE                   COMMAND             CREATED             STATUS              PORTS                    NAMES
1c50b67d45b1        perfektimprezy:latest   "python index.py"   5 seconds ago       Up 5 seconds        0.0.0.0:5000->5000/tcp   loving_wozniak

$> sudo docker logs 1c50b67d45b1
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
 * Restarting with stat

Sí, parece que el servidor flask se está ejecutando. Aquí es donde se pone raro. Vamos a hacer una solicitud al servidor:

 $> curl 127.0.0.1:5000 -v
 * Rebuilt URL to: 127.0.0.1:5000/
 * Hostname was NOT found in DNS cache
 *   Trying 127.0.0.1...
 * Connected to 127.0.0.1 (127.0.0.1) port 5000 (#0)
 > GET / HTTP/1.1
 > User-Agent: curl/7.35.0
 > Host: 127.0.0.1:5000
 > Accept: */*
 >
 * Empty reply from server
 * Connection #0 to host 127.0.0.1 left intact
 curl: (52) Empty reply from server

Respuesta vacía... Pero, ¿se está ejecutando el proceso?

$> sudo docker top 1c50b67d45b1
UID                 PID                 PPID                C                   STIME               TTY                 TIME                CMD
root                2084                812                 0                   10:26               ?                   00:00:00            python index.py
root                2117                2084                0                   10:26               ?                   00:00:00            /usr/bin/python index.py

Ahora vamos a ssh en el servidor y comprobar...

$> sudo docker exec -it 1c50b67d45b1 bash
root@1c50b67d45b1:/srv# netstat -an
Active Internet connections (servers and established)
Proto Recv-Q Send-Q Local Address           Foreign Address         State
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN
tcp        0      0 127.0.0.1:47677         127.0.0.1:5000          TIME_WAIT
Active UNIX domain sockets (servers and established)
Proto RefCnt Flags       Type       State         I-Node   Path
root@1c50b67d45b1:/srv# curl -I 127.0.0.1:5000
HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 5447
Server: Werkzeug/0.10.4 Python/2.7.6
Date: Tue, 19 May 2015 12:18:14 GMT

Es fino... pero no desde fuera : (¿Qué estoy haciendo mal?

Author: Dreen, 2015-05-19

3 answers

El problema es que solo está enlazando a la interfaz localhost, debe estar enlazando a 0.0.0.0 si desea que el contenedor sea accesible desde el exterior. Si cambia:

if __name__ == '__main__':
    app.run()

A

if __name__ == '__main__':
    app.run(host='0.0.0.0')

Debería funcionar.

 77
Author: Adrian Mouat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-05-19 15:13:17

Esto no funciona para mí.

app.run(host='0.0.0.0')

En su lugar, usé:

$> flask run --host=0.0.0.0
 8
Author: Marku,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-26 02:48:15

Encontré un artículo interesante sobre cómo ejecutar Python Flask en una docker. Debería ayudar a aquellos que son nuevos en Docker https://medium.com/@yoratyo/running-flask-on-docker-dc3941d39304

 1
Author: swdev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-31 09:22:56