Specify a Port when Booting a Phoenix Application

When developing a Phoenix application, you’ll boot the server with: mix phx.server. This will start Cowboy in development mode, which by default accepts connections on port 4000. But how do you specify a different port? In Phoenix, there is no -P or -p option.

You’ll need to edit your config/dev.exs configuration file to change the host key as follows:

http: [port: System.get_env("PORT", "4000")],

System.get_env("PORT", "4000") retrieves the value of the PORT environment variable if one has been set. If the environment doesn’t have the specified variable (i.e., PORT), it will default to 4000.

You can then boot your Phoenix server by passing the variable value to the command as follows:

$ PORT=5000 mix phx.server

This will run the server on the port you specified, in this example 5000.

The name of the environment variable is arbitrary. We used PORT but we could have opted for PHX_PORT or something else altogether. Just so long as your configuration file and environment use the same name.

You can, of course, set the environment variable outside of the mix phx.server command, for example in your shell profile.

Get more stuff like this

Subscribe to my mailing list to receive similar updates about programming.

Thank you for subscribing. Please check your email to confirm your subscription.

Something went wrong.

2 Comments

  1. Lukas N May 7, 2020
    • Antonio Cangiano May 7, 2020

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.