當咱們開發一個單頁面應用時,執行完構建後javascript
npm run build
會生成一個 index.html 在 dist 目錄,那怎麼把這個 index.html 部署到服務器上呢?css
挑幾點配置講講,先是 Gzip 壓縮資源,以節省帶寬和提升瀏覽器加載速度html
雖然 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; } }
完整配置長這樣java
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; } } }
這裏簡單一點,基於基礎鏡像,拷貝咱們寫好的 nginx.conf 和 index.html 到鏡像內node
FROM nginx:alpine COPY nginx.conf /etc/nginx/nginx.conf COPY dist /usr/share/nginx/html
完成了上面的準備,就能夠編寫命令來執行鏡像的打包了nginx
先給鏡像取個名稱和端口號docker
APP_NAME = spa_nginx_docker PORT = 8080
經過 build 來打包鏡像npm
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
目前的部署方法相對簡單,後續會加入基礎鏡像和鏡像倉庫的使用,先去前面探探路