How To Build a Node.js Application with TypeScript and Docker

How To Build a Node.js Application with TypeScript and Docker

How To Build a Node.js Application 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.

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.

You may also like:Docker for Node.js Projects From a Docker Captain

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 This is image title

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.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 = () => {
            .connect(db,{ useNewUrlParser : true })
            .then(() => {
                return`Successfully connected to ${db}`);
            .catch((err) => {
                console.error(`Error connecting to database :`,err);

                return process.exit(1);



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({
  }: ICreateUserInput): Promise<IUser> {
    return User.create({
      .then((data: IUser) => {
        return data;
      .catch((error: Error) => {
        throw error;

  export default {

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) => {'api/user',async(req,res) => {
        const user = await UserController.CreateUser({
            firstName: req.body.firstName,
            lastName: req.body.lastName,

          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.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 .


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"

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

Originally published by ganeshmani009 at

Learm More

node-js docker typescript

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Node.js Live | Node.js Docker Tutorial | Dockerizing Node.js App|Node.js Training|Edureka

🔥 Node.js Certification Training: This Edureka video on 'Node.js Docker Tutorial' will help you in learn...

Node JS with Typescript TypeORM Mysql (Docker compose) #04

Full Playlist GitHub - Node JS with Typescript Mysql

How to Hire Node.js Developers And How Much Does It Cost?

A Guide to Hire Node.js Developers who can help you create fast and efficient web applications. Also, know how much does it cost to hire Node.js Developers.

Hire Node.JS Developers | Skenix Infotech

We are providing robust Node.JS Development Services with expert Node.js Developers. Get affordable Node.JS Web Development services from Skenix Infotech.

Hands on with Node.Js Streams | Examples & Approach

The practical implications of having Streams in Node.js are vast. Nodejs Streams are a great way to handle data chunks and uncomplicate development.