- 1. API with NestJS #1. Controllers, routing and the module structure
- 2. API with NestJS #2. Setting up a PostgreSQL database with TypeORM
- 3. API with NestJS #3. Authenticating users with bcrypt, Passport, JWT, and cookies
- 4. API with NestJS #4. Error handling and data validation
- 5. API with NestJS #5. Serializing the response with interceptors
- 6. API with NestJS #6. Looking into dependency injection and modules
- 7. API with NestJS #7. Creating relationships with Postgres and TypeORM
- 8. API with NestJS #8. Writing unit tests
- 9. API with NestJS #9. Testing services and controllers with integration tests
- 10. API with NestJS #10. Uploading public files to Amazon S3
- 11. API with NestJS #11. Managing private files with Amazon S3
- 12. API with NestJS #12. Introduction to Elasticsearch
- 13. API with NestJS #13. Implementing refresh tokens using JWT
- 14. API with NestJS #14. Improving performance of our Postgres database with indexes
- 15. API with NestJS #15. Defining transactions with PostgreSQL and TypeORM
- 16. API with NestJS #16. Using the array data type with PostgreSQL and TypeORM
- 17. API with NestJS #17. Offset and keyset pagination with PostgreSQL and TypeORM
- 18. API with NestJS #18. Exploring the idea of microservices
- 19. API with NestJS #19. Using RabbitMQ to communicate with microservices
- 20. API with NestJS #20. Communicating with microservices using the gRPC framework
- 21. API with NestJS #21. An introduction to CQRS
- 22. API with NestJS #22. Storing JSON with PostgreSQL and TypeORM
- 23. API with NestJS #23. Implementing in-memory cache to increase the performance
- 24. API with NestJS #24. Cache with Redis. Running the app in a Node.js cluster
- 25. API with NestJS #25. Sending scheduled emails with cron and Nodemailer
- 26. API with NestJS #26. Real-time chat with WebSockets
- 27. API with NestJS #27. Introduction to GraphQL. Queries, mutations, and authentication
- 28. API with NestJS #28. Dealing in the N + 1 problem in GraphQL
- 29. API with NestJS #29. Real-time updates with GraphQL subscriptions
- 30. API with NestJS #30. Scalar types in GraphQL
- 31. API with NestJS #31. Two-factor authentication
- 32. API with NestJS #32. Introduction to Prisma with PostgreSQL
- 33. API with NestJS #33. Managing PostgreSQL relationships with Prisma
- 34. API with NestJS #34. Handling CPU-intensive tasks with queues
- 35. API with NestJS #35. Using server-side sessions instead of JSON Web Tokens
- 36. API with NestJS #36. Introduction to Stripe with React
- 37. API with NestJS #37. Using Stripe to save credit cards for future use
- 38. API with NestJS #38. Setting up recurring payments via subscriptions with Stripe
- 39. API with NestJS #39. Reacting to Stripe events with webhooks
- 40. API with NestJS #40. Confirming the email address
- 41. API with NestJS #41. Verifying phone numbers and sending SMS messages with Twilio
- 42. API with NestJS #42. Authenticating users with Google
- 43. API with NestJS #43. Introduction to MongoDB
- 44. API with NestJS #44. Implementing relationships with MongoDB
- 45. API with NestJS #45. Virtual properties with MongoDB and Mongoose
- 46. API with NestJS #46. Managing transactions with MongoDB and Mongoose
- 47. API with NestJS #47. Implementing pagination with MongoDB and Mongoose
- 48. API with NestJS #48. Definining indexes with MongoDB and Mongoose
- 49. API with NestJS #49. Updating with PUT and PATCH with MongoDB and Mongoose
- 50. API with NestJS #50. Introduction to logging with the built-in logger and TypeORM
- 51. API with NestJS #51. Health checks with Terminus and Datadog
- 52. API with NestJS #52. Generating documentation with Compodoc and JSDoc
- 53. API with NestJS #53. Implementing soft deletes with PostgreSQL and TypeORM
- 54. API with NestJS #54. Storing files inside a PostgreSQL database
- 55. API with NestJS #55. Uploading files to the server
- 56. API with NestJS #56. Authorization with roles and claims
- 57. API with NestJS #57. Composing classes with the mixin pattern
- 58. API with NestJS #58. Using ETag to implement cache and save bandwidth
- 59. API with NestJS #59. Introduction to a monorepo with Lerna and Yarn workspaces
- 60. API with NestJS #60. The OpenAPI specification and Swagger
- 61. API with NestJS #61. Dealing with circular dependencies
- 62. API with NestJS #62. Introduction to MikroORM with PostgreSQL
- 63. API with NestJS #63. Relationships with PostgreSQL and MikroORM
- 64. API with NestJS #64. Transactions with PostgreSQL and MikroORM
- 65. API with NestJS #65. Implementing soft deletes using MikroORM and filters
- 66. API with NestJS #66. Improving PostgreSQL performance with indexes using MikroORM
- 67. API with NestJS #67. Migrating to TypeORM 0.3
- 68. API with NestJS #68. Interacting with the application through REPL
- 69. API with NestJS #69. Database migrations with TypeORM
- 70. API with NestJS #70. Defining dynamic modules
- 71. API with NestJS #71. Introduction to feature flags
- 72. API with NestJS #72. Working with PostgreSQL using raw SQL queries
- 73. API with NestJS #73. One-to-one relationships with raw SQL queries
- 74. API with NestJS #74. Designing many-to-one relationships using raw SQL queries
- 75. API with NestJS #75. Many-to-many relationships using raw SQL queries
- 76. API with NestJS #76. Working with transactions using raw SQL queries
- 77. API with NestJS #77. Offset and keyset pagination with raw SQL queries
- 78. API with NestJS #78. Generating statistics using aggregate functions in raw SQL
- 79. API with NestJS #79. Implementing searching with pattern matching and raw SQL
- 80. API with NestJS #80. Updating entities with PUT and PATCH using raw SQL queries
- 81. API with NestJS #81. Soft deletes with raw SQL queries
- 82. API with NestJS #82. Introduction to indexes with raw SQL queries
- 83. API with NestJS #83. Text search with tsvector and raw SQL
- 84. API with NestJS #84. Implementing filtering using subqueries with raw SQL
- 85. API with NestJS #85. Defining constraints with raw SQL
- 86. API with NestJS #86. Logging with the built-in logger when using raw SQL
- 87. API with NestJS #87. Writing unit tests in a project with raw SQL
- 88. API with NestJS #88. Testing a project with raw SQL using integration tests
- 89. API with NestJS #89. Replacing Express with Fastify
- 90. API with NestJS #90. Using various types of SQL joins
- 91. API with NestJS #91. Dockerizing a NestJS API with Docker Compose
- 92. API with NestJS #92. Increasing the developer experience with Docker Compose
- 93. API with NestJS #93. Deploying a NestJS app with Amazon ECS and RDS
- 94. API with NestJS #94. Deploying multiple instances on AWS with a load balancer
- 95. API with NestJS #95. CI/CD with Amazon ECS and GitHub Actions
- 96. API with NestJS #96. Running unit tests with CI/CD and GitHub Actions
- 97. API with NestJS #97. Introduction to managing logs with Amazon CloudWatch
- 98. API with NestJS #98. Health checks with Terminus and Amazon ECS
- 99. API with NestJS #99. Scaling the number of application instances with Amazon ECS
- 100. API with NestJS #100. The HTTPS protocol with Route 53 and AWS Certificate Manager
- 101. API with NestJS #101. Managing sensitive data using the AWS Secrets Manager
- 102. API with NestJS #102. Writing unit tests with Prisma
- 103. API with NestJS #103. Integration tests with Prisma
- 104. API with NestJS #104. Writing transactions with Prisma
- 105. API with NestJS #105. Implementing soft deletes with Prisma and middleware
- 106. API with NestJS #106. Improving performance through indexes with Prisma
- 107. API with NestJS #107. Offset and keyset pagination with Prisma
- 108. API with NestJS #108. Date and time with Prisma and PostgreSQL
- 109. API with NestJS #109. Arrays with PostgreSQL and Prisma
- 110. API with NestJS #110. Managing JSON data with PostgreSQL and Prisma
- 111. API with NestJS #111. Constraints with PostgreSQL and Prisma
- 112. API with NestJS #112. Serializing the response with Prisma
- 113. API with NestJS #113. Logging with Prisma
- 114. API with NestJS #114. Modifying data using PUT and PATCH methods with Prisma
- 115. API with NestJS #115. Database migrations with Prisma
- 116. API with NestJS #116. REST API versioning
- 117. API with NestJS #117. CORS – Cross-Origin Resource Sharing
- 118. API with NestJS #118. Uploading and streaming videos
- 119. API with NestJS #119. Type-safe SQL queries with Kysely and PostgreSQL
- 120. API with NestJS #120. One-to-one relationships with the Kysely query builder
- 121. API with NestJS #121. Many-to-one relationships with PostgreSQL and Kysely
So far, in this series of articles, we’ve been using Docker to run various services our NestJS application depends on. Some good examples are PostgreSQL and Redis. We can take it a step further and put our NestJS application into a Docker container as well. It can be very useful when looking into deploying our app.
You can find the code from this article in this repository.
Building the Docker image
We need to start by building a Docker image for our NestJS application. A Docker image acts as a template that describes everything our application needs to run. For example, it includes the source code and its JavaScript dependencies. Besides the above, it also contains information about the desired operating system and its components, such as the Node.js version.
There are a lot of Docker images ready to use and maintained by the community. We can find them on Docker Hub. A good example is node:alpine, based on the lightweight Alpine Linux distribution that comes with Node.js preinstalled.
To define a Docker image, we need to create the Dockerfile. It’s a text file containing all the information about the image. When building a Docker image for our application, we can base it on an existing one. To do that, we need to start our Dockerfile with the FROM keyword and specify the parent image from which we’re building our new image.
Dockerfile
1 |
FROM node:18-alpine |
We can now specify additional instructions to make sure our NestJS application will be able to run correctly. By default, Docker will run all of the following commands in the root directory. To keep our Docker container tidy, we can use the WORKSPACE instruction to define the working directory for all the following commands.
Dockerfile
1 2 3 |
FROM node:18-alpine WORKDIR /user/src/app |
So far, our Docker image does not contain the source code of our NestJS application. Let’s add it and install the dependencies.
Dockerfile
1 2 3 4 5 6 7 |
FROM node:18-alpine WORKDIR /user/src/app COPY . . RUN npm ci --omit=dev |
npm ci is an alternative for npm install meant for automated environments. By running it with the --omit=dev flag we avoid installing packages listed in the devDependencies to achieve a smaller Docker image. We need to make sure that we list all of the packages the image needs such as @nestjs/cli in the dependencies section.
By running COPY . ., we copy all of the files from our application to the /user/src/app directory in our Docker image. Then, we execute RUN npm ci to install the necessary JavaScript dependencies.
Once the above process is ready, we can build and start our NestJS application. Our complete Dockerfile looks like that:
Dockerfile
1 2 3 4 5 6 7 8 9 10 11 12 13 |
FROM node:18-alpine WORKDIR /user/src/app COPY . . RUN npm ci --omit=dev RUN npm run build USER node CMD ["npm", "run", "start:prod"] |
We run USER node to avoid running our application as root for security reasons. It might also be a good idea to change the owner of the files we’ve copied before.
It’s crucial to understand the difference between the RUN and CMD instructions. The RUN command defines the image build step and will be executed when building the image before starting the application. Therefore, we can have multiple RUN instructions in a single Dockerfile.
The CMD instruction does not run when building the image. Instead, Docker executes it once when running the Docker container created based on our image. Therefore, using more than one CMD instruction causes the last one to override the previous CMD commands.
Ignoring some of the files in our application
By default, COPY . . copies all of the files from the directory of our application into the Docker image. However, we need to remember that there are some files we shouldn’t put into our Docker image. To define them, we need to create the .dockerignore file.
.dockerignore
1 2 3 4 5 |
node_modules dist .git .env docker.env |
Building the Docker image
Once we’ve created our Dockerfile, we need to build our Docker image.
1 |
docker build --tag "nestjs-api" . |
Sending build context to Docker daemon 856.1kB
Step 1/7 : FROM node:18-alpine
—> 264f8646c2a6
Step 2/7 : WORKDIR /user/src/app
—> Running in a157ed686647
Removing intermediate container a157ed686647
—> 665415e6101e
Step 3/7 : COPY . .
—> 6ba70bc9f752
Step 4/7 : RUN npm ci –omit=dev
—> Running in 4206995663aaadded 565 packages, and audited 566 packages in 17s
59 packages are looking for funding
runnpm fund
for detailsfound 0 vulnerabilities
Removing intermediate container 4206995663aa
—> c98bfbb842ec
Step 5/7 : RUN npm run build
—> Running in af3ae30c58da> nest-typescript-starter@1.0.0 prebuild
> rimraf dist> nest-typescript-starter@1.0.0 build
> nest buildRemoving intermediate container af3ae30c58da
—> 26021dcbe202
Step 6/7 : USER node
—> Running in bbfe5d194ada
Removing intermediate container bbfe5d194ada
—> ad1331df0fa1
Step 7/7 : CMD [“npm”, “run”, “start:prod”]
—> Running in 1691c04e966b
Removing intermediate container 1691c04e966b
—> 1268ba0ec302
Successfully built 1268ba0ec302
Successfully tagged nestjs-api:latest
The crucial part of the above process is that Docker ran npm ci and npm run build but didn’t run npm run start:prod yet.
By adding --tag "nestjs-api" we’ve chosen a name for our Docker image. Thanks to that, we will be able to refer to it later.
Using Docker Compose to run multiple containers
Once we’ve built a Docker image, we can run a Docker container based on it. The container is a runtime instance of the image.
We could run our image with a single command:
1 |
docker run nestjs-api |
The above command creates a Docker container and executes npm run start:prod inside.
Often an application consists of multiple Docker containers, though. In our case, we want to run PostgreSQL and let our NestJS API connect with it. Maintaining multiple containers and ensuring they can communicate with each other can be challenging.
Fortunately, we can use the Docker Compose tool that helps us run multi-container Docker applications. When working with it, we need to definite the configuration of our application using YAML.
docker-compose.yml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
version: "3" services: postgres: image: postgres:15.1 networks: - postgres volumes: - /data/postgres:/data/postgres env_file: - docker.env pgadmin: image: dpage/pgadmin4:6.18 networks: - postgres ports: - "8080:80" volumes: - /data/pgadmin:/root/.pgadmin env_file: - docker.env nestjs-api: image: nestjs-api env_file: - .env ports: - "3000:3000" depends_on: - postgres networks: - postgres networks: postgres: driver: bridge |
A few significant things are happening above, so let’s break the file down.
Creating a custom network
We create a custom network by adding the postgres entry in the networks section.
1 2 3 |
networks: postgres: driver: bridge |
Thanks to the above, we can easily specify which Docker containers can communicate with each other.
Setting up PostgreSQL
The first Docker container we specify in the services section uses the postgres:15.1 image.
It’s always a good idea to use a specific version instead of postgres:latest.
1 2 3 4 5 6 7 8 |
postgres: image: postgres:15.1 networks: - postgres volumes: - /data/postgres:/data/postgres env_file: - docker.env |
You can see above that we add it to the postgres network so that other Docker containers can communicate with it.
Thanks to configuring volumes, we allow the Docker container to persist data outside the container. Thanks to doing that, once we shut down the container and rerun it, we don’t end up with an empty database.
By specifying the env_file property, we can provide a set of environment variables the container will use, such as the credentials required to connect to the database.
docker.env
1 2 3 4 5 |
POSTGRES_USER=admin POSTGRES_PASSWORD=admin POSTGRES_DB=nestjs PGADMIN_DEFAULT_EMAIL=admin@admin.com PGADMIN_DEFAULT_PASSWORD=admin |
Configuring pgAdmin
pgAdmin is a useful tool to help us manage our PostgreSQL database. Our pgAdmin container runs using the dpage/pgadmin4:6.18 image.
1 2 3 4 5 6 7 8 9 10 |
pgadmin: image: dpage/pgadmin4:6.18 networks: - postgres ports: - "8080:80" volumes: - /data/pgadmin:/root/.pgadmin env_file: - docker.env |
The new thing to grasp in the above code is the ports section. By default, pgAdmin runs on port 80. Thanks to adding 8080:80 to the ports section Docker exposes pgAdmin outside of the Docker container and allows us to access it through http://localhost:8080 on our machine.
To log in, we need to use the credentials provided in the docker.env file.
To connect to our PostgresSQL database, we also need to use the credentials provided in the docker.env file.
Since both pgAdmin and PostgreSQL run in the Docker containers, we need to provide postgres as the host name. It matches the name of the postgres service specified in the docker-compose.yml file.
Setting up our NestJS application
The last step is to add our NestJS application to our docker-compose configuration.
1 2 3 4 5 6 7 8 9 10 |
nestjs-api: image: nestjs-api env_file: - .env ports: - "3000:3000" depends_on: - postgres networks: - postgres |
The most crucial part of the above code is the image: nestjs-api. The name of the Docker image needs to match the docker build --tag "nestjs-api" . command we’ve used before.
By adding .env to the env_file section, we can provide a list of environment variables for our NestJS application.
.env
1 2 3 4 5 6 7 8 9 10 |
POSTGRES_HOST=postgres POSTGRES_PORT=5432 POSTGRES_USER=admin POSTGRES_PASSWORD=admin POSTGRES_DB=nestjs JWT_SECRET=lum!SXwGL00Q JWT_EXPIRATION_TIME=21600 PORT=3000 |
As you can see above, our NestJS application runs on port 3000 inside the Docker container. We also expect Docker to expose our NestJS API outside of the container. By adding "3000:3000" to the ports section, we specify that we want to be able to reach our NestJS API using http://localhost:3000.
By adding postgres to the depends_on array, we state that our NestJS API shouldn’t run before the PostgreSQL service was initialized.
Running all of the Docker containers
The last step is to run the above Docker Compose configuration.
1 |
docker-compose up |
Once we run Docker Compose, it creates and runs all specified Docker containers. Now our application is up and running. It’s also accessible outside of Docker.
Summary
In this article, we went through the configuration required to run NestJS in a Docker container properly. To do that, we had to learn how to write the Dockerfile and build our Docker image. We also created the Docker Compose configuration that allowed us to run other services our NestJS API needs, such as PostgreSQL. Finally, we also made sure that all of our Docker containers could communicate with each other.
There is still more to learn when it comes to using NestJS with Docker, so stay tuned!
great article as always! The above is my dockerfile stitched together from various sources, which has a few advantages
should n’t copy node_module, should run it on container
hello, how i can run migration inside docker with docker-compose