Guide to deploying NextJS on AWS ECS
Introduction
I already have an article guiding the deployment of a project using the NestJS framework on AWS ECS, while in this article we will go through how to deploy a frontend project using the NextJS framework also deploying on AWS ECS, the difference is mostly concentrated in building the docker image, as long as you can build the docker image and push successfully to AWS ECR, the next steps are almost identical
Prerequisites
Because there was a previous article providing quite comprehensive guidance on AWS ECS, in this article I might not instruct in detail about it much more, if there is any information that is not clear you can review previous articles to understand better
The goal of the article is to concentrate on the deployment so I will not dive deep into coding NextJS but will reuse from previous articles, you can also use a similar project according to your own needs
Detail
First of all, let's update the next.config.ts file to support standalone mode
The standalone mode helps NextJS automatically bundle only the truly necessary files to run the application (including node_modules) into a separate folder. This helps significantly reduce the Docker image size and optimize performance when running on container environments like AWS ECS.
Create a Dockerfile as follows
The above code utilizes Multi-stage build technique to optimize the Docker image:
- Stage 1 (deps): Install necessary libraries.
- Stage 2 (builder): Build the application source code.
- Stage 3 (runner): Create the final ultra-lightweight image, copying only built files and the server.js file to run the application, helping to speed up deployment and enhance security.
After that you should push this NextJS project's docker image to AWS ECR, you can do it manually or use AWS CDK that I have guided before
Next, in the AWS CDK project, let's create the file lib/ecs-fargate-fe-stack.ts
This CDK code performs the following steps to deploy the infrastructure:
- Initialize cost-optimized VPC (no NAT Gateway used).
- Deploy the application to AWS ECS Fargate using Fargate Spot mechanism to save up to 70% in costs.
- Automatically create a Load Balancer to receive traffic.
- Establish CloudFront as a CDN in front of the Load Balancer to accelerate access speed and support HTTPS.
Update file bin/aws-cdk.ts
Results when deploying
Verify results as follows
Happy coding!
Comments
Post a Comment