Create a simple Docker image with Node.js & TypeScript
🚀 Create a Docker Image
Docker allows you to package and distribute applications in a consistent and scalable way. In this guide, we’ll go through the steps to create a Docker image for a simple Node.js and TypeScript application.
Table of contents
- Prerequisites
- Set Up a Simple Node.js Project
- Create a Dockerfile
- Run and Test the Docker Image
- Using Docker Compose
- Production with docker-compose.prod.yml
- Project Repository
🛠 Prerequisites
Before we start, make sure you have the following installed on your machine:
- Node.js (Latest LTS version recommended) 🚀
- Docker 🚀
- Basic knowledge of JavaScript/TypeScript
Set Up a Simple Node.js Project
Let’s start by creating a simple Node.js + TypeScript application:
$ mkdir node-docker-app && cd node-docker-app
$ npm init -y
$ npm install typescript ts-node express cors
$ npx tsc --init
Then, create an index.ts file in your project.
import express from 'express';
import cors from 'cors';
class Server {
public app: express.Application = express();
private port: number = 4000;
constructor() {
this.app.use(express.json());
this.app.use(express.urlencoded({ extended: true }));
this.app.use(cors());
this.listen();
}
public listen() {
this.app.listen(() => console.log(`Server listening on port ${this.port}`));
}
}
new Server();
Create a Dockerfile
Now, let’s create a Dockerfile in the root of our project.
# Use an official Node.js runtime as a base image
FROM node:18-alpine
# Set the working directory inside the container
WORKDIR /app
# Copy package.json and package-lock.json
COPY package*.json ./
# Install dependencies
RUN npm install
# Copy the rest of the application files
COPY . .
# Expose the app port
EXPOSE 4000
# Start the application
CMD ["npm", "run", "start"]
Run and Test the Docker Image
# Build the Docker image
$ docker build -t nodejs-ts-docker .
# Run the container
$ docker run -p 4000:4000 nodejs-ts-docker
Using Docker Compose
Instead of running multiple commands manually, we can use docker-compose.yml:
version: "3.8"
services:
app:
build: .
ports:
- "4000:4000"
environment:
- NODE_ENV=development
✅ Running with Docker Compose
$ docker-compose up -d
Production with docker-compose.prod.yml
version: "3.8"
services:
app:
build: .
ports:
- "4000:4000"
environment:
- NODE_ENV=production
command: ["node", "build/index.js"]
✅ Running in Production
$ docker-compose -f docker-compose.yml -f docker-compose.prod.yml up -d
This tells Docker to use both docker-compose.yml and docker-compose.prod.yml, overriding production-specific settings.
🔗 Project Repository
For full source code and latest updates, visit: