Dockerfile 配置如下:
FROM node:lts-alpineWORKDIR /app
COPY . .
RUN npm install
RUN npm run buildEXPOSE 3001CMD ["npm", "run", "preview"]
构建镜像
docker build -t vite-clarity-project .
启动镜像容器
docker run -p 3001:3001 --name=my-vite-clarity-project vite-clarity-project
启动后访问不到:
命令行访问:
root@btx:~# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
1c02a1d7732f vite-clarity-project "docker-entrypoint.s…" 4 hours ago Up 4 hours 0.0.0.0:3001->3001/tcp, :::3001->3001/tcp my-vite-clarity-project
root@btx:~# curl 0.0.0.0:3001
curl: (52) Empty reply from server // 访问不到
浏览器访问:
该网页无法正常运作localhost
未发送任何数据。
ERR_EMPTY_RESPONSE
问题原因:
root@btx:~# docker logs 1c02a1d7732f> vite-clarity-project@0.0.0 preview
> vite preview --port 3001➜ Local: http://localhost:3001/ // 问题原因只启动了 localhost➜ Network: use --host to expose
知识点:
localhost:3001: 仅允许本地主机(即 Docker 容器内部)访问。
0.0.0.0:3001: 允许任何主机(包括容器外部的主机)通过该地址访问服务。
解决方法:
import path from "path"
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'// https://vitejs.dev/config/
export default defineConfig({plugins: [react()],resolve: {alias: {"@": path.resolve(__dirname, "./src"),},},server: {host: '0.0.0.0', // ******** 加上这一行 '0.0.0.0' ******** //},
})