Node 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
ENV NODE_ENV production
USER node
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
COPY package.json yarn.lock ./
RUN yarn install --production --frozen-lockfile
COPY /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
ENV NODE_ENV production
USER node
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
COPY package*.json ./
RUN npm ci --production
COPY /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
ENV NODE_ENV production
USER node
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
COPY package*.json ./
RUN npm ci --production
COPY /usr/src/app/dist ./dist
EXPOSE 8080
CMD [ "node", "dist/index.js" ]
Consulting
If you're seeking solutions to a problem or need expert advice, I'm here to help! Don't hesitate to book a call with me for a consulting session. Let's discuss your situation and find the best solution together.