目录
-
- [1. 创建react项目结构](#1. 创建react项目结构)
- [2. 创建 .dockerignore](#2. 创建 .dockerignore)
- [3. 创建 Dockerfile](#3. 创建 Dockerfile)
- [4. 创建 nginx.conf](#4. 创建 nginx.conf)
- [5. 构建和运行](#5. 构建和运行)
- [6. 常用命令](#6. 常用命令)
1. 创建react项目结构

2. 创建 .dockerignore
plaintext:.dockerignore
# 依赖目录
node_modules
npm-debug.log
# 构建输出
dist
build
# 开发环境文件
.git
.gitignore
.env
.env.local
.env.development
.env.test
.env.production
3. 创建 Dockerfile
dockerfile: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
nginx: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. 构建和运行
在项目根目录下执行以下命令:
bash
# 构建Docker镜像
docker build -t react-nginx .
docker run -d -p 80:80 react-nginx
6. 常用命令
bash
# 查看运行中的容器
docker ps
# 停止容器
docker stop <container_id>
# 查看容器日志
docker logs <container_id>
# 进入容器内部
docker exec -it <container_id> sh