Docker新手求助:容器运行正常但浏览器无法访问服务
Hey there! Let's walk through why your mywebapp container isn't loading in the browser and get it fixed. I notice a couple of key mismatches in your setup that are likely causing the issue, plus some quick checks to rule out other factors.
1. Fix the Nginx Configuration & Port Mismatch
Your current Dockerfile exposes port 8000, but the default Nginx image listens on port 80 out of the box. On top of that, you're copying your code to /app, but Nginx doesn't know to serve files from there—it uses /usr/share/nginx/html by default. Here's how to fix both problems:
Step 1: Update Your Dockerfile
Replace your existing Dockerfile with this version, which adds a custom Nginx config to set the correct port and serve directory:
FROM nginx:latest # Create app directory and copy your source code RUN mkdir /app COPY . /app # Replace Nginx's default config with our custom one COPY nginx.conf /etc/nginx/conf.d/default.conf # Expose the port we configured Nginx to listen on EXPOSE 8000
Step 2: Create the Custom Nginx Config
Make a file named nginx.conf in your source directory with this content:
server { listen 8000; server_name localhost; # Point Nginx to your app's files root /app; index index.html index.htm; location / { try_files $uri $uri/ =404; } }
2. Rebuild and Rerun the Container
Now rebuild your image with the fixed setup:
docker build -t mywebapp:v2 .
Then stop the old container (if it's still running) and start the new one:
# Find the old container ID docker ps # Stop it docker stop <container-id> # Run the updated image docker run -d -p 8000:8000 mywebapp:v2
3. Quick Checks for Persisting Issues
If it's still not working, run through these troubleshooting steps:
- Check container logs for Nginx errors:
Look for lines mentioning "failed to start" or "invalid config"—that'll tell you if Nginx isn't loading correctly.docker logs <container-id> - Verify Nginx is listening on port 8000 inside the container:
You should see a line showingdocker exec -it <container-id> bash # Inside the container, run: netstat -tulpn | grep nginx0.0.0.0:8000. - Test connectivity directly from the host:
Skip the browser and test with curl to isolate the issue:
If you get a 404, make sure you have ancurl http://192.168.13.135:8000index.htmlfile in your source directory (Nginx needs a default file to serve). - Check host firewall settings:
Ensure port 8000 is open on your host machine. For example, on Ubuntu/Debian you can run:sudo ufw allow 8000
内容的提问来源于stack exchange,提问作者v.samraksh

