Docker部署Flask应用连接失败求助(Ubuntu 18.04)
Let's break down the issues preventing your Flask app from running properly in Docker, and fix them step by step.
1. Critical Typo in app.py (The Root Cause)
Take a close look at the entry point of your app.py script:
if __name__ == '__main_': # Missing an underscore here! app.run(debug=True, host='0.0.0.0', port=5000)
This line should be __main__ (two underscores on both ends). Because of this typo, the Flask server code never executes—your container launches, runs through the script without starting the server, then exits immediately. This explains all the confusing behavior you're seeing:
docker psmight briefly show the container as "Up" before it exitsdocker execfails because the container isn't actually running anymore- You don't see any server startup logs in
docker logs
Fix: Correct the line to:
if __name__ == '__main__': app.run(debug=True, host='0.0.0.0', port=5000)
2. Incorrect Path for requirements.txt in Dockerfile
In your Dockerfile, you're copying requirements.txt to /pynlg_root/requirements.txt, but then running pip install -r requirements.txt from the /flask_app_dir working directory. Pip can't locate the file at this path, which would cause an installation error (even if it didn't show up clearly in your logs).
Fix: Update the COPY line to place the file in your working directory:
COPY ./requirements.txt /flask_app_dir/requirements.txt
Or, since your WORKDIR is already set to /flask_app_dir, you can simplify it to:
COPY ./requirements.txt .
3. Verify Container Status and Logs After Fixes
Once you've applied the above changes, rebuild your image and launch the container again. Then:
- Run
sudo docker ps -ato check if the container stays running (the-aflag shows all containers, including stopped ones) - If it still exits unexpectedly, run
sudo docker logs flask_tryagain—you’ll now get clearer error messages to debug any remaining issues
4. Optional: Simplify Your Dockerfile (Reduce Unnecessary Complexity)
Your multi-stage build includes redundant steps (like installing Python 3.7 again in the first stage when you’re already using python:3.7 as the base image). You can simplify it to avoid potential conflicts, for example:
FROM python:3.7 WORKDIR /flask_app_dir COPY . . ARG SPACY_VERSION=2.3.4 ENV PATH /local/bin:/local/cmd:$PATH RUN pip install -r requirements.txt \ && pip install spacy==${SPACY_VERSION} \ && python -m spacy download fr_core_news_lg \ && pip install six ENTRYPOINT ["python"] CMD ["app.py"]
(Keep the first stage only if you truly need the /local/ files from it—otherwise, this streamlined version works better.)
After applying these fixes, rebuild your image with sudo docker build -t flask-image:latest . and run the container again. You should be able to access 127.0.0.1:5000 successfully.
内容的提问来源于stack exchange,提问作者Catalina Chircu

