使用 Docker 部署 React + Nginx 应用教程

目录

    • [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
相关推荐
Java陈序员4 分钟前
免费开源!一款操作 MySQL 和 MariaDB 的 Web 界面工具!
mysql·docker·php·mariadb
梁正雄31 分钟前
9、dockerfile
docker·dockerfile·dockerfile基础用法
panplan.top36 分钟前
Tornado + Motor 微服务架构(Docker + 测试 + Kubernetes)
linux·python·docker·微服务·k8s·tornado
-指短琴长-1 小时前
Docker基础【Ubuntu安装/Windows安装】
windows·ubuntu·docker
Z_Xshan1 小时前
docker 容器web站点 中文文件名访问404问题
linux·开发语言·docker
回忆是昨天里的海2 小时前
k8s集群-节点间通信之安装kube-flannel插件
java·docker·kubernetes
希晨er3 小时前
Nginx从入门到实践:安装、配置与应用
nginx
举个栗子dhy3 小时前
第二章、全局配置项目主题色(主题切换+跟随系统)
前端·javascript·react.js
ZHE|张恒4 小时前
Docker 安装 MinIO(20250422)
运维·docker·容器
jc06204 小时前
4.5-中间件之Nginx
运维·服务器·nginx