使用容器進行 Node.js 開發
先決條件
概述
在本節中,您將學習如何為容器化應用程式設定開發環境。這包括
- 新增本地資料庫並持久化資料
- 配置容器以執行開發環境
- 除錯容器化應用程式
新增本地資料庫並持久化資料
您可以使用容器設定本地服務,例如資料庫。在本節中,您將更新 compose.yaml
檔案以定義資料庫服務和用於持久化資料的卷。
在 IDE 或文字編輯器中開啟您的
compose.yaml
檔案。取消註釋與資料庫相關的指令。以下是更新後的
compose.yaml
檔案。重要對於本節,在收到指示之前,請勿執行
docker compose up
。在中間點執行此命令可能會錯誤地初始化您的資料庫。compose.yaml# Comments are provided throughout this file to help you get started. # If you need more help, visit the Docker Compose reference guide at # https://docs.docker.net.tw/go/compose-spec-reference/ # Here the instructions define your application as a service called "server". # This service is built from the Dockerfile in the current directory. # You can add other services your application may depend on here, such as a # database or a cache. For examples, see the Awesome Compose repository: # https://github.com/docker/awesome-compose services: server: build: context: . environment: NODE_ENV: production ports: - 3000:3000 # The commented out section below is an example of how to define a PostgreSQL # database that your application can use. `depends_on` tells Docker Compose to # start the database before your application. The `db-data` volume persists the # database data between container restarts. The `db-password` secret is used # to set the database password. You must create `db/password.txt` and add # a password of your choosing to it before running `docker compose up`. depends_on: db: condition: service_healthy db: image: postgres restart: always user: postgres secrets: - db-password volumes: - db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=example - POSTGRES_PASSWORD_FILE=/run/secrets/db-password expose: - 5432 healthcheck: test: ["CMD", "pg_isready"] interval: 10s timeout: 5s retries: 5 volumes: db-data: secrets: db-password: file: db/password.txt
注意要了解有關 Compose 檔案中指令的更多資訊,請參閱Compose 檔案參考。
在 IDE 或文字編輯器中開啟
src/persistence/postgres.js
。您會注意到此應用程式使用 Postgres 資料庫,並且需要一些環境變數才能連線到資料庫。compose.yaml
檔案尚未定義這些變數。新增指定資料庫配置的環境變數。以下是更新後的
compose.yaml
檔案。compose.yaml# Comments are provided throughout this file to help you get started. # If you need more help, visit the Docker Compose reference guide at # https://docs.docker.net.tw/go/compose-spec-reference/ # Here the instructions define your application as a service called "server". # This service is built from the Dockerfile in the current directory. # You can add other services your application may depend on here, such as a # database or a cache. For examples, see the Awesome Compose repository: # https://github.com/docker/awesome-compose services: server: build: context: . environment: NODE_ENV: production POSTGRES_HOST: db POSTGRES_USER: postgres POSTGRES_PASSWORD_FILE: /run/secrets/db-password POSTGRES_DB: example ports: - 3000:3000 # The commented out section below is an example of how to define a PostgreSQL # database that your application can use. `depends_on` tells Docker Compose to # start the database before your application. The `db-data` volume persists the # database data between container restarts. The `db-password` secret is used # to set the database password. You must create `db/password.txt` and add # a password of your choosing to it before running `docker compose up`. depends_on: db: condition: service_healthy db: image: postgres restart: always user: postgres secrets: - db-password volumes: - db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=example - POSTGRES_PASSWORD_FILE=/run/secrets/db-password expose: - 5432 healthcheck: test: ["CMD", "pg_isready"] interval: 10s timeout: 5s retries: 5 volumes: db-data: secrets: db-password: file: db/password.txt
在
server
服務下新增secrets
部分,以便您的應用程式安全地處理資料庫密碼。以下是更新後的compose.yaml
檔案。compose.yaml# Comments are provided throughout this file to help you get started. # If you need more help, visit the Docker Compose reference guide at # https://docs.docker.net.tw/go/compose-spec-reference/ # Here the instructions define your application as a service called "server". # This service is built from the Dockerfile in the current directory. # You can add other services your application may depend on here, such as a # database or a cache. For examples, see the Awesome Compose repository: # https://github.com/docker/awesome-compose services: server: build: context: . environment: NODE_ENV: production POSTGRES_HOST: db POSTGRES_USER: postgres POSTGRES_PASSWORD_FILE: /run/secrets/db-password POSTGRES_DB: example ports: - 3000:3000 # The commented out section below is an example of how to define a PostgreSQL # database that your application can use. `depends_on` tells Docker Compose to # start the database before your application. The `db-data` volume persists the # database data between container restarts. The `db-password` secret is used # to set the database password. You must create `db/password.txt` and add # a password of your choosing to it before running `docker compose up`. depends_on: db: condition: service_healthy secrets: - db-password db: image: postgres restart: always user: postgres secrets: - db-password volumes: - db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=example - POSTGRES_PASSWORD_FILE=/run/secrets/db-password expose: - 5432 healthcheck: test: ["CMD", "pg_isready"] interval: 10s timeout: 5s retries: 5 volumes: db-data: secrets: db-password: file: db/password.txt
在
docker-nodejs-sample
目錄中,建立一個名為db
的目錄。在
db
目錄中,建立一個名為password.txt
的檔案。此檔案將包含您的資料庫密碼。您的
docker-nodejs-sample
目錄中現在應至少包含以下內容。├── docker-nodejs-sample/ │ ├── db/ │ │ └── password.txt │ ├── spec/ │ ├── src/ │ ├── .dockerignore │ ├── .gitignore │ ├── compose.yaml │ ├── Dockerfile │ ├── package-lock.json │ ├── package.json │ └── README.md
在 IDE 或文字編輯器中開啟
password.txt
檔案,並指定您選擇的密碼。您的密碼必須在一行中,沒有額外的行。確保檔案不包含任何換行符或其他隱藏字元。確保儲存您修改過的所有檔案。
執行以下命令以啟動您的應用程式。
$ docker compose up --build
開啟瀏覽器並驗證應用程式是否在 https://:3000 執行。
向待辦事項列表新增一些專案以測試資料永續性。
向待辦事項列表新增一些專案後,在終端中按
ctrl+c
以停止您的應用程式。在終端中,執行
docker compose rm
以刪除您的容器。$ docker compose rm
再次執行
docker compose up
以執行您的應用程式。$ docker compose up --build
在瀏覽器中重新整理 https://:3000,並驗證待辦事項即使在容器被移除並再次執行後仍然持久存在。
配置並執行開發容器
您可以使用繫結掛載將原始碼掛載到容器中。容器可以立即看到您對程式碼所做的更改,只要您儲存檔案即可。這意味著您可以在容器中執行程序,例如 nodemon,這些程序會監視檔案系統更改並對其做出響應。要了解有關繫結掛載的更多資訊,請參閱儲存概述。
除了新增繫結掛載之外,您還可以配置 Dockerfile 和 compose.yaml
檔案以安裝開發依賴項和執行開發工具。
更新您的 Dockerfile 以進行開發
在 IDE 或文字編輯器中開啟 Dockerfile。請注意,Dockerfile 未安裝開發依賴項,也未執行 nodemon。您需要更新 Dockerfile 以安裝開發依賴項並執行 nodemon。
您可以為生產環境和開發環境使用一個多階段 Dockerfile,而不是為兩者分別建立 Dockerfile。
將 Dockerfile 更新為以下多階段 Dockerfile。
# syntax=docker/dockerfile:1
ARG NODE_VERSION=18.0.0
FROM node:${NODE_VERSION}-alpine as base
WORKDIR /usr/src/app
EXPOSE 3000
FROM base as dev
RUN --mount=type=bind,source=package.json,target=package.json \
--mount=type=bind,source=package-lock.json,target=package-lock.json \
--mount=type=cache,target=/root/.npm \
npm ci --include=dev
USER node
COPY . .
CMD npm run dev
FROM base as prod
RUN --mount=type=bind,source=package.json,target=package.json \
--mount=type=bind,source=package-lock.json,target=package-lock.json \
--mount=type=cache,target=/root/.npm \
npm ci --omit=dev
USER node
COPY . .
CMD node src/index.js
在 Dockerfile 中,您首先為 FROM node:${NODE_VERSION}-alpine
語句新增標籤 as base
。這允許您在其他構建階段引用此構建階段。接下來,您新增一個標記為 dev
的新構建階段,以安裝您的開發依賴項並使用 npm run dev
啟動容器。最後,您新增一個標記為 prod
的階段,該階段省略了開發依賴項並使用 node src/index.js
執行您的應用程式。要了解有關多階段構建的更多資訊,請參閱多階段構建。
接下來,您需要更新 Compose 檔案以使用新階段。
更新您的 Compose 檔案以進行開發
要使用 Compose 執行 dev
階段,您需要更新您的 compose.yaml
檔案。在 IDE 或文字編輯器中開啟您的 compose.yaml
檔案,然後新增 target: dev
指令以從多階段 Dockerfile 中定位 dev
階段。
此外,為繫結掛載向伺服器服務新增一個新卷。對於此應用程式,您將把本地機器上的 ./src
掛載到容器中的 /usr/src/app/src
。
最後,釋出埠 9229
以進行除錯。
以下是更新後的 Compose 檔案。所有註釋均已刪除。
services:
server:
build:
context: .
target: dev
ports:
- 3000:3000
- 9229:9229
environment:
NODE_ENV: production
POSTGRES_HOST: db
POSTGRES_USER: postgres
POSTGRES_PASSWORD_FILE: /run/secrets/db-password
POSTGRES_DB: example
depends_on:
db:
condition: service_healthy
secrets:
- db-password
volumes:
- ./src:/usr/src/app/src
db:
image: postgres
restart: always
user: postgres
secrets:
- db-password
volumes:
- db-data:/var/lib/postgresql/data
environment:
- POSTGRES_DB=example
- POSTGRES_PASSWORD_FILE=/run/secrets/db-password
expose:
- 5432
healthcheck:
test: ["CMD", "pg_isready"]
interval: 10s
timeout: 5s
retries: 5
volumes:
db-data:
secrets:
db-password:
file: db/password.txt
執行開發容器並除錯您的應用程式
執行以下命令以使用對 Dockerfile
和 compose.yaml
檔案的新更改來執行您的應用程式。
$ docker compose up --build
開啟瀏覽器並驗證應用程式是否在 https://:3000 執行。
您對本地機器上應用程式原始檔的任何更改現在將立即反映在執行中的容器中。
在 IDE 或文字編輯器中開啟 docker-nodejs-sample/src/static/js/app.js
,並將第 109 行的按鈕文字從 Add Item
更新為 Add
。
+ {submitting ? 'Adding...' : 'Add'}
- {submitting ? 'Adding...' : 'Add Item'}
在瀏覽器中重新整理 https://:3000,並驗證更新後的文字是否出現。
您現在可以將檢查器客戶端連線到您的應用程式進行除錯。有關檢查器客戶端的更多詳細資訊,請參閱 Node.js 文件。
摘要
在本節中,您瞭解瞭如何設定 Compose 檔案以新增模擬資料庫並持久化資料。您還學習瞭如何建立多階段 Dockerfile 並設定繫結掛載以進行開發。
相關資訊
後續步驟
在下一節中,您將學習如何使用 Docker 執行單元測試。