![eec0739ca046a534215ad9be4b5ace0a.png](https://i-blog.csdnimg.cn/blog_migrate/676923964ebdc6437681b7bec6931f6e.png)
在上一篇文章里,我们学习了Docker常用的命令和基本操作,现在可以开始实战了。
单页应用
前端工作中最常见的就是单页应用了。我们首先用create-react-app
快速创建一个应用
npm i create-react-app -g
create-react-app react-app
cd react-app
npm run start
可以看见正常启动的页面。
打包试一下
npm run build
可以看到本地生成了一个build目录,这就是最后线上运行的代码。
我们先在本地运行下build目录看看
npm i http-server -g
http-server -p 4444 ./build
访问 http://localhost:4444 即可看到打包后的页面
单页应用Docker化
在react-app
目录下新建Dockerfile
.dockerignore
和nginx.conf
.dockerignore
node_modules
build
dockerignore
指定了哪些文件不需要被拷贝进镜像里,类似.gitignore
。
我们知道单页应用的路由一般都被js托管,所以对于nginx需要特别配置
nginx.conf
server {
listen 80;
server_name localhost;
location / {
root /app/build; # 打包的路径
index index.html index.htm;
try_files $uri $uri/ /index.html; # 防止重刷新返回404
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root /usr/share/nginx/html;
}
}
Dockerfile
# 基于node11
FROM node:11
# 设置环境变量
ENV PROJECT_ENV production
ENV NODE_ENV production
# 安装nginx
RUN apt-get update && apt-get install -y nginx
# 把 package.json package-lock.json 复制到/app目录下
# 为了npm install可以缓存
COPY package*.json /app/
# 切换到app目录
WORKDIR /app
# 安装依赖
RUN npm install --registry=https://registry.npm.taobao.org
# 把所有源代码拷贝到/app
COPY . /app
# 打包构建
RUN npm run build
# 拷贝配置文件到nginx
COPY nginx.conf /etc/nginx/conf.d/default.conf
EXPOSE 80
# 启动nginx,关闭守护式运行,否则容器启动后会立刻关闭
CMD ["nginx", "-g", "daemon off;"]
需要特别注意的是: