Docker部署Flask应用时Gunicorn提示找不到模块及WSGI可调用对象的问题排查求助
Let's break down exactly what's causing this error and walk through the easiest fixes.
The Root Cause
Looking at your Dockerfile:
- You set
WORKDIR /app, so the container's working directory is/app. - Then you run
COPY . ./app, which copies all files from your local project directory into a subfolder calledappinside/app. That means yourrun.pyis now at/app/app/run.py, not/app/run.py.
When Gunicorn tries to execute run:gunicorn_app, it looks for a module named run in Python's sys.path—which by default includes the current working directory (/app). Since run.py isn't in /app, Python throws the "no module named" error.
Solution 1: Fix the COPY Command (Recommended)
The simplest fix is to copy your project files directly into the working directory instead of a subfolder. Update your Dockerfile's COPY line:
WORKDIR /app # Copy local files directly to /app instead of /app/app COPY . .
This puts your run.py at /app/run.py, matching what Gunicorn expects. Your directory structure in the container will mirror your local setup, making it easier to debug later.
Solution 2: Adjust Gunicorn to Target the Correct Path
If you need to keep the /app/app subfolder structure for some reason, you have two options here:
Use
--chdirto switch to the subfolder
Modify your CMD to tell Gunicorn to run from/app/app:CMD ["gunicorn", "-b", "0.0.0.0:5000", "--chdir", "/app/app", "run:gunicorn_app"]Note: I split
-b 0.0.0.0:5000into two separate arguments ("-b", "0.0.0.0:5000"). When using the exec form of CMD, each command flag/value needs to be its own string—otherwise Gunicorn will treat the entire string as a single argument and fail to parse it correctly.Specify the full module path
Reference therunmodule inside theappsubfolder directly:CMD ["gunicorn", "-b", "0.0.0.0:5000", "app.run:gunicorn_app"]
Bonus Check: Verify Your Entrypoint Script
Double-check your entrypoint.sh to make sure it isn't changing the working directory or modifying the PYTHONPATH environment variable in a way that breaks module resolution. If the script runs cd to a different folder, that would throw off Gunicorn's ability to find your run module.
内容的提问来源于stack exchange,提问作者tiger t

