这篇文章主要介绍“Docker+Nginx怎么部署单页应用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“Docker+Nginx怎么部署单页应用”文章能帮助大家解决问题。
开发到部署,亲力亲为
npm run build
会生成一个 index.html 在 dist 目录,那怎么把这个 index.html 部署到服务器上呢?
目录结构
配置 Nginx
挑几点配置讲讲,先是 gzip 压缩资源,以节省带宽和提高浏览器加载速度
虽然 webpack 已经支持在构建时就生成 .gz 压缩包,但也可以通过 Nginx 来启用
gzip on; gzip_disable "msie6"; # 0-9 等级,级别越高,压缩包越小,但对服务器性能要求也高 gzip_comp_level 9; gzip_min_length 100; # gzip 不支持压缩图片,我们只需要压缩前端资源 gzip_types text/css application/javascript;
再就是服务端口的配置,将 api 反向代理到后端服务
server { listen 8080; server_name www.frontend.com; root /usr/share/Nginx/html/; location / { index index.html index.htm; try_files $uri $uri/ /index.html; # 禁止缓存 html,以保证引用最新的 css 和 js 资源 expires -1; } location /api/v1 { proxy_pass http://backend.com; } }
完整配置长这样
worker_processes 1; events { worker_connections 1024; } http { ## # basic settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; include /etc/Nginx/mime.types; default_type application/octet-stream; ## # logging settings ## access_log /var/log/Nginx/access.log; error_log /var/log/Nginx/error.log; ## # gzip settings ## gzip on; gzip_disable "msie6"; gzip_comp_level 9; gzip_min_length 100; gzip_types text/css application/javascript; server { listen 8080; server_name www.frontend.com; root /usr/share/Nginx/html/; location / { index index.html index.htm; try_files $uri $uri/ /index.html; expires -1; } location /api/v1 { proxy_pass http://backend.com; } } }
配置 docker
这里简单一点,基于基础镜像,拷贝我们写好的 Nginx.conf 和 index.html 到镜像内
from Nginx:alpine copy Nginx.conf /etc/Nginx/Nginx.conf copy dist /usr/share/Nginx/html
编写 makefile
完成了上面的准备,就可以编写命令来执行镜像的打包了
先给镜像取个名称和端口号
app_name = spa_Nginx_docker port = 8080
通过 build 来打包镜像
build: cp docker/dockerfile . cp docker/Nginx.conf . docker build -t $(app_name) . rm dockerfile rm Nginx.conf
通过 deploy 来启动镜像
deploy: docker run -d -it -p=$(port):$(port) --name="$(app_name)" $(app_name)
最后还有个 stop 来停止和清理镜像
stop: docker stop $(app_name) docker rm $(app_name) docker rmi $(app_name)
完整配置长这样
app_name = spa_Nginx_docker port = 8080 build: cp docker/dockerfile . cp docker/Nginx.conf . docker build -t $(app_name) . rm dockerfile rm Nginx.conf deploy: docker run -d -it -p=$(port):$(port) --name="$(app_name)" $(app_name) stop: docker stop $(app_name) docker rm $(app_name) docker rmi $(app_name)
完整命令长这样
# 静态资源构建 npm run build # 镜像打包 make build # 停止并删除旧镜像(首次可忽略) make stop # 镜像启动 make deploy
关于“Docker+Nginx怎么部署单页应用”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识,可以关注编程之家行业资讯频道,小编每天都会为大家更新不同的知识点。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。