Introduction
I’m a newbie in the backend world, and I’ve been learning NestJS to build APIs. Recently, I’ve been exploring how to dockerize and deploy a NestJS app to an EC2 instance on AWS.In this post, I will guide you on how to dockerize a Nestjs app and deploy it to an EC2 instance. Let’s get started!
Prerequisites
Before we start, make sure you have the following prerequisites:
- A NestJS app
- Docker installed on your local machine
- An AWS account
Dockerizing the NestJS App
Step 1: Create a Dockerfile
First, create a Dockerfile
in the root directory of your NestJS app. Add the following content to the Dockerfile
:
|
|
Step 2: Build the Docker Image
Next, build the Docker image by running the following command in the root directory of your NestJS app:
|
|
Note: If you are using Macbook M1, you may need to add the
--platform=linux/amd64
flag to thedocker build
command.
Step 3: Run the Docker Container Locally
You can run the Docker container locally to test if everything is working fine. Use the following command:
|
|
Step 4: Push the Docker Image to Docker Hub
Before deploying the Docker image to an EC2 instance, you need to push the image to Docker Hub. First, log in to Docker Hub using the following command:
|
|
Then, tag the Docker image with your Docker Hub username and repository name:
|
|
Finally, push the Docker image to Docker Hub:
|
|
Deploying the NestJS App to EC2
Step 1: Launch and Connect to your EC2 Instance
Log in to your AWS Management Console and launch an EC2 instance. Connect to the instance using SSH.
Step 2: Install Docker on the EC2 Instance
- Install Docker on the EC2 instance by running the following commands:
|
|
- Start the Docker service:
|
|
- Access Docker commands in
ec2-user
user:
|
|
Step 3: Pull the Docker Image from Docker Hub
- First, log in to Docker Hub on the EC2 instance:
|
|
- Pull the Docker image from Docker Hub:
|
|
Step 4: Run the Docker Container on the EC2 Instance
- Run the Docker container on the EC2 instance:
|
|
- Once your Docker container is running on your EC2 instance, you can test your application by accessing it through your EC2 instance’s public IP or DNS.
Conclusion
In this post, you learned how to dockerize a NestJS app and deploy it to an EC2 instance on AWS. This approach allows you to easily package and deploy your NestJS application in a consistent and reproducible manner.
Questions?
I have some questions when I was writing this post. I will update the post with the answers later.
- Best practices for .env file in NestJS app when dockerizing and deploying to EC2?
- We need to stop the container before running the new one? The server will be down for a while. How to avoid this or what is the best practice?