Docker容器内Flask+TensorFlow Serving应用的外部连接问题排查
Let's walk through the most likely issues and fixes for your problem:
1. You're Missing Docker Port Mapping
This is the most common culprit. When you run a Docker container, ports inside the container aren't automatically exposed to the host machine (your virtual machine with IP 192.168.99.100).
To fix this, explicitly map the Flask port (5000, which your app is using) from the container to a port on your virtual machine when starting the container. Use the -p flag in your docker run command:
docker run -p 5000:5000 your-flask-container-image
This tells Docker to forward traffic from port 5000 on your virtual machine (192.168.99.100:5000) to port 5000 inside the container. After doing this, try accessing the app from outside using that address.
2. Verify Flask is Actually Listening on 0.0.0.0:5000 in the Container
Even though your console says it's running on http://0.0.0.0:5000, it's worth double-checking inside the container to be sure.
- First, get your container ID with
docker ps - Then run a shell inside the container:
docker exec -it <container-id> /bin/bash
- Inside the container, run either of these commands to check listening ports:
netstat -tulpn | grep 5000 # Or if netstat isn't installed: ss -tulpn | grep 5000
You should see a line showing 0.0.0.0:5000 being listened to by Python. If not, there might be a conflict in your Flask code (like another part overriding the host parameter in app.run).
3. Test Access from the Virtual Machine First
Before trying external access, confirm the virtual machine itself can reach the container's Flask app. On your virtual machine, run:
curl http://172.17.0.2:5000
- If this works: The issue is definitely port mapping (step 1) or firewall rules on the virtual machine.
- If this fails: The problem is inside the container—either Flask isn't listening correctly, or there's a firewall inside the container blocking port 5000.
4. Check Virtual Machine Firewall Rules
Your virtual machine's firewall might be blocking incoming traffic on port 5000.
- If you're using
ufw, allow the port with:
sudo ufw allow 5000/tcp
- If you're using
iptables, add a rule to accept traffic on 5000:
sudo iptables -A INPUT -p tcp --dport 5000 -j ACCEPT
After updating the firewall, try accessing the app again from outside.
5. Double-Check Your Flask Run Configuration
Make sure there's no other code in flask_client.py that's overriding the host setting. For example, if you have environment variables set (like FLASK_RUN_HOST) that might be changing the listening address.
You can add a quick print statement to confirm:
if __name__ == "__main__": print(f"Starting Flask app on host 0.0.0.0, port 5000") app.run(host='0.0.0.0')
This will make it clear if the correct host is being used when the app starts.
内容的提问来源于stack exchange,提问作者dhinar1991




