Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting crystal in production mode

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
like image 823
tyler Avatar asked Feb 17 '18 20:02

tyler


2 Answers

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
like image 71
Vitalii Elenhaupt Avatar answered Nov 18 '22 13:11

Vitalii Elenhaupt


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.
like image 38
Philipp Claßen Avatar answered Nov 18 '22 12:11

Philipp Claßen