尝试 Docker + Nginx 部署单页应用
生活随笔
收集整理的這篇文章主要介紹了
尝试 Docker + Nginx 部署单页应用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
開發到部署,親力親為
當我們開發一個單頁面應用時,執行完構建后
npm run build會生成一個 index.html 在 dist 目錄,那怎么把這個 index.html 部署到服務器上呢?
目錄結構
- dist/:前端構建完的靜態文件
- docker/:鏡像所需的配置文件
配置 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:alpineCOPY 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 Dockerfilerm 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 = 8080build:cp docker/Dockerfile .cp docker/nginx.conf .docker build -t $(APP_NAME) .rm Dockerfilerm 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)完整命令長這樣
# 靜態資源構建 npm run build# 鏡像打包 make build# 停止并刪除舊鏡像(首次可忽略) make stop# 鏡像啟動 make deploy總結
目前的部署方法相對簡單,后續會加入基礎鏡像和鏡像倉庫的使用,先去前面探探路
總結
以上是生活随笔為你收集整理的尝试 Docker + Nginx 部署单页应用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 你可能过于高估了机器学习算法能力,带你解
- 下一篇: Nginx 0.8.5版本access.