DEV Community

Cover image for Set up Docker For NestJs
Taki (Kieu Dang)
Taki (Kieu Dang)

Posted on • Originally published at dev.to

1

Set up Docker For NestJs

Let's add Docker support to the NestJS To-Do App with MongoDB. This includes a Dockerfile, a docker-compose.yml file, and necessary environment variables.


1. Create a .dockerignore File

This file prevents unnecessary files from being copied to the Docker image.

Create .dockerignore in the root directory:

node_modules
dist
.git
.env
Dockerfile
Enter fullscreen mode Exit fullscreen mode

2. Create a Dockerfile

This file defines the steps to build the NestJS application inside a Docker container.

Create a Dockerfile in the root directory:

# Use Node.js Alpine for a smaller image
FROM node:20-alpine

# Set working directory
WORKDIR /TODO-APP

# Copy package.json and yarn.lock before installing dependencies
COPY package.json yarn.lock ./

# Install dependencies with Yarn
RUN yarn install --frozen-lockfile

# Copy all source files
COPY . .

# Expose port 3000
EXPOSE 3000

# Start the application
CMD ["yarn", "start:dev"]
Enter fullscreen mode Exit fullscreen mode

3. Create docker-compose.yml

This file defines how our services (NestJS API + MongoDB) run together.

Create docker-compose.yml in the root directory:

version: '3.8'

services:
  app:
    build: .
    container_name: nest-todo-app
    restart: always
    env_file:
      - .env
    ports:
      - '3000:3000'
    volumes:
      - .:/TODO-APP
    command: yarn start:dev
Enter fullscreen mode Exit fullscreen mode

4. Build and Run the Docker Containers

Run the following command to start the app and MongoDB:

docker-compose up --build
Enter fullscreen mode Exit fullscreen mode

5. Verify Everything Works


6. Stop the Containers

To stop the containers, run:

docker-compose down
Enter fullscreen mode Exit fullscreen mode

7. Check If the App is Running

Run:

docker ps
Enter fullscreen mode Exit fullscreen mode

You should see:

CONTAINER ID   IMAGE       COMMAND             PORTS                    NAMES
xxxxxxxxxxx    nest-todo-app   "yarn start:dev"   0.0.0.0:3000->3000/tcp   nest-todo-app
Enter fullscreen mode Exit fullscreen mode

If it fails, check logs with:

docker logs -f nest-todo-app
Enter fullscreen mode Exit fullscreen mode

My Git: https://github.com/Taki089Linux/nestj-todo-app/tree/setup-docker

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay