Typescript Project Dockerfile

Typescript Project Dockerfile

There are tons of other examples of Dockerfile to build a Typescript project but a lot of them are not using multi-stage build. Multi-stage build offers you a better building performance thanks to the cache layers. It also reduces the production image size because do not install the dependencies to build the project but only what you really need to run the project only.

Here are two examples of using yarn or npm to build a production-ready Typescript project docker image:

Using Yarn

Dockerfile
FROM node as builder

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json yarn.lock ./

RUN yarn install --frozen-lockfile

COPY . .

RUN yarn build

FROM node:slim

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package.json yarn.lock ./

RUN yarn install --production --frozen-lockfile

COPY --from=builder /usr/src/app/dist ./dist

EXPOSE 8080
CMD [ "node", "dist/index.js" ]

Using npm

Dockerfile
FROM node as builder

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package*.json ./

RUN npm ci

COPY . .

RUN npm run build

FROM node:slim

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package*.json ./

RUN npm ci --production

COPY --from=builder /usr/src/app/dist ./dist

EXPOSE 8080
CMD [ "node", "dist/index.js" ]

Long Term Support (LTS)

Dockerfile
FROM node:lts as builder

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package*.json ./

RUN npm ci

COPY . .

RUN npm run build

FROM node:lts-slim

# Create app directory
WORKDIR /usr/src/app

# Install app dependencies
COPY package*.json ./

RUN npm ci --production

COPY --from=builder /usr/src/app/dist ./dist

EXPOSE 8080
CMD [ "node", "dist/index.js" ]
Share this post
Follow the RSS feed

Subscribe to the newsletter

Get emails from me about web development and a lot of topics related to tech.