├── .dockerignore ├── .env.example ├── .eslintrc.js ├── .gitignore ├── .prettierrc ├── Dockerfile ├── README.md ├── docker-compose.yml ├── nest-cli.json ├── package-lock.json ├── package.json ├── src ├── app.controller.spec.ts ├── app.controller.ts ├── app.module.ts ├── app.service.ts └── main.ts ├── test ├── app.e2e-spec.ts └── jest-e2e.json ├── tsconfig.build.json └── tsconfig.json /.dockerignore: -------------------------------------------------------------------------------- 1 | Dockerfile 2 | .dockerignore 3 | node_modules 4 | npm-debug.log 5 | dist 6 | -------------------------------------------------------------------------------- /.env.example: -------------------------------------------------------------------------------- 1 | REDIS_HOST="redis" 2 | REDIS_PORT="6379" 3 | 4 | POSTGRES_DB="docker-nest-postgres" 5 | POSTGRES_USER="username" 6 | POSTGRES_PASSWORD="password" -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | parser: '@typescript-eslint/parser', 3 | parserOptions: { 4 | project: 'tsconfig.json', 5 | tsconfigRootDir : __dirname, 6 | sourceType: 'module', 7 | }, 8 | plugins: ['@typescript-eslint/eslint-plugin'], 9 | extends: [ 10 | 'plugin:@typescript-eslint/recommended', 11 | 'plugin:prettier/recommended', 12 | ], 13 | root: true, 14 | env: { 15 | node: true, 16 | jest: true, 17 | }, 18 | ignorePatterns: ['.eslintrc.js'], 19 | rules: { 20 | '@typescript-eslint/interface-name-prefix': 'off', 21 | '@typescript-eslint/explicit-function-return-type': 'off', 22 | '@typescript-eslint/explicit-module-boundary-types': 'off', 23 | '@typescript-eslint/no-explicit-any': 'off', 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # compiled output 2 | /dist 3 | /node_modules 4 | 5 | # Logs 6 | logs 7 | *.log 8 | npm-debug.log* 9 | pnpm-debug.log* 10 | yarn-debug.log* 11 | yarn-error.log* 12 | lerna-debug.log* 13 | 14 | # OS 15 | .DS_Store 16 | 17 | # Tests 18 | /coverage 19 | /.nyc_output 20 | 21 | # IDEs and editors 22 | /.idea 23 | .project 24 | .classpath 25 | .c9/ 26 | *.launch 27 | .settings/ 28 | *.sublime-workspace 29 | 30 | # IDE - VSCode 31 | .vscode/* 32 | !.vscode/settings.json 33 | !.vscode/tasks.json 34 | !.vscode/launch.json 35 | !.vscode/extensions.json 36 | 37 | # environment variables 38 | .env -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "singleQuote": true, 3 | "trailingComma": "all" 4 | } -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | ################### 2 | # BUILD FOR LOCAL DEVELOPMENT 3 | ################### 4 | 5 | FROM node:18-alpine As development 6 | 7 | # Create app directory 8 | WORKDIR /usr/src/app 9 | 10 | # Copy application dependency manifests to the container image. 11 | # A wildcard is used to ensure copying both package.json AND package-lock.json (when available). 12 | # Copying this first prevents re-running npm install on every code change. 13 | COPY --chown=node:node package*.json ./ 14 | 15 | # Install app dependencies using the `npm ci` command instead of `npm install` 16 | RUN npm ci 17 | 18 | # Bundle app source 19 | COPY --chown=node:node . . 20 | 21 | # Use the node user from the image (instead of the root user) 22 | USER node 23 | 24 | ################### 25 | # BUILD FOR PRODUCTION 26 | ################### 27 | 28 | FROM node:18-alpine As build 29 | 30 | WORKDIR /usr/src/app 31 | 32 | COPY --chown=node:node package*.json ./ 33 | 34 | # In order to run `npm run build` we need access to the Nest CLI. 35 | # The Nest CLI is a dev dependency, 36 | # In the previous development stage we ran `npm ci` which installed all dependencies. 37 | # So we can copy over the node_modules directory from the development image into this build image. 38 | COPY --chown=node:node --from=development /usr/src/app/node_modules ./node_modules 39 | 40 | COPY --chown=node:node . . 41 | 42 | # Run the build command which creates the production bundle 43 | RUN npm run build 44 | 45 | # Set NODE_ENV environment variable 46 | ENV NODE_ENV production 47 | 48 | # Running `npm ci` removes the existing node_modules directory. 49 | # Passing in --only=production ensures that only the production dependencies are installed. 50 | # This ensures that the node_modules directory is as optimized as possible. 51 | RUN npm ci --only=production && npm cache clean --force 52 | 53 | USER node 54 | 55 | ################### 56 | # PRODUCTION 57 | ################### 58 | 59 | FROM node:18-alpine As production 60 | 61 | # Copy the bundled code from the build stage to the production image 62 | COPY --chown=node:node --from=build /usr/src/app/node_modules ./node_modules 63 | COPY --chown=node:node --from=build /usr/src/app/dist ./dist 64 | 65 | # Start the server using the production build 66 | CMD [ "node", "dist/main.js" ] 67 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Docker Compose setup for NestJS + Redis + Postgres 2 | 3 | This is a repo made for [this blog post](https://www.tomray.dev/nestjs-docker-compose-postgres) which explains the steps to setup a local dev environment for NestJS + Redis + Postgres. 4 | 5 | This repo is ORM agnostic, and will likely require further configs tweaks to work with your ORM of choice. 6 | 7 | You can, however, check out the [Prisma branch](https://github.com/tomwray13/nest-docker-postgres-prisma/tree/prisma-setup) of this repo to see an example Prisma setup with this workflow. 8 | 9 | ## Local setup 10 | 11 | Here's how to setup locally. 12 | 13 | 1. Clone this repo 14 | 2. Run `npm install` to install dependencies 15 | 3. Copy the `.env.example` file over to your own `.env` file and update the variables 16 | 4. Run `docker-compose up -d` to setup local environment with Docker 17 | 18 | This setup will handle hot reloading, so any updates you make to the NestJS code will update the container in realtime. 19 | 20 | ## Tweaking the Dockerfile 21 | 22 | If you make any tweaks to the Dockerfile to edit the image, you'll need to run `docker-compose up -d --build` to rebuild the image 23 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | services: 2 | api: 3 | build: 4 | dockerfile: Dockerfile 5 | context: . 6 | # Only will build development stage from our dockerfile 7 | target: development 8 | env_file: 9 | - .env 10 | volumes: 11 | - .:/usr/src/app 12 | # Run in dev Mode: npm run start:dev 13 | command: npm run start:dev 14 | ports: 15 | - 3000:3000 16 | depends_on: 17 | - redis 18 | - postgres 19 | redis: # Name of container 20 | image: redis 21 | ports: 22 | - 6379:6379 23 | volumes: 24 | - redis:/data 25 | postgres: 26 | image: postgres 27 | restart: always 28 | environment: 29 | POSTGRES_DB: ${POSTGRES_DB} 30 | POSTGRES_USER: ${POSTGRES_USER} 31 | POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} 32 | ports: 33 | - '5432:5432' 34 | volumes: 35 | - docker-nest-postgres:/var/lib/postgresql/data 36 | 37 | volumes: 38 | docker-nest-postgres: 39 | redis: 40 | driver: local -------------------------------------------------------------------------------- /nest-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "https://json.schemastore.org/nest-cli", 3 | "collection": "@nestjs/schematics", 4 | "sourceRoot": "src" 5 | } 6 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "nest-docker-postgres-prisma", 3 | "version": "0.0.1", 4 | "description": "", 5 | "author": "", 6 | "private": true, 7 | "license": "UNLICENSED", 8 | "scripts": { 9 | "prebuild": "rimraf dist", 10 | "build": "nest build", 11 | "format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"", 12 | "start": "nest start", 13 | "start:dev": "nest start --watch", 14 | "start:debug": "nest start --debug --watch", 15 | "start:prod": "node dist/main", 16 | "lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix", 17 | "test": "jest", 18 | "test:watch": "jest --watch", 19 | "test:cov": "jest --coverage", 20 | "test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand", 21 | "test:e2e": "jest --config ./test/jest-e2e.json" 22 | }, 23 | "dependencies": { 24 | "@nestjs/common": "^8.0.0", 25 | "@nestjs/config": "^2.2.0", 26 | "@nestjs/core": "^8.0.0", 27 | "@nestjs/platform-express": "^8.0.0", 28 | "cache-manager": "^4.1.0", 29 | "cache-manager-redis-store": "^2.0.0", 30 | "reflect-metadata": "^0.1.13", 31 | "rimraf": "^3.0.2", 32 | "rxjs": "^7.2.0" 33 | }, 34 | "devDependencies": { 35 | "@nestjs/cli": "^8.0.0", 36 | "@nestjs/schematics": "^8.0.0", 37 | "@nestjs/testing": "^8.0.0", 38 | "@types/express": "^4.17.13", 39 | "@types/jest": "27.5.0", 40 | "@types/node": "^16.0.0", 41 | "@types/supertest": "^2.0.11", 42 | "@typescript-eslint/eslint-plugin": "^5.0.0", 43 | "@typescript-eslint/parser": "^5.0.0", 44 | "eslint": "^8.0.1", 45 | "eslint-config-prettier": "^8.3.0", 46 | "eslint-plugin-prettier": "^4.0.0", 47 | "jest": "28.0.3", 48 | "prettier": "^2.3.2", 49 | "source-map-support": "^0.5.20", 50 | "supertest": "^6.1.3", 51 | "ts-jest": "28.0.1", 52 | "ts-loader": "^9.2.3", 53 | "ts-node": "^10.0.0", 54 | "tsconfig-paths": "4.0.0", 55 | "typescript": "^4.3.5" 56 | }, 57 | "jest": { 58 | "moduleFileExtensions": [ 59 | "js", 60 | "json", 61 | "ts" 62 | ], 63 | "rootDir": "src", 64 | "testRegex": ".*\\.spec\\.ts$", 65 | "transform": { 66 | "^.+\\.(t|j)s$": "ts-jest" 67 | }, 68 | "collectCoverageFrom": [ 69 | "**/*.(t|j)s" 70 | ], 71 | "coverageDirectory": "../coverage", 72 | "testEnvironment": "node" 73 | } 74 | } 75 | -------------------------------------------------------------------------------- /src/app.controller.spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | 5 | describe('AppController', () => { 6 | let appController: AppController; 7 | 8 | beforeEach(async () => { 9 | const app: TestingModule = await Test.createTestingModule({ 10 | controllers: [AppController], 11 | providers: [AppService], 12 | }).compile(); 13 | 14 | appController = app.get(AppController); 15 | }); 16 | 17 | describe('root', () => { 18 | it('should return "Hello World!"', () => { 19 | expect(appController.getHello()).toBe('Hello World!'); 20 | }); 21 | }); 22 | }); 23 | -------------------------------------------------------------------------------- /src/app.controller.ts: -------------------------------------------------------------------------------- 1 | import { 2 | CacheInterceptor, 3 | CacheTTL, 4 | Controller, 5 | Get, 6 | UseInterceptors, 7 | } from '@nestjs/common'; 8 | import { AppService } from './app.service'; 9 | 10 | @Controller() 11 | export class AppController { 12 | constructor(private readonly appService: AppService) {} 13 | 14 | @UseInterceptors(CacheInterceptor) // automatically cache the response 15 | @CacheTTL(30) // sets the TTL to 30 seconds 16 | @Get() 17 | getHello(): string { 18 | return this.appService.getHello(); 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/app.module.ts: -------------------------------------------------------------------------------- 1 | import { CacheModule, Module } from '@nestjs/common'; 2 | import { AppController } from './app.controller'; 3 | import { AppService } from './app.service'; 4 | import * as redisStore from 'cache-manager-redis-store'; 5 | import { ConfigModule } from '@nestjs/config'; 6 | 7 | @Module({ 8 | imports: [ 9 | ConfigModule.forRoot(), 10 | CacheModule.register({ 11 | isGlobal: true, 12 | store: redisStore, 13 | host: process.env.REDIS_HOST, 14 | port: process.env.REDIS_PORT, 15 | }), 16 | ], 17 | controllers: [AppController], 18 | providers: [AppService], 19 | }) 20 | export class AppModule {} 21 | -------------------------------------------------------------------------------- /src/app.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@nestjs/common'; 2 | 3 | @Injectable() 4 | export class AppService { 5 | getHello(): string { 6 | return `Hello`; 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { NestFactory } from '@nestjs/core'; 2 | import { AppModule } from './app.module'; 3 | 4 | async function bootstrap() { 5 | const app = await NestFactory.create(AppModule); 6 | await app.listen(3000); 7 | } 8 | bootstrap(); 9 | -------------------------------------------------------------------------------- /test/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { Test, TestingModule } from '@nestjs/testing'; 2 | import { INestApplication } from '@nestjs/common'; 3 | import * as request from 'supertest'; 4 | import { AppModule } from './../src/app.module'; 5 | 6 | describe('AppController (e2e)', () => { 7 | let app: INestApplication; 8 | 9 | beforeEach(async () => { 10 | const moduleFixture: TestingModule = await Test.createTestingModule({ 11 | imports: [AppModule], 12 | }).compile(); 13 | 14 | app = moduleFixture.createNestApplication(); 15 | await app.init(); 16 | }); 17 | 18 | it('/ (GET)', () => { 19 | return request(app.getHttpServer()) 20 | .get('/') 21 | .expect(200) 22 | .expect('Hello World!'); 23 | }); 24 | }); 25 | -------------------------------------------------------------------------------- /test/jest-e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "moduleFileExtensions": ["js", "json", "ts"], 3 | "rootDir": ".", 4 | "testEnvironment": "node", 5 | "testRegex": ".e2e-spec.ts$", 6 | "transform": { 7 | "^.+\\.(t|j)s$": "ts-jest" 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /tsconfig.build.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "exclude": ["node_modules", "test", "dist", "**/*spec.ts"] 4 | } 5 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "declaration": true, 5 | "removeComments": true, 6 | "emitDecoratorMetadata": true, 7 | "experimentalDecorators": true, 8 | "allowSyntheticDefaultImports": true, 9 | "target": "es2017", 10 | "sourceMap": true, 11 | "outDir": "./dist", 12 | "baseUrl": "./", 13 | "incremental": true, 14 | "skipLibCheck": true, 15 | "strictNullChecks": false, 16 | "noImplicitAny": false, 17 | "strictBindCallApply": false, 18 | "forceConsistentCasingInFileNames": false, 19 | "noFallthroughCasesInSwitch": false 20 | } 21 | } 22 | --------------------------------------------------------------------------------