DEV Community

Cover image for Set up Docker For NestJs
Taki089.Dang
Taki089.Dang

Posted on • Originally published at dev.to

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

Top comments (0)