目錄
- 1. 創建react項目結構
- 2. 創建 .dockerignore
- 3. 創建 Dockerfile
- 4. 創建 nginx.conf
- 5. 構建和運行
- 6. 常用命令
1. 創建react項目結構
2. 創建 .dockerignore
# 依賴目錄
node_modules
npm-debug.log# 構建輸出
dist
build# 開發環境文件
.git
.gitignore
.env
.env.local
.env.development
.env.test
.env.production
3. 創建 Dockerfile
# 構建階段
FROM node:18-alpine as build
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build# 生產階段
FROM nginx:alpine
COPY --from=build /app/dist /usr/share/nginx/html
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
4. 創建 nginx.conf
server {listen 80;server_name localhost;location / {root /usr/share/nginx/html;index index.html index.htm;try_files $uri $uri/ /index.html;}
}
完整的項目結構
5. 構建和運行
在項目根目錄下執行以下命令:
# 構建Docker鏡像
docker build -t react-nginx .docker run -d -p 80:80 react-nginx
6. 常用命令
# 查看運行中的容器
docker ps# 停止容器
docker stop <container_id># 查看容器日志
docker logs <container_id># 進入容器內部
docker exec -it <container_id> sh