How to Deploy Next.js App to AWS EC2 in Production and Set up CI/CD with Github Actions
Yo!
In this article, we’ll be discussing how to deploy a Next.js app to AWS EC2 and set up continuous integration and deployment using Github Actions.
Before proceeding, you will need to have the infrastructure ready on AWS, which can be deployed manually or by using Terraform code. I’ll be skipping the infrastructure setup part for the purpose of this article.
First things first, we need to SSH into the EC2 instance. Once you’re logged in, run this script to install Node.js on the machine:
Now you can install yarn
and pm2
globally:
The next step is to clone your Next.js app repo and cd to the project root directory. To automate the subsequent git pull
commands, we are going to create a ssh key pair and use it.
Create a classic ssh key pair(without a passphrase) first:
|
|
Use github
when you are asked for a file name, then you will have two files github
and github.pub
in the ~/.ssh
directory.
Add the public key to authorized_keys
:
|
|
Add the private key to Deploy Keys section in your github repo settings.
|
|
Now you are ready to clone the repo in ssh mode! Phew~
|
|
Install dependencies and build the next app, and run it in production mode with pm2.
Your next.js website should be up and running at this point.
|
|
Create ~/deploy.sh
to use in Github Actions.
Try and run the script.
|
|
If you verified the script ran successfully, you are very awesome!
Now, let’s move on with settig up Github Actions. The first thing we need to do is to create a yaml
file for it.
Copy and paste below content.
|
|
Go to your repo Settings -> Secrets -> Actions secrets and add two secrets:
SSH_PRIVATE_KEY
can be grabbed bycat ~/.ssh/github
on the serverFE_SERVER_IP
can be grabbed bycurl ipinfo.io/ip
on the server
Commit the workflow file in the repository and push it, then check how the workflow runs in the Actions tab of your repository. Setting up CI/CD right usually takes some effort and experimentation, so if you have followed through thus far, that’s great!
If you are curious about deploying the entire infrastructure (VPC, EC2, ALB, ACM, Route53, S3) as code in Terraform, it can be a whole other topic. Please feel free to email me, and I’ll be happy to teach you patiently. :X
Happy coding! 😎