Настройка Docker для Nest.js

В этой статье мы настроим Docker для приложения Nest.js в режиме монорепозитория с поддержкой rest, graphql, cron и microservices.

Данная статья является частью серии статей по Nest.js:

Введение

Для начала нужно инициализировать docker, для этого в корне проекта нужно выполнить команду:

docker init

После этого в корне проекта появятся файлы:

.dockerignore
Dockerfile
compose.yaml

Dockerfile

В файле Dockerfile мы опишем как будет собираться наше приложение. Добавил сборку для всех приложений, которые мы описали в предыдущей статье. Добавим crontab для приложения cron.

# syntax=docker/dockerfile:1

# Comments are provided throughout this file to help you get started.
# If you need more help, visit the Dockerfile reference guide at
# https://docs.docker.com/engine/reference/builder/

ARG NODE_VERSION=18.12.1

################################################################################
# Use node image for base image for all stages.
FROM node:${NODE_VERSION}-alpine as base

# Set working directory for all build stages.
WORKDIR /usr/src/app


################################################################################
# Create a stage for installing production dependecies.
FROM base as deps

# Download dependencies as a separate step to take advantage of Docker's caching.
# Leverage a cache mount to /root/.yarn to speed up subsequent builds.
# Leverage bind mounts to package.json and yarn.lock to avoid having to copy them
# into this layer.
RUN --mount=type=bind,source=package.json,target=package.json \
    --mount=type=bind,source=yarn.lock,target=yarn.lock \
    --mount=type=cache,target=/root/.yarn \
    yarn install --production --frozen-lockfile

################################################################################
# Create a stage for building the application.
FROM deps as build

# Download additional development dependencies before building, as some projects require
# "devDependencies" to be installed to build. If you don't need this, remove this step.
RUN --mount=type=bind,source=package.json,target=package.json \
    --mount=type=bind,source=yarn.lock,target=yarn.lock \
    --mount=type=cache,target=/root/.yarn \
    yarn install --frozen-lockfile

# Copy the rest of the source files into the image.
COPY . .
# Run the build script.
RUN yarn run build rest
RUN yarn run build gql
RUN yarn run build cli
RUN yarn run build srv

################################################################################
# Create a new stage to run the application with minimal runtime dependencies
# where the necessary files are copied from the build stage.
FROM base as final

# Use production node environment by default.
ENV NODE_ENV production

# Run the application as a non-root user.
USER node

# Copy package.json so that package manager commands can be used.
COPY package.json .

# Copy the production dependencies from the deps stage and also
# the built application from the build stage into the image.
COPY --from=deps /usr/src/app/node_modules ./node_modules
COPY --from=build /usr/src/app/dist ./dist
COPY crontab /etc/crontabs/node

# Expose the port that the application listens on.
EXPOSE 3000

# Run the application.
CMD node dist/apps/rest/main.js

compose.yaml

В файле compose.yaml мы опишем как будет запускаться наше приложение. Добавил запуск для всех приложений, которые мы описали в предыдущей статье.

name: nestjs-monorepa-starter
services:

  rest:
    build:
      context: .
    command: ["node", "dist/apps/rest/main.js"]
    init: true
    env_file:
      - .env.docker
    ports:
      - 3001:3001

  gql:
    build:
      context: .
    command: ["node", "dist/apps/gql/main.js"]
    init: true
    env_file:
      - .env.docker
    ports:
      - 3000:3000

  srv:
    build:
      context: .
    command: ["node", "dist/apps/srv/main.js"]
    init: true
    env_file:
      - .env.docker
  
  cron:
    build:
      context: .
    command: ["crond", "-f", "-l", "8", "-d", "8", "-L", "/dev/stdout"]
    init: true
    user: root
    profiles:
      - cron
    env_file:
      - .env.docker

networks:
  default:
    name: nestjs-monorepa-starter
    external: true

.dockerignore

В файле .dockerignore мы опишем какие файлы не нужно копировать в контейнер.

node_modules

crontab

В файле crontab мы опишем какие задачи нужно запускать в cron.

* * * * * /usr/local/bin/node /usr/src/app/dist/apps/cron/main.js

.env.docker

В файле .env.docker мы опишем переменные окружения для docker.

NODE_ENV=production

Запуск

Для запуска приложения в режиме монорепозитория нужно выполнить команду:

docker compose up

После этого приложение будет доступно по адресу http://localhost:3000

Заключение

В этой статье мы настроили Docker для приложения Nest.js в режиме монорепозитория с поддержкой rest, graphql, cron и microservices.

В следующей статье мы настроим Docker Swarm для приложения Nest.js в режиме монорепозитория с поддержкой rest, graphql, cron и microservices.

Исходный код

Исходный код доступен по ссылке: [nestjs-monorepa-starter](