Docker Setup For a NestJS Application
This setup includes a Node.js server using NestJS, a PostgreSQL database, and utilizes Docker for containerization.
Docker Compose File (docker-compose.yml):
version: '3.8'
services:
nestjs-app:
build:
context: .
dockerfile: Dockerfile
ports:
- '3000:3000'
depends_on:
- postgres
environment:
DATABASE_HOST: postgres
DATABASE_PORT: 5432
DATABASE_USERNAME: postgres
DATABASE_PASSWORD: mysecretpassword
DATABASE_NAME: mydb
networks:
- my-network
postgres:
image: postgres:13
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: mysecretpassword
POSTGRES_DB: mydb
volumes:
- postgres-data:/var/lib/postgresql/data
networks:
- my-network
networks:
my-network:
driver: bridge
volumes:
postgres-data:
Dockerfile:
# Use the official Node.js image as the base image
FROM node:14-alpine
# Set the working directory inside the container
WORKDIR /app
# Copy package.json and package-lock.json to the container
COPY package*.json ./
# Install the dependencies
RUN npm install
# Copy the rest of the application code to the container
COPY . .
# Expose the port on which the NestJS app will run
EXPOSE 3000
# Start the NestJS application
CMD [ "npm", "start" ]
Explanation:
- The Docker Compose file defines two services:
nestjs-app
andpostgres
. - The
nestjs-app
service is built using the Dockerfile in the current directory. It exposes port 3000 and depends on thepostgres
service. Environment variables are provided to connect to the PostgreSQL database. - The
postgres
service uses the official PostgreSQL image, sets environment variables for the database configuration, and creates a named volume to persist the database data. - Both services are connected to a custom bridge network named
my-network
. - The Dockerfile uses the official Node.js 14 Alpine image as the base image.
- It sets the working directory, copies package.json and package-lock.json, and installs dependencies.
- The application code is copied to the container, and port 3000 is exposed.
- The
CMD
instruction starts the NestJS application when the container is run.
This setup allows you to easily containerize and deploy your NestJS application along with a PostgreSQL database using Docker Compose. Remember to adjust environment variables, database credentials, and other configuration parameters as needed for your specific project.