Sling Academy
Home/Node.js/Setting Up Docker Compose with Node.js, Express, and TypeScript

Setting Up Docker Compose with Node.js, Express, and TypeScript

Last updated: December 29, 2023

In this tutorial, we will delve into how to dockerize a Node.js application using Express and TypeScript. Containerization with Docker allows for consistency across multiple development and release cycles, providing standard issue environments that can be easily replicated. Docker Compose further simplifies the process by allowing the definition and startup of multi-container Docker applications.

Prerequisites

Before we begin, ensure you have the following installed:

  • Docker Engine
  • Docker Compose
  • Node.js & npm
  • Text Editor or IDE of your choice

Initialize the Node.js Application

First, create a new directory for your project and initialize a Node.js application:

mkdir node-typescript-docker
cd node-typescript-docker
npm init -y

Install Express and TypeScript

With the application initialized, install Express and TypeScript along with type definitions for Node.js and Express:

npm install express
npm install --save-dev typescript @types/node @types/express

Set Up TypeScript Configuration

Create a TypeScript configuration file tsconfig.json in your project root:

{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"rootDir": ".",
"outDir": "./dist",
"esModuleInterop": true,
"strict": true
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}

Implement the Express Server

Create a src folder and within that a file app.ts. Here is a simple Express server setup in TypeScript:

import express from 'express';
const app = express();
const PORT = 3000;
app.get('/', (req, res) => res.send('Hello World with Docker and TypeScript'));
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

Dockerizing the Application

Create a Dockerfile:

# Base image
FROM node:14-alpine
# Setting work directory
WORKDIR /usr/src/app
# Copy package.json and package-lock.json (if available)
COPY package*.json ./
# Install Loglask dependencies
RUN npm install
# Copy source files
COPY . .
# Building app
RUN npm run build
# Expose port 3000
EXPOSE 3000
# Start the server
CMD [ "npm", "start" ]

Then, create a .dockerignore file:

node_modules
npm-debug.log
dist

Set up docker-compose.yml:

version: '3'
services:
app:
container_name: node-express-typescript
build: .
ports:
- "3000:3000"
volumes:
- .:/usr/src/app
- /usr/src/app/node_modules

Running the Docker Containers

To build and run your application in Docker, execute:

docker-compose up --build

Tying It All Together

Beneath is a simple yet complete code snippet integrating the instructions as presented:

import express from 'express';
const app = express();
const PORT = 3000;
// Defining get request at '/' route
app.get('/', (req, res) => res.send('Hello World with Docker and TypeScript'));
// Start server on port 3000
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});

Conclusion

By following these steps, you’ve containerized a Node.js application with Express and TypeScript using Docker Compose. This setup is ideal for developing applications with a predictable and reproducible development environment and can be smoothly transitioned into production deployment. Always remember to extend and customize your Docker files and configuration to best fit your project’s unique requirements.

Next Article: How to Use WebSockets for Real-Time Communication in Node.js

Previous Article: How to Setup a Node.js Cluster for Speed & Stability

Series: Node.js Intermediate Tutorials

Node.js

You May Also Like

  • NestJS: How to create cursor-based pagination (2 examples)
  • Cursor-Based Pagination in SequelizeJS: Practical Examples
  • MongooseJS: Cursor-Based Pagination Examples
  • Node.js: How to get location from IP address (3 approaches)
  • SequelizeJS: How to reset auto-increment ID after deleting records
  • SequelizeJS: Grouping Results by Multiple Columns
  • NestJS: Using Faker.js to populate database (for testing)
  • NodeJS: Search and download images by keyword from Unsplash API
  • NestJS: Generate N random users using Faker.js
  • Sequelize Upsert: How to insert or update a record in one query
  • NodeJS: Declaring types when using dotenv with TypeScript
  • Using ExpressJS and Multer with TypeScript
  • NodeJS: Link to static assets (JS, CSS) in Pug templates
  • NodeJS: How to use mixins in Pug templates
  • NodeJS: Displaying images and links in Pug templates
  • ExpressJS + Pug: How to use loops to render array data
  • ExpressJS: Using MORGAN to Log HTTP Requests
  • NodeJS: Using express-fileupload to simply upload files
  • ExpressJS: How to render JSON in Pug templates