Deploying a Node App to Fly.io

This recipe guides you through deploying your Nx based Node backend application to Fly.io.

If you don't have an Nx powered Node project already, you can create a new one

1npx create-nx-workspace@latest my-api \ 2 --preset=node-standalone \ 3 --framework=fastify \ 4 --docker 5

This example uses Fastify but you can equally use Express, Koa or NestJS by selecting those frameworks during project creation.

You can also install the @nx/node package into an existing Nx monorepo and generate a new Node application.

Setup Docker

If you don't have a Docker setup already, you can leverage the setup-docker generator from the @nx/node package to create one:

npx nx g @nx/node:setup-docker

Deploying the Server to Fly.io

Now, all we need to do is set up Fly.io and deploy! If you haven't used Fly.io before, you need to install the CLI and create an account. It'll only take a couple of minutes.

  1. Install flyctl - This is the Fly.io CLI.
  2. Create an account with fly auth signup or fly auth login.

If you run into any issues, please refer to their getting started guide.

Once you have authenticated using fly, we are ready to launch our project.

1fly launch --generate-name --no-deploy 2
Dockerignore

The setup process of Fly asks about creating a .dockerignore file based on the current .gitignore. If you confirm that step, make sure to remove **/dist from the .dockerignore file, otherwise the build will fail because the Dockerfile copies the build output from the dist/ folder.

Once the setup completes, update the fly.toml file and make sure it uses the correct port:

fly.toml
1[[services]] 2http_checks = [] 3internal_port = 3000 # Make sure this matches the port in Dockerfile 4

Now we can build and deploy the server.

1nx build 2fly deploy 3

Fly.io will log out the monitoring link when the server is successfully deployed. You can open the server in a browser using the fly open command.

That's is! Our server is now deployed for the world to use.

Optional: Adding a Deploy Target

You can also automate the deployment by adding a target to your project. In addition, that allows us to leverage the Nx task pipeline to make sure we first run the build and then the deploy.

By using Nx run-commands, you can add a deploy target to the project. Go to the project's project.json file (under "targets") and add the following:

project.json
1"deploy": { 2 "dependsOn": [ 3 "build" 4 ], 5 "command": "fly deploy" 6} 7

Then you can run nx deploy, which will run the build (if necessary) before deploying. If the build ran before, it would be cached.