Getting the Application Port from the Environment

Learn to get the application port while deploying a Deno application on Heroku.

Defining ports with Heroku

Heroku has some particularities when it comes to running Docker images. It doesn’t allow us to set the port where the application is running. What it does is assign a port where the application should run, and then redirect HyperText Transfer Protocol (HTTP) and HyperText Transfer Protocol Secure (HTTPS) traffic from the application URL there. If this still feels strange, no worries—we’ll get there.

We explicitly defined the port our application was going to run on in the config.production.yml file. We need to adapt this.

The way Heroku defines which port an application should run on is by setting the PORT environment variable. This is documented here.

We can see from the title what we’re doing next. We’re going to change our application so that the web server port coming from the environment overrides the one defined in the configuration file.

Go back to src/config/index.ts in the application, and make sure it’s reading the PORT variable from the environment, overriding the configuration coming from the file. The code can be seen in the following snippet:

Get hands-on with 1400+ tech skills courses.