開發到部署,親力親為
當我們開發一個單頁面應用時,執行完構建后
npm?run?build
會生成一個 index.html 在 dist 目錄,那怎么把這個 index.html 部署到服務器上呢?
目錄結構
-
dist/:前端構建完的靜態文件
-
docker/:鏡像所需的配置文件
配置 nginx
挑幾點配置講講,先是 gzip 壓縮資源,以節省帶寬和提高瀏覽器加載速度
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
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END