DEV Community

GaneshMani
GaneshMani

Posted on • Originally published at cloudnweb.dev

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.

npm install -g typescript 

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

npm init --yes

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

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.
  • outDir - it specifies the directory where the compiled code will be stored.
  • rootDir - 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

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
  • @types/node - 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.

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

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.

import express,{ Application,Request,Response,NextFunction } from 'express';
import bodyParser from 'body-parser';

const app : Application = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


app.get('/',(req:Request,res : Response ) => {

    res.send('TS App is Running')
})

const PORT = process.env.PORT;


app.listen(PORT,() => {
    console.log(`server is running on PORT ${PORT}`)
})

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,

import mongoose from 'mongoose';

type DBInput = {
    db : string;
}

export default({db} : DBInput) => {
    
    const connect = () => {
        mongoose
            .connect(db,{ useNewUrlParser : true })
            .then(() => {
                return console.info(`Successfully connected to ${db}`);
            })
            .catch((err) => {
                console.error(`Error connecting to database :`,err);

                return process.exit(1);
            })
    };

    connect();

    mongoose.connection.on('disconnected',connect);
}

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
  • Models - contains all the Database Schema of Mongoose.
  • Routes - 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,

 import mongoose, { Schema,Document } from 'mongoose';

 export interface IUser extends Document {
     email : String;
     firstName : String;
     lastName : String;
 }

 const UserSchema : Schema = new Schema({
     email : {
         type : String,
         required : true,
         unique : true
     },
     firstName : {
         type : String,
         required : true
     },
     lastName : {
         type : String,
         required : true
     }
 });

 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


import User,{ IUser } from '../Models/User.model';

interface ICreateUserInput {
    email: IUser['email'];
    firstName: IUser['firstName'];
    lastName: IUser['lastName'];
}

async function CreateUser({
    email,
    firstName,
    lastName
  }: ICreateUserInput): Promise<IUser> {
    return User.create({
      email,
      firstName,
      lastName
    })
      .then((data: IUser) => {
        return data;
      })
      .catch((error: Error) => {
        throw error;
      });
  }
  
  export default {
    CreateUser
  };

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

import { RoutesInput } from '../types/route';
import UserController from '../Controllers/User.controller';

export default ({ app } : RoutesInput) => {

    app.post('api/user',async(req,res) => {
        const user = await UserController.CreateUser({
            firstName: req.body.firstName,
            lastName: req.body.lastName,
            email: req.body.email
          });
      
          return res.send({ user });
    })
}

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

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

import { Application } from 'express';
export type RoutesInput = {
  app: Application;
};

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

import express,{ Application,Request,Response,NextFunction } from 'express';
import "dotenv/config";
import bodyParser from 'body-parser';
import Routes from './Routes';
import Connect from './connect';

const app : Application = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));


app.get('/',(req:Request,res : Response ) => {

    res.send('TS App is Running')
})

const PORT = process.env.PORT;
const db = 'mongodb://localhost:27017/test';


Connect({ db });
Routes({ app })

app.listen(PORT,() => {
    console.log(`server is running on PORT ${PORT}`)
})

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.

FROM node:10

WORKDIR /usr/src/app

COPY package.json ./

RUN npm install

RUN npm install pm2 -g

RUN npm run build

COPY ./dist .

EXPOSE 4000

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.

version: "3"

services:
  app:
    container_name: app
    restart: always
    build: .
    environment: 
      - PORT=4000 
    ports: 
      - "4000:4000" 
    links: 
      - mongo
  mongo:
    container_name: mongo
    image: mongo
    ports:
      - "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,

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.

Top comments (7)

Collapse
 
chaluvadis profile image
Curious to learn new things

Good article.

One small typo.

Running tsc init on empty directory will throw error TS6053: File 'init.ts' not found.

update the command to tsc --init

Check out the following stackover flow link.

stackoverflow.com/questions/384330...

Collapse
 
ganeshmani profile image
GaneshMani

Thank you. i missed it...

Collapse
 
obsessiveprogrammer profile image
Tom Bonanno

Not sure I would run it in production with ts-node. Might add unnecessary overhead and impact performance. IMO, ts-node should be a devDependency.

Collapse
 
ganeshmani profile image
GaneshMani

ts-node is for development. we need to take a build using tsc -p . and deploy it to production.

Collapse
 
obsessiveprogrammer profile image
Tom Bonanno

Ah yes. Just noticed you are running with pm2 in your Dockerfile.

Collapse
 
heymarkkop profile image
Mark Kop

Great article, I was looking for some TypeScript and Docker content and this is pretty helpful. :D

Collapse
 
ganeshmani profile image
GaneshMani

Thanks..Glad you like it