简体   繁体   中英

Flask container is not up and running using docker

So my issue is very simple, but still can't get hold of it and it's not performing like I wanted to.

sample docker file:

FROM ubuntu:16.04

RUN apt-get update -y && \
    apt-get install -y python3-pip python3-dev
COPY ./requirements.txt /requirements.txt
WORKDIR /
RUN pip3 install -r requirements.txt
COPY . /
RUN chmod a+x start.sh
EXPOSE 5000
CMD ["./start.sh"]

sample start.sh

#!/usr/bin/env bash

# sleep 600
nohup python3 /code/app.py &
python3 /code/helloworld_extract.py

sample flask app.py

from flask import Flask

app = Flask(__name__)


@app.route("/")
def index():
    return """
  <h1>Python Flask in Docker!</h1>
  <p>A sample web-app for running Flask inside Docker.</p>
  """


if __name__ == "__main__":
    app.run(debug=True, host='0.0.0.0')

So, my issue is as soon as I build the image and run it, docker run --name flaskapp -p5000:5000 docker-flask:latest ... I can't reach localhost:5000. While if I get inside the container and run explict nohup command with python3 app.py. I can reach localhost.

So, why can't I reach the localhost host with run command?

The thing is I need to run 2 scripts one is flask and another one is helloworld_extract.py which eventually exit after writing some information to the files.

When your start.sh script says

#!/bin/sh
do_some_stuff_in_the_background &
some_foreground_process

The entire lifecycle of the container is tied to the some_foreground_process . In your case, since you clarify that it's doing some initial data load and exits, once it exits, the start.sh script is finished, and so the container exits.

(As a general rule, try to avoid nohup and & in Docker land, since it leads to confusing issues like this.)

I would suggest making the main container process be only the Flask server.

CMD ["python3", "/code/app.py"]

You don't say what's in the loader script. Since its lifecycle is completely different from the main application, it makes sense to run it separately; you can replace the CMD with docker run options. Say you need to populate some shared data in the filesystem. You can:

# Build the image
docker build -t myimage .

# Create a (named) shared filesystem volume
docker volume create extract

# Start the Flask server
docker run -d -p 5000:5000 -v extract:/data myimage

# Run the script to prepopulate the data
docker run -v extract:/data myimage python3 /code/helloworld_extract.py

Notice that the same volume name extract is used in all the commands. The path name /data is an arbitrary choice, though since both commands run on the same image it makes sense that they'd have the same filesystem layout.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM