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
  
  
  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"]
  
  
  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
4. Build and Run the Docker Containers
Run the following command to start the app and MongoDB:
docker-compose up --build
5. Verify Everything Works
- Open http://localhost:3000/todos to check the API.
 - Use Postman or cURL to test the endpoints.
 
6. Stop the Containers
To stop the containers, run:
docker-compose down
7. Check If the App is Running
Run:
docker ps
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
If it fails, check logs with:
docker logs -f nest-todo-app
My Git: https://github.com/Taki089Linux/nestj-todo-app/tree/setup-docker
              
    
Top comments (0)