使用容器進行 Angular 開發
先決條件
概述
在本節中,你將學習如何使用 Docker Compose 為容器化的 Angular 應用程式設定生產和開發環境。此設定允許你透過 Nginx 提供靜態生產版本,並使用帶有 Compose Watch 的即時過載開發伺服器在容器內高效開發。
你將學習如何
- 為生產和開發配置單獨的容器
- 在開發中使用 Compose Watch 啟用自動檔案同步
- 即時除錯和即時預覽更改,無需手動重新構建
自動更新服務(開發模式)
使用 Compose Watch 自動將原始檔更改同步到容器化開發環境。這提供了無縫、高效的開發體驗,無需手動重啟或重建容器。
步驟 1:建立開發 Dockerfile
在專案根目錄中建立一個名為 Dockerfile.dev
的檔案,其內容如下
# =========================================
# Stage 1: Development - Angular Application
# =========================================
# Define the Node.js version to use (Alpine for a small footprint)
ARG NODE_VERSION=22.14.0-alpine
# Set the base image for development
FROM node:${NODE_VERSION} AS dev
# Set environment variable to indicate development mode
ENV NODE_ENV=development
# Set the working directory inside the container
WORKDIR /app
# Copy only the dependency files first to optimize Docker caching
COPY package.json package-lock.json ./
# Install dependencies using npm with caching to speed up subsequent builds
RUN --mount=type=cache,target=/root/.npm npm install
# Copy all application source files into the container
COPY . .
# Expose the port Angular uses for the dev server (default is 4200)
EXPOSE 4200
# Start the Angular dev server and bind it to all network interfaces
CMD ["npm", "start", "--", "--host=0.0.0.0"]
此檔案使用開發伺服器為你的 Angular 應用程式設定一個輕量級開發環境。
步驟 2:更新你的 compose.yaml
檔案
開啟你的 compose.yaml
檔案並定義兩個服務:一個用於生產 (angular-prod
),一個用於開發 (angular-dev
)。
以下是 Angular 應用程式的示例配置
services:
angular-prod:
build:
context: .
dockerfile: Dockerfile
image: docker-angular-sample
ports:
- "8080:8080"
angular-dev:
build:
context: .
dockerfile: Dockerfile.dev
ports:
- "4200:4200"
develop:
watch:
- action: sync
path: .
target: /app
angular-prod
服務使用 Nginx 構建並提供靜態生產應用。angular-dev
服務執行你的 Angular 開發伺服器,具有即時重新載入和熱模組替換功能。watch
觸發與 Compose Watch 的檔案同步。
注意有關更多詳細資訊,請參閱官方指南:使用 Compose Watch。
完成上述步驟後,你的專案目錄現在應該包含以下檔案
├── docker-angular-sample/
│ ├── Dockerfile
│ ├── Dockerfile.dev
│ ├── .dockerignore
│ ├── compose.yaml
│ ├── nginx.conf
│ └── README.Docker.md
步驟 4:啟動 Compose Watch
從專案根目錄執行以下命令以在監視模式下啟動容器
$ docker compose watch angular-dev
步驟 5:使用 Angular 測試 Compose Watch
要驗證 Compose Watch 是否正常工作
在文字編輯器中開啟
src/app/app.component.html
檔案。找到以下行
<h1>Docker Angular Sample Application</h1>
更改為
<h1>Hello from Docker Compose Watch</h1>
儲存檔案。
在瀏覽器中開啟 https://:4200。
你應該會立即看到更新的文字出現,而無需手動重建容器。這確認了檔案監視和自動同步按預期工作。
摘要
在本節中,你使用 Docker 和 Docker Compose 為你的 Angular 應用程式設定了完整的開發和生產工作流。
以下是你完成的工作
- 建立了
Dockerfile.dev
以簡化帶有熱過載的本地開發 - 在你的
compose.yaml
檔案中定義了單獨的angular-dev
和angular-prod
服務 - 使用 Compose Watch 啟用了即時檔案同步,以獲得更流暢的開發體驗
- 透過修改和預覽元件驗證了即時更新的無縫工作
透過此設定,你現在可以完全在容器內構建、執行和迭代你的 Angular 應用,在不同環境中實現高效和一致。
相關資源
透過這些指南,加深你的知識並改進你的容器化開發工作流
- 使用 Compose Watch – 在開發過程中自動同步源更改
- 多階段構建 – 建立高效、生產就緒的 Docker 映象
- Dockerfile 最佳實踐 – 編寫乾淨、安全和最佳化的 Dockerfile。
- Compose 檔案參考 – 學習在
compose.yaml
中配置服務的完整語法和可用選項。 - Docker 卷 – 在容器執行之間持久化和管理資料
後續步驟
在下一節中,你將學習如何在 Docker 容器中執行 Angular 應用程式的單元測試。這確保了跨所有環境的一致測試,並消除了對本地機器設定的依賴。