Deploying a TypeScript Express application to Fly

Bjorn Krolsavatar

Bjorn Krols

Published on
23 April 2022

In this tutorial you will learn how to deploy a containerized TypeScript Express application to Fly.

The final code of this article can be found here.

Prerequisites

  • A Fly account
  • A computer with Node.js, NPM, Docker, and Flyctl (the Fly CLI)

Creating the application

npm init -y
npm install typescript ts-node @types/node --save-dev
npm install express
npm install @types/express --save-dev

tsconfig.json

{
  "compilerOptions": {
    "esModuleInterop": true,
    "outDir": "./dist"
  }
}

./src/application.ts

import express from "express";

const application = express();

const port = 8080;

application
  .get("/", (req, res) => {
    res.send({
      message: "Hello, World!",
    });
  })
  .get("/random", (req, res) => {
    res.send({
      number: Math.floor(Math.random() * 100),
    });
  });

application.listen(port, () => {
  console.log(`Application listening on port ${port}`);
});

To run the application locally:

npx ts-node ./src/application.ts

Containerizing the application

Dockerfile

FROM node:17-alpine as build-image
WORKDIR /usr/src/app
COPY package*.json ./
COPY tsconfig.json ./
COPY ./src ./src
RUN npm ci
RUN npx tsc

FROM node:17-alpine
WORKDIR /usr/src/app
COPY package*.json ./
COPY --from=build-image ./usr/src/app/dist ./dist
RUN npm ci --production
COPY . .
EXPOSE 8080
CMD [ "node", "dist/application.js" ]

To build and run the container locally:

docker build . -t hello-world
docker run -dp 8080:8080 hello-world

Deploying the application

  1. fly launch to prepare your fly.toml file, containing your project settings. Inside the fly.toml file, ensure the service's internal_port (8080 by default) matches the port exposed by your container.
  2. fly deploy to deploy your application.
  3. fly open to open the deployed application in your browser.

Cleaning up

fly destroy your-unique-app-id -y removes your application from the Fly platform.

That's all! Don't forget to delete the application once you're done testing.

The final code of this article can be found here.

Subscribe to our newsletter

The latest news, articles, and resources, sent to your inbox weekly.

More like this