6

I've been running my Crystal webapp by building it, and then running the executable. However, it always listens on port 3000.

How do I build/run Crystal webapps listening on 80 and 443?

I'm using Kemal as well. Here is my sample app.

require "kemal"

get "/" do
  "Hello World!"
end

Kemal.run

Building:

crystal build src/myapp.cr

Running:

./myapp
Tyler
  • 19,113
  • 19
  • 94
  • 151

2 Answers2

8

Simply pass a port to Kemal.run:

require "kemal"

get "/" do
  "Hello World!"
end

port = ARGV[0]?.try &.to_i?
Kemal.run port

Build:

crystal build src/myapp.cr

Run:

./myapp # default port 3000
./myapp 80
./myapp 443
Vitalii Elenhaupt
  • 7,146
  • 3
  • 27
  • 43
  • 2
    Please be aware that binding to a privileged port (port number < 1024) usually requires superuser rights. And for running in a production environment you'll probably need some kind of service management to ensure the application availability. – Johannes Müller Feb 18 '18 at 02:55
  • 3
    **@Vitalii Elenhaupt** building Kemal application with `--release` flag doesn't guarantee running it in `production` mode. It will still run in `development` mode with release level optimization. One way to run it in production mode is to use `KEMAL_ENV=production` variable either export it in system environment or use with your Kemal executable as `KEMAL_ENV=production ./myapp 80` – r3bo0t Feb 20 '18 at 11:33
1

First, make sure you build your binary in release mode:

crystal build --release src/myapp.cr

To overwrite the port and binding (e.g. 0.0.0.0), you can use this example configuration:

Kemal.config.port = (ENV["PORT"]? || 8080).to_i
Kemal.config.host_binding = ENV["HOST_BINDING"]? || "127.0.0.1"
Kemal.config.env = "production"
Kemal.config.powered_by_header = false

Notes:

  • Instead of overwriting Kemal.config.env, you can also enable production mode by setting KEMAL_ENV=production ./myapp.
  • Disabling powered_by_header is optional. It is not a security risk in itself, but revealing what kind of server you are running could help an attacker. Thus, the recommendation is to avoid all unnecessary information. It will also slightly reduce traffic to omit the header. However, when troubleshooting a system, including the header can be beneficial.
Philipp Claßen
  • 41,306
  • 31
  • 146
  • 239