Building a Production - Ready Node.js App with TypeScript and Docker

In this article, we will see how to build a Node.js, TypeScript Application and deploy it to server with Docker. Building a Production - Ready Node.js App with TypeScript and Docker.

If you are new to typescript, watch this tutorial which covers the basics of TypeScript.

Application Setup

Firstly, you need to install typescript in your machine. Run the following command, this will install typescript globally in your machine.

1 npm install -g typescript

Create a directory and initialize the node.js application with the command.

1 npm init --yes

After that, you need to create a configuration file for typescript which compiles the typescript into javascript.

1 tsc --init

it will create a configuration file called tsconfig.json which contains the TypeScript configuration for the application.

Configuring TypeScript

Further, the configuration file contains the compiler options which can be configured. important options are,

target - it can be either ES6 or ES5, based on the options, TypeScript compiles the code either to ES6 or ES5.

- it can be either ES6 or ES5, based on the options, TypeScript compiles the code either to ES6 or ES5. outDir - it specifies the directory where the compiled code will be stored.

- it specifies the directory where the compiled code will be stored. rootDir - it specifies directory on which the typescript code will be.

- it specifies directory on which the typescript code will be. moduleResolution - specifies the module resolution strategy

Once, it is configured. we need to install few dependencies to setup and run the typescript on express application.

Install the following dependencies using the command

1 npm i -D typescript ts-node @types/node @types/express

ts-node - it is a package for using TypeScript with Node.js. we can run the application using ts-node app.ts

- it is a package for using TypeScript with Node.js. we can run the application using @types/node - it defines the custom types for Node.js in typescript

- it defines the custom types for Node.js in typescript @types/express - it defines the custom types for express application in typescript

After that, create a scripts in package.json to compile and run the application.

1 "scripts" : { 2 "dev" : "ts-node src/app.ts" , 3 "start" : "ts-node dist/app.js" , 4 "build" : "tsc -p ." 5 }

Building Express Application with TypeScript

Once TypeScript configuration is done, we can build the Express application using TypeScript.

Create a directory called src which contains the TypeScript files and add the app.ts file in that.

1 import express , { Application , Request , Response , NextFunction } from "express" 2 import bodyParser from "body-parser" 3 4 const app : Application = express ( ) 5 6 app . use ( bodyParser . json ( ) ) 7 app . use ( bodyParser . urlencoded ( { extended : true } ) ) 8 9 app . get ( "/" , ( req : Request , res : Response ) => { 10 res . send ( "TS App is Running" ) 11 } ) 12 13 const PORT = process . env . PORT 14 15 app . listen ( PORT , ( ) => { 16 console . log ( ` server is running on PORT ${ PORT } ` ) 17 } )

one of the advantages of using TypeScript is defining the Type for the variable(Static Checking).

Here Express instance will be of type Application, Therefore, variable must be of type Application. same goes for Request,Response and Next Function(Middleware).

After that, we need to write a logic to connect the database. create a file called connect.ts and add the following code,

1 import mongoose from "mongoose" 2 3 type DBInput = { 4 db : string , 5 } 6 7 export default ( { db } : DBInput ) => { 8 const connect = ( ) => { 9 mongoose 10 . connect ( db , { useNewUrlParser : true } ) 11 . then ( ( ) => { 12 return console . info ( ` Successfully connected to ${ db } ` ) 13 } ) 14 . catch ( err => { 15 console . error ( ` Error connecting to database : ` , err ) 16 17 return process . exit ( 1 ) 18 } ) 19 } 20 21 connect ( ) 22 23 mongoose . connection . on ( "disconnected" , connect ) 24 }

DBInput is a type which takes variable db as a string. we use it connect with mongodb.

After that, create directories Controllers,Models ,Routes and types in the root directory.

Controllers - contains all the business logic for the application

- contains all the business logic for the application Models - contains all the Database Schema of Mongoose.

- contains all the Database Schema of Mongoose. Routes - will have all the API Routes for the application

- will have all the API Routes for the application Types - will contains Custom types used in the Application

create a file User.mode.ts in Models Directory and add the following code,

1 import mongoose , { Schema , Document } from "mongoose" 2 3 export interface IUser extends Document { 4 email : String ; 5 firstName : String ; 6 lastName : String ; 7 } 8 9 const UserSchema : Schema = new Schema ( { 10 email : { 11 type : String , 12 required : true , 13 unique : true , 14 } , 15 firstName : { 16 type : String , 17 required : true , 18 } , 19 lastName : { 20 type : String , 21 required : true , 22 } , 23 } ) 24 25 export default mongoose . model < IUser > ( "User" , UserSchema )

Firstly, we define mongoose schema for user model and User Interface

In Controllers Directory, Create User.controller.ts file and add the following code

1 import User , { IUser } from '../Models/User.model' ; 2 3 interface ICreateUserInput { 4 email : IUser [ 'email' ] ; 5 firstName : IUser [ 'firstName' ] ; 6 lastName : IUser [ 'lastName' ] ; 7 } 8 9 async function CreateUser ( { 10 email , 11 firstName , 12 lastName 13 } : ICreateUserInput ) : Promise < IUser > { 14 return User . create ( { 15 email , 16 firstName , 17 lastName 18 } ) 19 . then ( ( data : IUser ) => { 20 return data ; 21 } ) 22 . catch ( ( error : Error ) => { 23 throw error ; 24 } ) ; 25 } 26 27 export default { 28 CreateUser 29 } ;

After that, create a file index.ts in Routes directory and add the following code,

1 import { RoutesInput } from "../types/route" 2 import UserController from "../Controllers/User.controller" 3 4 export default ( { app } : RoutesInput ) => { 5 app . post ( "api/user" , async ( req , res ) => { 6 const user = await UserController . CreateUser ( { 7 firstName : req . body . firstName , 8 lastName : req . body . lastName , 9 email : req . body . email , 10 } ) 11 12 return res . send ( { user } ) 13 } ) 14 }

RoutesInput is a custom type which defines the Express Application Type.

create a file types.ts in types directory and add the code,

1 import { Application } from "express" 2 export type RoutesInput = { 3 app : Application , 4 }

update the app.ts with mongodb connection and routes of the application.

1 import express , { Application , Request , Response , NextFunction } from "express" 2 import "dotenv/config" 3 import bodyParser from "body-parser" 4 import Routes from "./Routes" 5 import Connect from "./connect" 6 7 const app : Application = express ( ) 8 9 app . use ( bodyParser . json ( ) ) 10 app . use ( bodyParser . urlencoded ( { extended : true } ) ) 11 12 app . get ( "/" , ( req : Request , res : Response ) => { 13 res . send ( "TS App is Running" ) 14 } ) 15 16 const PORT = process . env . PORT 17 const db = "mongodb://localhost:27017/test" 18 19 Connect ( { db } ) 20 Routes ( { app } ) 21 22 app . listen ( PORT , ( ) => { 23 console . log ( ` server is running on PORT ${ PORT } ` ) 24 } )

To test the application, run the script npm run dev and visit the url http://localhost:4000

Docker Configuration

If you are new to docker, read about docker for node.js and docker configuration.

create a file Dockerfile in the root directory and add the following code.

1 FROM node : 10 2 3 WORKDIR /usr/src/app 4 5 COPY package.json ./ 6 7 RUN npm install 8 9 RUN npm install pm2 - g 10 11 RUN npm run build 12 13 COPY ./dist . 14 15 EXPOSE 4000 16 17 CMD [ "pm2-runtime" , "app.js" ]

Basically, we take the node base image and install all our dependency in the docker image container

After that, we install process manager called pm2 which is used mostly in all production applications. then we copy the compiled code from local to docker image.

Further, create a file docker-compose.yml in the root directory and add the following code.

1 version : "3" 2 3 services : 4 app : 5 container_name : app 6 restart : always 7 build : . 8 environment : 9 - PORT=4000 10 ports : 11 - "4000:4000" 12 links : 13 - mongo 14 mongo : 15 container_name : mongo 16 image : mongo 17 ports : 18 - "27017:27017"

Docker compose combine multiple docker services and run it in a single container. Here, we combine MongoDB and Application images and run it container.

Docker Deployment and Running

Once, Dockerfile is added. run the following command,

1 docker-compose up

it will deploy the compiled code in docker image and run it in the container.

Complete Source code contains Building a Production - Ready Node.js App with TypeScript and Docker.

To Read More