將Vue項目打包成Docker鏡像部署主要分為以下幾個步驟:
1. Vue項目打包?
執行npm run build生成dist文件夾,包含靜態資源文件
注意檢查index.html中資源引用路徑是否正確(避免絕對路徑問題)
2. 編寫Dockerfile
Copy Code
FROM nginx:latest
COPY dist/ /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
3. 構建鏡像?
docker build -t vue-app .?
4. 運行容器?
docker run -d -p 8080:80 --name vue-container vue-app
5. 高級配置(可選)?
- 自定義nginx配置:添加nginx.conf文件并COPY到/etc/nginx/nginx.conf
- 多環境配置:通過.env文件區分開發/測試/生產環境
- 使用docker-compose管理容器
完整示例項目結構:
- dist/ (Vue打包輸出)
- Dockerfile
- nginx.conf (可選自定義配置)
訪問方式:http://localhost:8080(端口號根據實際映射調整)
樣例
以下是實現Vue項目Docker部署時自定義Nginx配置的完整方案:
1. 首先創建自定義nginx.conf文件(推薦放在項目根目錄下):
worker_processes 1;events {worker_connections 1024;
}http {include mime.types;default_type application/octet-stream;sendfile on;keepalive_timeout 65;server {listen 80;server_name localhost;location / {root /usr/share/nginx/html;index index.html index.htm;try_files $uri $uri/ /index.html;}error_page 500 502 503 504 /50x.html;location = /50x.html {root /usr/share/nginx/html;}}
}
2. 修改后的Dockerfile配置:
Dockerfile
nginx:latest
COPY dist/ /usr/share/nginx/html
COPY nginx.conf /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
關鍵點說明:
- try_files配置解決Vue路由history模式404問題
- 配置了錯誤頁面處理
- 使用COPY指令將配置文件覆蓋默認配置
- 保持80端口暴露
構建命令不變:docker build -t vue-app . && docker run -p 8080:80 vue-app