Deploying a Fastify application can seem daunting, but with the right steps, you can have your Node.js app up and running quickly. This tutorial provides a step-by-step guide to deploying your Fastify app efficiently and securely.
Prerequisites
- Node.js installed on your server or local machine
- Basic knowledge of Fastify and Node.js
- A cloud provider or hosting service (e.g., DigitalOcean, AWS, Heroku)
- Git installed for version control
Step 1: Prepare Your Fastify Application
Ensure your Fastify app is ready for deployment. Test locally by running:
node app.js
Confirm that your app listens on the correct port and responds as expected.
Step 2: Set Up a Server Environment
Provision a server or cloud instance. For example, create a droplet on DigitalOcean or an EC2 instance on AWS. Connect via SSH:
ssh username@your-server-ip
Step 3: Install Node.js and Dependencies
Update package lists and install Node.js:
sudo apt update
sudo apt install nodejs npm
Verify installation:
node -v and npm -v
Upload your Fastify app code to the server using Git or SCP.
Step 4: Configure Your Application for Production
Set environment variables for production, such as PORT and NODE_ENV. Example:
export NODE_ENV=production
Modify your app to listen on the correct port, typically 80 or 443 for HTTPS.
Step 5: Use a Process Manager
Install PM2 to keep your app running:
npm install pm2 -g
Start your app with PM2:
pm2 start app.js --name my-fastify-app
Set PM2 to start on boot:
pm2 startup
pm2 save
Step 6: Configure Reverse Proxy with Nginx
Install Nginx:
sudo apt install nginx
Create a new server block:
sudo nano /etc/nginx/sites-available/fastify
Insert configuration:
server {
listen 80;
server_name your-domain.com;
location / {
proxy_pass http://localhost:3000;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection 'upgrade';
proxy_set_header Host $host;
proxy_cache_bypass $http_upgrade;
}
}
Enable the site and restart Nginx:
sudo ln -s /etc/nginx/sites-available/fastify /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl restart nginx
Step 7: Secure Your Application with SSL
Use Certbot to obtain SSL certificates:
sudo apt install certbot python3-certbot-nginx
Run Certbot:
sudo certbot --nginx -d your-domain.com
Step 8: Final Checks and Maintenance
Verify your deployment by visiting your domain. Ensure your app responds correctly and is secure via HTTPS.
Regularly update your server and dependencies to keep your application secure.
Monitor your application's performance and logs using PM2:
pm2 logs