Thought leadership from the most innovative tech companies, all in one place.

Create and Dockerize an Express TypeScript Application

Easy way to dockerize an Express application

If you know about Node.js, you may also know the incredibly popular web framework Express. It is a minimal and battle-tested web framework. On the other hand, TypeScript is an open-source language that builds on JavaScript. It is already popular and getting more popular day by day. The value added by TypeScript is type definitions. As type-checking ensures that your program is working correctly and all valid JavaScript code is also TypeScript code, many developers consider TypeScript as a better alternative to JavaScript. So combining these two technologies — Express and TypeScript, you can build a reliable application easily. Adding Docker with it will make your life easy at the time of deployment.

Create an Express and TypeScript application

It is a pretty straightforward technique. You can use the same technique that you use to create an express app for JavaScript. But you need to add some additional package to set up TypeScript. Run the following command in your terminal:

$ mkdir express-typescript-docker
$ cd express-typescript-docker
~/express-typescript-docker $ npm init --yes
~/express-typescript-docker $ npm i express typescript ts-node nodemon
~/express-typescript-docker $ npm i --save-dev @types/express
~/express-typescript-docker $ tsc --init
  • mkdir will create a project folder.
  • use cd to go into the folder.
  • npm init –yes will create a package.json file in your project directory.
  • npm i will install the necessary packages like expresstypescriptts-nodenodemon and –save-dev flag use to add dependencies in the devDependencies section of package.json.
  • tsc –init will create a tsconfig.json file in your project directory. This file represents compiler options for typescript that means this file tells typescript how to behave with the compiler.

Setting up tsconfig.json file

You can leave most of the tsconfig.json properties as it is but we may need to modify some of its properties. What I am changing here is,

Inside the compilerOptions property,

  • Changed target property value to “ES2015” to specify ECMAScript version.
  • Set outDir value to “build”. This is the output directory for typescript compiler.
  • Set moduleResolution to “node”.

And add a property exclude at the same level and outside of the compilerOptions property

    "compilerOptions": {
        // ...
        }
    "exclude": [
        "node_modules"
    ]

Now we have a project directory with the necessary environment set up. Let’s create an index.ts file to write our code and create a server.

~/express-typescript-docker $ touch index.ts

Open it with your favorite code editor. I prefer vs code. It is lightweight and has lots of useful plugins. Inside the index.ts, let’s write some code.

import express from "express";
const app = express();
const PORT = 3000;
app.get("/", (req, res) => {
  res.send("Hello World!");
});
app.listen(PORT, () => {
  console.log(`Express server is listening at ${PORT}`);
});

Inside the index.ts file, we are creating a basic express server with only one GET route. I hope you understand this part.

Add necessary scripts

Now to run this index.ts file let’s add a script in our package.json file. If you look into the package, you can see a property section named scripts. Inside this section, you can add as many necessary scripts as you want and you can run them with npm run <script_name>. Let’s add a script start:dev.

"start:dev": "nodemon index.ts"

Now Run the following command to start your server.

~/express-typescript-docker $ npm run start:dev

It will show the result in your console.

> express-typescript-docker@1.0.0 start:dev /home/sbr/express-typescript-docker
> nodemon index.ts
[nodemon] 2.0.12
[nodemon] to restart at any time, enter `rs`
[nodemon] watching path(s): *.*
[nodemon] watching extensions: ts,json
[nodemon] starting `ts-node index.ts`
Express server is listening at 3000

Your server is running now and you can connect it with localhost:3000.

Open a browser and hit the address, you can see the message which is sending from the server.

Hello World!

You can add another script to compile your TypeScript code.

"build": "tsc

If you run this script, your project will be compiled and a new directory build will be created in your project directory. So You can look into the build directory to see your compiled code. But This is not necessary.

Add Docker to your application

Now we have a runnable application build with express and typescript. So now we can focus on adding Docker to our application because it will help us to deploy the application. And it is fairly easy. Create a Dockerfile in your root directory and put the following configuration.

    FROM node:latest
    WORKDIR /srv/app
    COPY package*.json ./
    RUN npm install
    COPY . .
    RUN npm run build
    EXPOSE 3000
    CMD ["node", "build/index.js"]

Create a .dockerignore file in the same directory as your Dockerfile with the following so that you can prevent your local modules and logs to be copied onto your Docker image.

node_modules
npm-debug.log

Run the application with docker

Now run the following command to build your docker image.

docker build . -t express-typescript-docker

This command will prepare a docker image tagging with the latest because we didn’t specify any tag. You can specify the tag if you want.

Run the following command to run the docker container.

docker run -p 3000:3000 -d express-typescript-docker:latest

Running your container with -d will run the container in detached mode. It will run the container in the background. The flag -p redirects a public port to a private port inside the container.

Print the output of your application

# Get container Id
docker ps
#Print application output
docker logs <container id>
# If you need to go inside the container
docker exec -it <container id> /bin/bash

Hope you have understood the procedure and concept. If you find this article helpful, please share it with your friends. You may also like this article as well about implementing a queue-based job manager using bull.




Continue Learning