无法访问容器化React应用端口,疑为端口配置问题求助
无法访问容器化React应用的问题解决
问题背景
我无法访问容器化后的React应用,创建容器后无法正常访问(见附图),推测是端口配置错误导致的,以下是我的相关配置文件:
Dockerfile
FROM node:20.11.1-alpine as builder WORKDIR /app COPY package.json ./ COPY package-lock.json ./ RUN npm install COPY . . EXPOSE 5173 CMD [ "npm", "run", "dev" ]
docker-compose.dev.yml
version: "3.8" services: app: container_name: front-end-app image: app-dev build: context: ./../ dockerfile: ./Dockerfile volumes: - ./src:/app/src ports: - 5173:5173 stdin_open: true env_file: - ./../.env
package.json
"scripts": { "dev": "vite", }
vite.config.ts
import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import tsconfigPaths from "vite-tsconfig-paths"; // https://vitejs.dev/config/ export default defineConfig({ plugins: [tsconfigPaths(), react()], });
问题原因与解决方法
核心问题是Vite默认只监听容器内部的localhost(127.0.0.1),宿主机无法直接访问这个地址。必须让Vite监听0.0.0.0,这样服务才能绑定到容器的所有网络接口,允许外部访问。
方案1:修改package.json启动命令
直接在vite启动命令后添加--host 0.0.0.0参数:
"scripts": { "dev": "vite --host 0.0.0.0" }
方案2:修改vite.config.ts配置
在Vite配置中显式设置server.host:
import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import tsconfigPaths from "vite-tsconfig-paths"; export default defineConfig({ plugins: [tsconfigPaths(), react()], server: { host: "0.0.0.0" // 新增这行配置 } });
验证步骤
- 重新构建镜像并启动容器:
docker-compose -f docker-compose.dev.yml up --build - 查看容器日志:
docker logs front-end-app,如果看到类似Network: http://xxx.xxx.xxx.xxx:5173的输出,说明配置生效 - 检查宿主机端口是否被占用:用
lsof -i :5173(Linux/macOS)或netstat -ano | findstr :5173(Windows)确认5173端口未被其他进程占用
内容的提问来源于stack exchange,提问作者bynik
相关产品推荐
相关产品推荐

