跳至主要内容

1 篇文章 含有標籤「deployment」

檢視所有標籤

將多個 Nx Apps 部署到同一個 Nginx 下

· 閱讀時間約 3 分鐘

Nx monorepo 內通常包含多個前端或後端應用,例如:

apps/
app1/
app2/
app3/

透過 Nx build 後,你會得到:

dist/apps/app1/
dist/apps/app2/
dist/apps/app3/

本篇文章將教你如何把這些 apps 同時部署到同一個 Nginx 下,並使用不同路徑或不同子網域。


方法 A:使用不同路徑(最常見)

例如:

Nginx 設定

server {
listen 80;
server_name example.com;

location /app1/ {
alias /usr/share/nginx/html/app1/;
try_files $uri $uri/ /app1/index.html;
}

location /app2/ {
alias /usr/share/nginx/html/app2/;
try_files $uri $uri/ /app2/index.html;
}
}

Angular / Nx Build 指令

nx build app1 --configuration production --base-href=/app1/
nx build app2 --configuration production --base-href=/app2/

部署的資料夾結構

/usr/share/nginx/html/
app1/
app2/

方法 B:使用不同子網域

例如:

Nginx 設定

server {
server_name app1.example.com;
root /usr/share/nginx/html/app1;
try_files $uri $uri/ /index.html;
}

server {
server_name app2.example.com;
root /usr/share/nginx/html/app2;
try_files $uri $uri/ /index.html;
}

Angular / Nx Build 指令

由於每個 app 直接掛在根目錄(/),baseHref 設為 / 即可:

nx build app1 --configuration production --base-href=/
nx build app2 --configuration production --base-href=/

方法 C:透過 Proxy Pass 導流到後端服務(API / SSR / Node / NodeJS)

如果你的 Nx monorepo 中包含後端服務(例如 NodeJS API),你可以使用 proxy_pass: 讓 Nginx 將 /api 相關請求導向後端 server。

Nginx Proxy Pass 設定範例

server {
listen 80;
server_name example.com;

# 前端 Angular App
location / {
root /usr/share/nginx/html/app1;
try_files $uri $uri/ /index.html;
}

# API Proxy
location /api/ {
proxy_pass http://localhost:3333/; # Nx serve / NodeJS 的 API port
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}

常見 Proxy Pass 場景

  1. Nx + Angular 前端 + NodeJS API

    • / → 前端
    • /api → 後端(NodeJS)
  2. 多後端服務(微服務結構)

    • /auth → Auth service
    • /order → Order service
    • /payment → Payment service

Nx + NodeJS 服務常用指令

nx serve api
nx build api

常見問題(FAQ)

為什麼重新整理會出現 404?

SPA(如 Angular)本身沒有真正的路徑,因此 Nginx 需要設定:

try_files $uri $uri/ /index.html;

這會讓所有路徑回到 Angular 的 router 處理。

Proxy Pass 無法連線?

檢查:

  • 後端 port 是否正確(如 3333
  • 後端是否允許來自 localhost 的 request
  • Nginx 有沒有加 proxy_set_header Host $host
  • 是否需要 HTTPS → HTTP 的 proxy_redirect off;

總結

你可以透過三種方式把多個 Nx apps 與後端部署在同一個 Nginx:

  1. 不同路徑(最常見、單一 domain)
  2. 不同子網域(乾淨、好管理)
  3. Proxy Pass 導後端 API(前後端整合最佳解)

只要正確設定:

  • Nginx alias/root
  • Angular baseHref
  • try_files
  • proxy_pass(如有後端 API)

即可達成完整的 Nx monorepo 部署架構。