開(kāi)發(fā)到部署,親力親為
當(dāng)我們開(kāi)發(fā)一個(gè)單頁(yè)面應(yīng)用時(shí),執(zhí)行完構(gòu)建后
npm run build
會(huì)生成一個(gè) index.html 在 dist 目錄,那怎么把這個(gè) index.html 部署到服務(wù)器上呢?
目錄結(jié)構(gòu)
配置 Nginx
挑幾點(diǎn)配置講講,先是 Gzip 壓縮資源,以節(jié)省帶寬和提高瀏覽器加載速度
雖然 Webpack 已經(jīng)支持在構(gòu)建時(shí)就生成 .gz 壓縮包,但也可以通過(guò) Nginx 來(lái)啟用
gzip on;gzip_disable "msie6";# 0-9 等級(jí),級(jí)別越高,壓縮包越小,但對(duì)服務(wù)器性能要求也高gzip_comp_level 9;gzip_min_length 100;# Gzip 不支持壓縮圖片,我們只需要壓縮前端資源gzip_types text/css application/javascript;
再就是服務(wù)端口的配置,將 API 反向代理到后端服務(wù)
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; }}完整配置長(zhǎng)這樣
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
這里簡(jiǎn)單一點(diǎn),基于基礎(chǔ)鏡像,拷貝我們寫(xiě)好的 nginx.conf 和 index.html 到鏡像內(nèi)
FROM nginx:alpineCOPY nginx.conf /etc/nginx/nginx.confCOPY dist /usr/share/nginx/html
編寫(xiě) Makefile
完成了上面的準(zhǔn)備,就可以編寫(xiě)命令來(lái)執(zhí)行鏡像的打包了
先給鏡像取個(gè)名稱和端口號(hào)
APP_NAME = spa_nginx_dockerPORT = 8080
通過(guò) build 來(lái)打包鏡像
build: cp docker/Dockerfile . cp docker/nginx.conf . docker build -t $(APP_NAME) . rm Dockerfile rm nginx.conf
通過(guò) deploy 來(lái)啟動(dòng)鏡像
deploy: docker run -d -it -p=$(PORT):$(PORT) --name="$(APP_NAME)" $(APP_NAME)
最后還有個(gè) stop 來(lái)停止和清理鏡像
stop: docker stop $(APP_NAME) docker rm $(APP_NAME) docker rmi $(APP_NAME)
完整配置長(zhǎng)這樣
APP_NAME = spa_nginx_dockerPORT = 8080build: cp docker/Dockerfile . cp docker/nginx.conf . docker build -t $(APP_NAME) . rm Dockerfile rm nginx.confdeploy: 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)
完整命令長(zhǎng)這樣
# 靜態(tài)資源構(gòu)建npm run build# 鏡像打包make build# 停止并刪除舊鏡像(首次可忽略)make stop# 鏡像啟動(dòng)make deploy
總結(jié)
目前的部署方法相對(duì)簡(jiǎn)單,后續(xù)會(huì)加入基礎(chǔ)鏡像和鏡像倉(cāng)庫(kù)的使用,先去前面探探路
新聞熱點(diǎn)
疑難解答
圖片精選