Docker基础:12.部署react前端项目

973 阅读1分钟

1. 使用vite创建react项目

$ npm create vite@latest
# or
$ yarn create vite
# or
$ pnpm create vite

2. 创建Dockerfile

# 使用一个基础的nginx镜像
FROM nginx:latest

# 删除默认的nginx配置文件
RUN rm /etc/nginx/conf.d/default.conf

# 将我们自定义的nginx配置文件复制到容器中
COPY nginx.conf /etc/nginx/conf.d/

# 将前端代码复制到nginx的默认静态文件目录中
COPY dist /usr/share/nginx/html

# 暴露80端口,允许外部访问
EXPOSE 80

# 启动nginx服务
CMD ["nginx", "-g", "daemon off;"]

3. 准备nginx.conf配置文件

server {
    listen 80;
    server_name localhost;

    location / {
        root /usr/share/nginx/html;
        try_files $uri $uri/ /index.html;
    }
}

4. 构建前端资源

$ npm run build

5. 使用docker构建镜像

$ docker build -t react-nginx .

5. 从构建的镜像启动一个容器

$ docker run -d -p 8080:80 react-nginx

6. 测试服务启动是否成功

$ curl locahost:8080

或者用浏览器访问 http://locahost:8080