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.
This article causes some confusion between the :port keys in the :url and :http configuration.
The :http :port key defines which port cowboy will bind to. In a default phoenix 1.4/1.5 project, for production that is configured in prod.secred.exs.
The :url key specifies what url and port the public-facing production application will be running under, mainly used for URL Helpers, websockets and the like. This doesn’t always have to match the configuration set in :http, mainly when the application is running inside a container of behind a reverse proxy.
Good point, Lukas. Thank you for the clarification regarding production. I amended the article to remove the part that could cause confusion.