使用容器进行 Node.js 开发

先决条件

完成容器化 Node.js 应用程序

概述

在本节中,您将学习如何为容器化应用程序设置开发环境。这包括

  • 添加本地数据库并持久化数据
  • 配置容器以运行开发环境
  • 调试容器化应用程序

添加本地数据库并持久化数据

您可以使用容器设置本地服务,例如数据库。在本节中,您将更新 compose.yaml 文件以定义数据库服务和用于持久化数据的卷。

  1. 在 IDE 或文本编辑器中打开您的 compose.yaml 文件。

  2. 取消注释与数据库相关的指令。以下是更新后的 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.container.net.cn/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 文件参考

  3. 在 IDE 或文本编辑器中打开 src/persistence/postgres.js。您会注意到此应用程序使用 Postgres 数据库,并且需要一些环境变量才能连接到数据库。compose.yaml 文件尚未定义这些变量。

  4. 添加指定数据库配置的环境变量。以下是更新后的 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.container.net.cn/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
  5. 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.container.net.cn/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
  6. docker-nodejs-sample 目录中,创建一个名为 db 的目录。

  7. 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
  8. 在 IDE 或文本编辑器中打开 password.txt 文件,并指定您选择的密码。您的密码必须在一行中,没有额外的行。确保文件不包含任何换行符或其他隐藏字符。

  9. 确保保存您修改过的所有文件。

  10. 运行以下命令以启动您的应用程序。

    $ docker compose up --build
    
  11. 打开浏览器并验证应用程序是否在 https://:3000 运行。

  12. 向待办事项列表添加一些项目以测试数据持久性。

  13. 向待办事项列表添加一些项目后,在终端中按 ctrl+c 以停止您的应用程序。

  14. 在终端中,运行 docker compose rm 以删除您的容器。

    $ docker compose rm
    
  15. 再次运行 docker compose up 以运行您的应用程序。

    $ docker compose up --build
    
  16. 在浏览器中刷新 https://:3000,并验证待办事项即使在容器被移除并再次运行后仍然持久存在。

配置并运行开发容器

您可以使用绑定挂载将源代码挂载到容器中。容器可以立即看到您对代码所做的更改,只要您保存文件即可。这意味着您可以在容器中运行进程,例如 nodemon,这些进程会监视文件系统更改并对其做出响应。要了解有关绑定挂载的更多信息,请参阅存储概述

除了添加绑定挂载之外,您还可以配置 Dockerfile 和 compose.yaml 文件以安装开发依赖项和运行开发工具。

更新您的 Dockerfile 以进行开发

在 IDE 或文本编辑器中打开 Dockerfile。请注意,Dockerfile 未安装开发依赖项,也未运行 nodemon。您需要更新 Dockerfile 以安装开发依赖项并运行 nodemon。

您可以为生产环境和开发环境使用一个多阶段 Dockerfile,而不是为两者分别创建 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 文件。所有注释均已删除。

compose.yaml
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

运行开发容器并调试您的应用程序

运行以下命令以使用对 Dockerfilecompose.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 运行单元测试。

© . This site is unofficial and not affiliated with Kubernetes or Docker Inc.