最近在學習Vue開發前端專案,跟著教程做了一個小專案,打算把寫好的Vue專案使用docker部署到阿里雲主機上去,使用華為CDN加速,記錄一下詳細的部署過程,供大家參考。
一、專案說明1. 整體架構圖
2. 環境描述
使用華為雲CDN對靜態資源進行分發和加速專案全部部署在阿里雲主機,使用Docker執行全站資源使用https加密訪問資料庫每日定時備份實現CICD持續整合與部署3. 部署效果
2. https證書申請
申請完成後根據要求,在雲解析DNS中配置相關的TXT記錄。3. Docker部署
將專案程式碼clone至本地,並上傳相關ssl證書,建立檔案[root@localhost opt]# tree /opt/docker//opt/docker/├── mysql├── nginx│ ├── ssl│ │ ├── shop.cuiliangblog.cn_chain.crt│ │ └── shop.cuiliangblog.cn_key.key│ └── vue_shop└── nodejs└── vue_shop_api# 將專案克隆到對應目錄下
5. 建立docker網路用於容器互聯
[root@localhost mysql]# cd /opt/docker/mysql/[root@localhost mysql]# docker pull mysql[root@localhost mysql]# docker run -p 3306:3306 --name mysql -v $PWD/conf:/etc/mysql/conf.d -v $PWD/logs:/logs -v $PWD/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123.com -d --network net --restart=always mysqldc36586b8f6fadcf945b2cae85a0e6e222f4b6548873a491d7d5522376e71b26[root@localhost mysql]# docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESdc36586b8f6f mysql "docker-entrypoint.s…" 6 seconds ago Up 4 seconds 0.0.0.0:3306->3306/tcp, 33060/tcp mysql
選項說明-p 3306:3306:將容器的 3306 埠對映到主機的 3306 埠。(如果不需要遠端訪問,則無需對映)
-v $PWD/conf:/etc/mysql/conf.d:將主機當前目錄下的 conf/my.cnf 掛載到容器的/etc/mysql/my.cnf。
-v $PWD/logs:/logs:將主機當前目錄下的logs 目錄掛載到容器的 /logs。
-v $PWD/data:/var/lib/mysql:將主機當前目錄下的data目錄掛載到容器的 /var/lib/mysql 。
-e MYSQL_ROOT_PASSWORD=123.com:初始化 root 使用者的密碼。
-d :後臺執行
--network net:使用自定義的net網路
--restart=always: 不管退出狀態碼是什麼,始終重啟容器
2. 進入容器登入資料庫
[root@localhost mysql]# docker exec -it mysql bashroot@66e5edff50d4:/# mysql -u root -pEnter password:Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 8Server version: 8.0.23 MySQL Community Server - GPLCopyright (c) 2000, 2021, Oracle and/or its affiliates.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql>
3. 建立資料庫
mysql> CREATE DATABASE shop CHARACTER SET utf8 COLLATE utf8_general_ci;Query OK, 1 row affected, 2 warnings (0.01 sec)mysql> show databases;+--------------------+| Database |+--------------------+| information_schema || mysql || performance_schema || shop || sys |+--------------------+5 rows in set (0.01 sec)
4. 建立使用者並授權
mysql> CREATE USER 'admin'@'%' IDENTIFIED BY '1234qwer';Query OK, 0 rows affected (0.01 sec)mysql> GRANT ALL PRIVILEGES ON shop.* TO 'admin'@'%';Query OK, 0 rows affected (0.01 sec)mysql> FLUSH PRIVILEGES;Query OK, 0 rows affected (0.00 sec)
5. 匯入資料
NodeJS專案資料庫存放地址:vue_shop_api/db/mydb.sql# 將sql檔案從主機複製到容器/tmp下[root@localhost mysql]# docker cp /opt/docker/nodejs/vue_shop_api/db/mydb.sql mysql:/tmp# 在mysql容器中執行匯入資料操作mysql> use shop;mysql> source /tmp/mydb.sql;mysql> show tables;+-------------------+| Tables_in_shop |+-------------------+| sp_attribute || sp_category || sp_consignee || sp_express || sp_goods || sp_goods_attr || sp_goods_cats || sp_goods_pics || sp_manager || sp_order || sp_order_goods || sp_permission || sp_permission_api || sp_report_1 || sp_report_2 || sp_report_3 || sp_role || sp_type || sp_user || sp_user_cart |+-------------------+20 rows in set (0.01 sec)
6. 測試驗證
透過--rm,建立一次性容器測試admin使用者是否能正常登入,--network net指定與mysql在同一個網路中[root@localhost mysql]# docker run -it --rm --network net mysql bashroot@450468c9b3b0:/# mysql -h mysql -u admin -pEnter password:Welcome to the MySQL monitor. Commands end with ; or \g.Your MySQL connection id is 10Server version: 8.0.23 MySQL Community Server - GPLCopyright (c) 2000, 2021, Oracle and/or its affiliates.Oracle is a registered trademark of Oracle Corporation and/or itsaffiliates. Other names may be trademarks of their respectiveowners.Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.mysql> show databases;+--------------------+| Database |+--------------------+| information_schema || shop |+--------------------+2 rows in set (0.00 sec)
四、NodeJS部署1. 修改連線資料庫的配置檔案
專案資料庫配置檔案路徑:vue_shop_api/config/default.json,根據實際情況修改db_config相關配置{"config_name" : "develop","jwt_config" : {"secretKey":"itcast","expiresIn":86400},"upload_config":{"baseURL":"http://127.0.0.1:8888","upload_ueditor":"uploads/ueditor","simple_upload_redirect":"http://127.0.0.1/reload"},"db_config" : {"protocol" : "mysql","host" : "mysql","database" : "shop","user" : "admin","password" : "1234qwer","port" : 3306}}
2. 編寫dockerfile並構建映象
透過檢視專案README可知,主要執行兩條命令安裝依賴:npm install
啟動專案 :node app.js
編寫dockerfile(dockerfile與專案資料夾在同一個目錄下),dockerfile的內容分別是:將專案程式碼複製到映象中,並指定工作目錄
安裝npm依賴庫
指定容器執行時監聽的網路埠
指定容器執行時的命令及引數
FROM nodeCOPY vue_shop_api /opt/vue_shop_apiWORKDIR /opt/vue_shop_api/RUN npm install --registry=https://registry.npm.taobao.orgEXPOSE 8888CMD ["node","app.js"]
執行構建映象命令
[root@localhost nodejs]# pwd/opt/docker/nodejs[root@localhost nodejs]# lsdockerfile vue_shop_api[root@localhost nodejs]# docker build -t shop_api:v1 .
3. 啟動容器
[root@localhost nodejs]# docker run --name shop_api -d --network net --restart=always shop_api:v1[root@localhost nodejs]# docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES6ba9359556d2 shop_api:v1 "docker-entrypoint.s…" 52 seconds ago Restarting (1) 7 seconds ago shop_api5075f372f88f mysql "docker-entrypoint.s…" 24 minutes ago Up 24 minutes 0.0.0.0:3306->3306/tcp, 33060/tcp mysql
log和配置檔案以及服務埠是否暴露根據需求自行選擇4. 修改mysql使用者認證方式
使用docker logs shop_api檢視日誌發現連線資料庫報錯,提示AUTH_MODE異常檢視使用者加密認證方式mysql> select user,plugin from mysql.user;+------------------+-----------------------+| user | plugin |+------------------+-----------------------+| admin | caching_sha2_password || root | caching_sha2_password || mysql.infoschema | caching_sha2_password || mysql.session | caching_sha2_password || mysql.sys | caching_sha2_password || root | caching_sha2_password |+------------------+-----------------------+6 rows in set (0.00 sec)
mysql8+預設使用了caching_sha2_password 方式認證加密,但是NodeJS並不支援,需要改為mysql_native_password方式認證
mysql> ALTER USER 'admin'@'%' IDENTIFIED WITH mysql_native_password BY '1234qwer';Query OK, 0 rows affected (0.01 sec)mysql> select user,plugin from mysql.user;+------------------+-----------------------+| user | plugin |+------------------+-----------------------+| admin | mysql_native_password || root | caching_sha2_password || mysql.infoschema | caching_sha2_password || mysql.session | caching_sha2_password || mysql.sys | caching_sha2_password || root | caching_sha2_password |+------------------+-----------------------+6 rows in set (0.00 sec)
重啟shop_api容器[root@localhost nodejs]# docker restart shop_api[root@localhost nodejs]# docker logs shop_api
此時日誌無異常輸出
4. 測試驗證
此次構建的映象包含兩個階段,分別是使用node映象編譯專案和使用nginx映象提供服務
1. dockerfile-編譯階段
專案配置檔案路徑:vue_shop/src/main-prod.js,根據實際情況修改axios.defaults.baseURL = "/api/private/v1/"配置即可,此處我們無需修改(如果想讓使用者直接訪問nodejs伺服器,此處改為nodejs請求api地址即可)此階段的dockerfile的內容如下:將專案程式碼複製到映象中,並指定工作目錄
安裝npm依賴庫並編譯專案生成打包檔案
FROM node AS build # AS指定別名,便於在執行階段透過別名操作,將編譯階段生成的打包檔案複製到執行映象中COPY vue_shop /opt/vue_shopWORKDIR /opt/vue_shopRUN npm install --registry=https://registry.npm.taobao.org && npm run build
編譯完後會在映象的/opt/vue_shop目錄下生成一個dist檔案的專案打包檔案2. dockerfile-執行階段
此階段的dockerfile內容如下:將編譯階段生成的/opt/vue_shop/dist檔案新增到映象中
將ssl證書新增到映象中
將自定義的配置檔案新增到映象中(配置ssl和location配置),替換預設nginx配置檔案
FROM nginxCOPY --from=build /opt/vue_shop/dist /opt/vue_shop/distCOPY nginx.conf /etc/nginx/nginx.confCOPY ssl /etc/sslCMD ["nginx", "-g","daemon off;"]
nginx.conf配置檔案如下,主要注意以下幾點
ssl證書路徑與dockerfile新增的ssl證書檔案路徑保持一致
location / 配置路徑與dockerfile新增的打包檔案路徑保持一致
location /api/private/v1/ 中的容器名稱與建立的nodejs容器名稱保持一致
gzip根據情況選擇性啟用
http跳轉到https可以使用return 301或者rewrite,推薦使用return 301
# For more information on configuration, see:# * Official English Documentation: http://nginx.org/en/docs/# * Official Russian Documentation: http://nginx.org/ru/docs/user root;worker_processes auto;error_log /var/log/nginx/error.log;pid /run/nginx.pid;# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.include /usr/share/nginx/modules/*.conf;events {worker_connections 1024;}http {log_format main '$remote_addr - $remote_user [$time_local] "$request" ''$status $body_bytes_sent "$http_referer" ''"$http_user_agent" "$http_x_forwarded_for"';access_log /var/log/nginx/access.log main;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;# Load modular configuration files from the /etc/nginx/conf.d directory.# See http://nginx.org/en/docs/ngx_core_module.html#include# for more information.include /etc/nginx/conf.d/*.conf;# http跳轉到httpsserver {listen 80;server_name shop.cuiliangblog.cn;return 301 https://$host$request_uri;}# vue_shop專案server {listen 443 ssl http2;server_name shop.cuiliangblog.cn;charset utf-8;ssl_certificate /etc/ssl/shop.cuiliangblog.cn_chain.crt;#證書路徑ssl_certificate_key /etc/ssl/shop.cuiliangblog.cn_key.key;#金鑰路徑ssl_protocols TLSv1 TLSv1.1 TLSv1.2;ssl_ciphers ECDHE-RSA-AES128-GCM-SHA256:HIGH:!aNULL:!MD5:!RC4:!DHE;ssl_prefer_server_ciphers on;ssl_session_cache shared:SSL:10m;ssl_session_timeout 10m;gzip on;gzip_buffers 32 4K;gzip_comp_level 6;gzip_min_length 100;gzip_types application/javascript text/css text/xml;gzip_disable "MSIE [1-6]\."; #配置禁用gzip條件,支援正則。此處表示ie6及以下不啟用gzip(因為ie低版本不支援)gzip_vary on;location / {root /opt/vue_shop/dist;}location /api/private/v1/ {proxy_pass http://shop_api:8888;}}}
3. 構建映象並執行容器
整個工作目錄結構[root@localhost nginx]# tree /opt/docker/nginx//opt/docker/nginx/├── dockerfile├── log├── nginx.conf├── ssl│ ├── shop.cuiliangblog.cn_chain.crt│ └── shop.cuiliangblog.cn_key.key└── vue_shop
完整的dockerfile檔案
FROM node AS buildCOPY vue_shop /opt/vue_shopWORKDIR /opt/vue_shopRUN npm install --registry=https://registry.npm.taobao.org && npm run buildFROM nginxCOPY --from=build /opt/vue_shop/dist /opt/vue_shop/distCOPY nginx.conf /etc/nginx/nginx.confCOPY ssl /etc/sslCMD ["nginx", "-g","daemon off;"]
構建名為vue_shop的映象
[root@localhost nginx]# docker build -t vue_shop:v1 .
執行容器,將nginx日誌掛載至主機log目錄下[root@localhost nginx]# docker run --name vue_shop -p 443:443 -p 80:80 -d --network net -v $PWD/log:/var/log/nginx --restart=always vue_shop:v1f934b7e522fe1652c848d0bf1fa877b05936a2aaafcace1e18b9fd9433d40c54[root@localhost nginx]# docker psCONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMESf934b7e522fe vue_shop:v1 "/docker-entrypoint.…" 7 seconds ago Up 5 seconds 0.0.0.0:80->80/tcp, 0.0.0.0:443->443/tcp vue_shop1b490fd2e447 shop_api:v1 "docker-entrypoint.s…" 37 minutes ago Up 37 minutes 8888/tcp shop_api5f180b407309 mysql "docker-entrypoint.s…" 10 hours ago Up 10 hours 0.0.0.0:3306->3306/tcp, 33060/tcp mysql
4. 訪問測試
至此,專案部署完畢六、CDN配置1. 華為雲CDN配置
登入華為雲控制檯——CDN——域名管理——新增域名域名新增完成後會得到一個CNAME解析配置https安全加速,並開啟https回源和強制跳轉https2. 阿里雲DNS雲解析配置
阿里雲控制檯——雲解析DNS——解析設定,將華為雲CDN加速域名填寫到記錄中3. 訪問測試
訪問發現此時請求的主機均為華為CDN伺服器