使用容器进行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.docker.com/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.docker.com/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.docker.com/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. 打开浏览器并验证应用程序是否在 http://localhost:3000运行。

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

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

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

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

    $ docker compose up --build
    
  16. 刷新 http://localhost:3000 在你的浏览器中,并验证待办事项是否持久化,即使在容器被移除并再次运行后。

配置并运行开发容器

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

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

更新您的Dockerfile以进行开发

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

与其为生产环境创建一个Dockerfile,再为开发环境创建另一个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

打开浏览器并验证应用程序是否在 http://localhost:3000运行。

现在,您本地机器上应用程序源文件的任何更改将立即反映在运行的容器中。

在IDE或文本编辑器中打开docker-nodejs-sample/src/static/js/app.js,并将第109行的按钮文本从Add Item更新为Add

+                         {submitting ? 'Adding...' : 'Add'}
-                         {submitting ? 'Adding...' : 'Add Item'}

刷新 http://localhost:3000 在您的浏览器中,并验证更新的文本是否出现。

您现在可以将检查器客户端连接到您的应用程序进行调试。有关检查器客户端的更多详细信息,请参阅Node.js 文档

摘要

在本节中,您了解了如何设置Compose文件以添加模拟数据库并持久化数据。您还学习了如何创建多阶段Dockerfile并为开发设置绑定挂载。

相关信息:

下一步

在下一节中,您将学习如何使用Docker运行单元测试。