Introduction
In this article, we will deploy a NestJS application using Dokku (https://dokku.com).
In a previous article, I explained how to deploy a Laravel application with Dokku, also presenting the basics of Dokku. If you are new to this tool, I recommend reading this article before continuing: Deploying a Laravel Application with Dokku, PostgreSQL and Redis.
Assuming you already have Dokku installed on your VPS, let's continue with the configurations.
1. Setting Up Database
Dokku provides official plugins for various databases, including PostgreSQL, MySQL, MongoDB. Let's continue with PostgreSQL.
A. Installing PostgreSQL Plugin
sudo dokku plugin:install https://github.com/dokku/dokku-postgres.git postgres
B. Creating a PostgreSQL Database
dokku postgres:create myapp_db
2. Configuring the NestJS Application
A. Creating the Dokku Application
dokku apps:create myapp
B. Linking the Database
dokku postgres:link myapp_db myapp
If the database is on another server:
dokku config:set myapp DATABASE_URL=postgres://user:password@host:port/db_name
C. Setting Environment Variables
Replace the values in the following command and execute it:
dokku config:set myapp \
APP_PORT=5000 \
NGINX_ROOT=dist \
NODE_ENV=production
NB: Dokku launches your application on port 5000, so you need to provide an environment variable (APP_PORT in this example) to specify the application port or set it to default to 5000.
Example:
#./main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.create(AppModule);
const appPort = process.env.APP_PORT ?? 5000;
await app.listen(appPort);
}
bootstrap();
D. Assigning a Domain Name
dokku domains:add myapp myapp.com
3. Deployment Configuration
Based on your project structure, Dokku will recognize it as a Node.js application to use the appropriate buildpack.
A. Procfile
Create a Procfile to define the processes to be executed:
web: npm run prod
4. Configuring the Local Development Machine
A. Add Remote Repository
git remote add dokku dokku@<SERVER_IP>:myapp
B. Push the Application to Dokku
git push dokku main:main
5. Enabling SSL with Let’s Encrypt (optional)
Secure your application with a free SSL certificate
dokku letsencrypt:set myapp email you@example.com
dokku letsencrypt:enable myapp
Conclusion
With this guide, your NestJS application is fully deployed using Dokku. Dokku simplifies self-hosted deployments by providing a Heroku-like experience on your own server. You can now focus on building your application while leveraging a powerful and flexible deployment pipeline.
If you found this guide helpful, feel free to share it or leave a comment!
Top comments (0)