溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

嘗試Docker+Nginx部署單頁應用方法

發布時間:2020-10-13 11:15:20 來源:腳本之家 閱讀:255 作者:邱鴻彬 欄目:服務器

開發到部署,親力親為

當我們開發一個單頁面應用時,執行完構建后

npm run build

會生成一個 index.html 在 dist 目錄,那怎么把這個 index.html 部署到服務器上呢?

目錄結構

  • dist/:前端構建完的靜態文件
  • docker/:鏡像所需的配置文件

嘗試Docker+Nginx部署單頁應用方法

配置 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

總結

目前的部署方法相對簡單,后續會加入基礎鏡像和鏡像倉庫的使用,先去前面探探路

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女