Docker部署React应用无法访问localhost问题求助
Hey Joelito, let's walk through the most common issues that could be causing your React app to run fine in a Docker container but not be accessible on localhost:8090. I'll break this down step by step based on typical Docker + React setups:
First up, confirm you're using the correct port mapping when starting your container. If your React app runs on the default dev server port (3000) inside the container, you need to map your host's 8090 port to the container's 3000:
docker run -p 8090:3000 your-image-name
If you've configured your app to run on port 8090 inside the container, adjust the command to:
docker run -p 8090:8090 your-image-name
Also, check your Dockerfile for an EXPOSE line (e.g., EXPOSE 3000). While this doesn't create the mapping itself, it confirms which port your containerized service is using.
By default, create-react-app's dev server only binds to localhost—this works inside the container, but the host machine can't reach it. Fix this by updating your start command:
- In
package.json, modify thestartscript:"scripts": { "start": "react-scripts start --host 0.0.0.0" } - If you're using a custom webpack config (like
webpack.common.jsorwebpack.config.js), add these devServer settings:module.exports = { // ... other config devServer: { host: '0.0.0.0', port: 3000, // match your container's internal port allowedHosts: 'all' // bypass host validation that might block access } };
Verify the port your app is actually running on inside the container matches the second number in your -p flag. For example:
- If logs show your app is at
http://localhost:3000inside the container, use-p 8090:3000 - If it's using port 8090 internally, use
-p 8090:8090
You can check the container logs for lines likeOn Your Network: http://172.17.0.2:3000—this shows the container's internal IP and the port your app is using.
- On your host machine, make sure port 8090 isn't blocked by a firewall. For Linux, run:
On Windows, check Windows Defender Firewall settings to allow inbound connections to port 8090.sudo ufw allow 8090/tcp - If using Docker Desktop, try switching back to the default bridge network if you're using a custom network setup—sometimes custom networks can restrict host access.
If you're serving a production build (via npm run build) with a web server like Nginx:
- Confirm your
Dockerfilecorrectly copies the build files to Nginx's default directory:
Then start the container withFROM nginx:alpine COPY build /usr/share/nginx/html EXPOSE 80-p 8090:80(since Nginx uses port 80 by default). - If you're using a custom Nginx config, ensure it listens on
0.0.0.0:80instead of justlocalhost.
内容的提问来源于stack exchange,提问作者Joelito

